首页 > 代码库 > BZOJ 1086: [SCOI2005]王室联邦

BZOJ 1086: [SCOI2005]王室联邦

1086: [SCOI2005]王室联邦

Time Limit: 10 Sec  Memory Limit: 162 MBSec  Special Judge
Submit: 1399  Solved: 830
[Submit][Status][Discuss]

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

HINT

 

Source

 
[Submit][Status][Discuss]

 

DFS每一个点,先递归子树,然后拿到子树传回的该子树中的未分组点。对所有子树的传回点合并,每每够了B个就分一块。最后把自己加入未分组点队列,传回上层。这是分块方法的一种叙述,但显然不能这么写是吧,2333。

用一个栈保存未分组的点,每次DFS一个点先记录下此时的栈顶位置,然后递归子树,每每当前栈顶到记录栈顶元素个数超过B个,就把这一段分为一块。这一段一定都是在当前点的子树里,且和当前点相邻。最后把当前点压入栈顶,返回上层即可。

这种分块的方法貌似也经常用在树上莫队等问题中。

 

 1 #include <bits/stdc++.h> 2  3 const int siz = 10000000; 4  5 char buf[siz], *bit = buf; 6  7 inline int nextInt (void) { 8     register int ret = 0; 9     register int neg = 0;10     11     while (*bit < 0) 12         if (*bit++ == -)13             neg ^= true;14             15     while (*bit >= 0) 16         ret = ret*10 + *bit++ - 0;17     18     return neg ? -ret : ret;19 }20 21 const int maxn = 2000 + 5;22 23 int n;24 int m;25 int tot;26 int cnt;27 int top;28 int hd[maxn];29 int nt[maxn];30 int to[maxn];31 int stk[maxn];32 int bel[maxn];33 int cap[maxn];34 35 void divid (int u, int f) {36     int bot = top;37     38     for (register int i = hd[u]; ~i; i = nt[i])39         if (to[i] != f) {40             divid (to[i], u);41             if (top - bot >= m) {42                 cap[++cnt] = u;43                 while (top != bot)44                     bel[stk[top--]] = cnt;45             }46         }47         48     stk[++top] = u;49 }50 51 signed main (void) {52     fread (buf, 1, siz, stdin);53     54     n = nextInt ();55     m = nextInt ();56     57     memset (hd, -1, sizeof (hd)), tot = 0;58     59     for (register int i = 1; i < n; ++i) {60         int x = nextInt ();61         int y = nextInt ();62         nt[tot] = hd[x]; to[tot] = y; hd[x] = tot++;63         nt[tot] = hd[y]; to[tot] = x; hd[y] = tot++;64     }65     66     divid (1, -1);67     68     while (top > 0)69         bel[stk[top--]] = cnt;70     71     printf ("%d\n", cnt);72     73     for (register int i = 1; i < n; ++i)74         printf ("%d ", bel[i]);75     printf ("%d\n", bel[n]);76     77     for (register int i = 1; i < cnt; ++i)78         printf ("%d ", cap[i]);79     printf ("%d\n", cap[cnt]);80 }

 

@Author: YouSiki

BZOJ 1086: [SCOI2005]王室联邦