# [BZOJ1086][SCOI2005]王室联邦

## 1086: [SCOI2005]王室联邦

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

## Description

“余”人国的国王想重新编制他的国家。他想把他的国家划分成若干个省，每个省都由他们王室联邦的一个成

## Input

第一行包含两个数N，B（1<=N<=1000, 1 <= B <= N）。接下来N－1行，每行描述一条边，包含两个数，即这

## Output

如果无法满足国王的要求，输出0。否则输出数K，表示你给出的划分方案中省的个数，编号为1..K。第二行输

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

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char buf[10000000], *ptr = buf - 1;
int n = 0;
char ch = *++ptr;
while (ch < '0' || ch > '9') ch = *++ptr;
while (ch <= '9' && ch >= '0') {
n = (n << 1) + (n << 3) + ch - '0';
ch = *++ptr;
}
return n;
}
const int maxn = 1000 + 10;
struct Edge {
int to, next;
Edge(){}
Edge(int _t, int _n) : to(_t), next(_n){}
}e[maxn * 2];
int fir[maxn] = { 0 }, cnt = 0;
inline void ins(int u, int v) {
e[++cnt] = Edge(v, fir[u]); fir[u] = cnt;
e[++cnt] = Edge(u, fir[v]); fir[v] = cnt;
}
int N, B;
int sta[maxn], top = 0;
int belong[maxn], root[maxn], bcnt = 0;
void dfs(int u, int fa) {
int bot = top;
for (int v, i = fir[u]; i; i = e[i].next) {
v = e[i].to;
if (v == fa) continue;
dfs(v, u);
if (top - bot >= B) {
bcnt++;
root[bcnt] = u;
while (top != bot)
belong[sta[top--]] = bcnt;
}
}
sta[++top] = u;
}
int main() {
for (int u, v, i = 1; i < N; i++) {
ins(u, v);
}
dfs(1, 0);
while (top) belong[sta[top--]] = bcnt;
printf("%d\n", bcnt);
for (int i = 1; i <= N; i++)
printf("%d ", belong[i]);
puts("");
for (int i = 1; i <= bcnt; i++)
printf("%d ", root[i]);
return 0;
}

posted @ 2017-09-26 18:40  Elder_Giang  阅读(111)  评论(0编辑  收藏  举报