对树dfs,每次dfs完儿子,如果不小于块大小的下限,那么就独立成块。用栈维护。
#include <cstdio>
#define N 1010
struct edge {int to, next;}e[N<<1];
int n, B, head[N], cnt = 1, vis[N];
inline void ins(int x, int y) {e[++cnt].to = y; e[cnt].next = head[x]; head[x] = cnt;}
inline void init() {
scanf("%d%d", &n, &B);
for(int i = 1; i < n; ++i) {int x, y; scanf("%d%d", &x, &y); ins(x, y); ins(y, x);}
}
int top = 0, stack[N], bcnt = 0, root[N], belong[N];
void dfs(int x) {
vis[x] = 1; int cnt = top;
for(int i = head[x]; i; i = e[i].next) {
int y = e[i].to;
if(!vis[y]) {
dfs(y);
if(top - cnt >= B) {
bcnt++;
root[bcnt] = x;
while(top != cnt) belong[stack[top--]] = bcnt;
}
}
}
stack[++top] = x;
}
inline void output() {
while(top) belong[stack[top--]] = bcnt;
printf("%d\n", bcnt);
for(int i = 1; i <= n; ++i) printf("%d ", belong[i]); puts("");
for(int i = 1; i <= bcnt; ++i) printf("%d ", root[i]);
}
int main() {
init(); dfs(1); output();
return 0;
}