bzoj 1086

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

Sample Output

3
2 1 1 3 3 3 3 2
2 1 8
 
思路: 

首先从根dfs整棵树,如果某棵子树剩余大小大于B,就将它单独成一块,并将它移除(即不再记录它的大小)
如果最后树的节点个数不足B,就把它加入上一块。z

这样分块每块大小为[B,3B)(只有一块,剩下的块直径不超过2B),直径不超过3B、但不保证连通。可以在树上莫队中使用

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int const N = 1000 + 3;
 4 struct edge
 5 {
 6     int to, nt;
 7 } e[N << 1];
 8 int n, m, h[N], cnt, bl[N], sum, st[N], top, rt[N], a[N];
 9 void add(int a, int b)
10 {
11     cnt++;
12     e[cnt].to = b;
13     e[cnt].nt = h[a];
14     h[a] = cnt;
15 }
16 void out(int x, int num)
17 {
18     a[++sum] = x;
19     while(num--) bl[st[top--]] = sum;
20 }
21 void dfs(int x, int fa)
22 {
23     int now = top;
24     for(int i = h[x]; i; i = e[i].nt)
25     {
26         int v = e[i].to;
27         if(v == fa) continue;
28         dfs(v, x);
29         if(top - now >= m) out(x, top - now);
30     }
31     st[++top] = x;
32 }
33 int main()
34 {
35     scanf("%d%d", &n, &m);
36     for(int i = 1; i < n; i++)
37     {
38         int x, y;
39         scanf("%d%d", &x, &y);
40         add(x, y);
41         add(y, x);
42     }
43     dfs(1, 0);
44     while(top) bl[st[top--]] = sum;
45     printf("%d\n", sum);
46     for(int i = 1; i <= n; i++) printf("%d ", bl[i]);
47     printf("\n");
48     for(int i = 1; i <= sum; i++) printf("%d ", a[i]);
49     return 0;
50 }
View Code

 

posted @ 2019-04-07 11:21  zjxxcn  阅读(136)  评论(0编辑  收藏  举报