Description
“余”人国的国王想重新编制他的国家。他想把他的国家划分成若干个省,每个省都由他们王室联邦的一个成
员来管理。他的国家有n个城市,编号为1..n。一些城市之间有道路相连,任意两个不同的城市之间有且仅有一条
直接或间接的道路。为了防止管理太过分散,每个省至少要有B个城市,为了能有效的管理,每个省最多只有3B个
城市。每个省必须有一个省会,这个省会可以位于省内,也可以在该省外。但是该省的任意一个城市到达省会所经
过的道路上的城市(除了最后一个城市,即该省省会)都必须属于该省。一个城市可以作为多个省的省会。聪明的
你快帮帮这个国王吧!
Input
第一行包含两个数N,B(1<=N<=1000, 1 <= B <= N)。接下来N-1行,每行描述一条边,包含两个数,即这
条边连接的两个城市的编号。
Output
如果无法满足国王的要求,输出0。否则输出数K,表示你给出的划分方案中省的个数,编号为1..K。第二行输
出N个数,第I个数表示编号为I的城市属于的省的编号,第三行输出K个数,表示这K个省的省会的城市编号,如果
有多种方案,你可以输出任意一种。
Sample Input
8 2
1 2
2 3
1 8
8 7
8 6
4 6
6 5
1 2
2 3
1 8
8 7
8 6
4 6
6 5
Sample Output
3
2 1 1 3 3 3 3 2
2 1 8
2 1 1 3 3 3 3 2
2 1 8
HINT
Source
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~dfs~
这一道题就是树上莫队中摘出的一个操作嘛……
啊,水题的快感……
我们dfs遍历这棵树,每个元素入栈,如果u的子树大于等于B,则把它的子树划为一块,u就是首都(u不在该块中);每次遍历完子树后把u加入栈中,最后剩余的点数<=B+1,直接加到最后划分出的一个块中。
需要注意的是如果最后没有划分出块,是无解的情况,输出'0'。
#include<cstdio>
int n,b,fi[1001],w[2001],ne[2001],stk[1001],top,tot,cnt,pos[1001],num[1001];
int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
while(ch>='0' && ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return x*f;
}
void add(int u,int v)
{
w[++cnt]=v;ne[cnt]=fi[u];fi[u]=cnt;
w[++cnt]=u;ne[cnt]=fi[v];fi[v]=cnt;
}
void dfs(int u,int fa)
{
int now=top;
for(int i=fi[u];i;i=ne[i])
if(w[i]!=fa)
{
dfs(w[i],u);
if(top-now>=b)
{
tot++;
while(top-now) pos[stk[top--]]=tot;
num[tot]=u;
}
}
stk[++top]=u;
}
int main()
{
n=read();b=read();
for(int i=1;i<n;i++) add(read(),read());
dfs(1,0);
if(top)
{
if(!tot)
{
printf("0\n");
return 0;
}
while(top) pos[stk[top--]]=tot;
}
printf("%d\n",tot);
for(int i=1;i<=n;i++) printf("%d ",pos[i]);printf("\n");
for(int i=1;i<=tot;i++) printf("%d ",num[i]);
return 0;
}