比較有意思的題目,聽說這是樹分塊的裸題?
我們開一個棧,遍歷一個節點,若該節點的幾棵子樹的大小>=B,那麼就把他們分到一塊,省會爲當前節點
這樣做會剩下不到B個節點,這時候就利用棧傳到上一層節點就可以
最後會剩下不到B個節點,因爲我們原來的塊都是一定不超過2B的,於是把這B個節點放到最後一個塊就可以
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#define maxn 2010
using namespace std;
int head[maxn],to[maxn],next[maxn];
int st[maxn],root[maxn],bel[maxn];
int n,m,num,b,cnt,top;
void addedge(int x,int y)
{
num++;to[num]=y;next[num]=head[x];head[x]=num;
}
void dfs(int x,int fa)
{
int now=top;
for (int p=head[x];p;p=next[p])
if (to[p]!=fa)
{
dfs(to[p],x);
if (top-now>=b) {root[++cnt]=x;while (top!=now) bel[st[top--]]=cnt;}
}
st[++top]=x;
}
int main()
{
scanf("%d%d",&n,&b);
for (int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
addedge(x,y);addedge(y,x);
}
dfs(1,0);
while (top) bel[st[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;
}