1086: [SCOI2005]王室联邦
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
http://blog.csdn.net/popoqqq/article/details/42772237
1 #include<iostream> 2 #include<cstdlib> 3 #include<cmath> 4 #include<cstring> 5 #include<cstdio> 6 #include<algorithm> 7 #include<string> 8 #include<map> 9 #include<queue> 10 #include<vector> 11 #include<set> 12 #define inf 1000000000 13 #define maxn (1000+5) 14 #define maxm (1000+5) 15 #define eps 1e-10 16 #define ll long long 17 #define for0(i,n) for(int i=0;i<=(n);i++) 18 #define for1(i,n) for(int i=1;i<=(n);i++) 19 #define for2(i,x,y) for(int i=(x);i<=(y);i++) 20 #define for3(i,x,y) for(int i=(x);i>=(y);i--) 21 #define for4(i,x) for(int i=head[x],y=e[i].go;i;i=e[i].next,y=e[i].go) 22 using namespace std; 23 struct edge{ 24 int go,next; 25 }e[maxm*2]; 26 int head[maxn],tot; 27 int n,b,cnt; 28 int belong[maxn],root[maxn],s[maxn],top; 29 void insert(int x,int y){ 30 e[++tot]=(edge){y,head[x]};head[x]=tot; 31 e[++tot]=(edge){x,head[y]};head[y]=tot; 32 } 33 void dfs(int x,int fa){ 34 int bottom=top; 35 for4(i,x){ 36 if(y!=fa){ 37 dfs(y,x); 38 if(top-bottom>=b){ 39 root[++cnt]=x; 40 while(top!=bottom) 41 belong[s[top--]]=cnt; 42 } 43 } 44 } 45 s[++top]=x; 46 } 47 int read(){ 48 int x=0,f=1;char ch=getchar(); 49 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 50 while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();} 51 return x*f; 52 } 53 int main(){ 54 //freopen("input.txt","r",stdin); 55 //freopen("output.txt","w",stdout); 56 n=read();b=read(); 57 for1(i,n-1){ 58 int x=read(),y=read(); 59 insert(x,y); 60 } 61 dfs(1,0); 62 while(top) 63 belong[s[top--]]=cnt; 64 printf("%d\n",cnt); 65 for1(i,n) 66 printf("%d%c",belong[i],i==n?'\n':' '); 67 for1(i,cnt) 68 printf("%d%c",root[i],i==cnt?'\n':' '); 69 return 0; 70 }