orz POPOQQQ。。。好评!
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxv 1050 #define maxe 2050 using namespace std; int n,b,x,y,g[maxv],nume=0,stack[maxv],top=0,root[maxv],cnt=0,bel[maxv]; struct edge { int v,nxt; }e[maxe]; void addedge(int u,int v) { e[++nume].v=v; e[nume].nxt=g[u]; g[u]=nume; } void dfs(int x,int fath) { int bottom=top; for (int i=g[x];i;i=e[i].nxt) { int v=e[i].v; if (v==fath) continue; dfs(v,x); if (top-bottom>=b) { root[++cnt]=x; while (top!=bottom) bel[stack[top--]]=cnt; } } stack[++top]=x; } int main() { scanf("%d%d",&n,&b); for (int i=1;i<=n-1;i++) { scanf("%d%d",&x,&y); addedge(x,y);addedge(y,x); } dfs(1,0); while (top) bel[stack[top--]]=cnt; printf("%d\n",cnt); for (int i=1;i<=n;i++) printf("%d ",bel[i]);printf("\n"); for (int i=1;i<=cnt;i++) printf("%d ",root[i]);printf("\n"); return 0; }