# [BZOJ 1086] [SCOI2005] 王室联邦 【树分块】

### 代码

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;

const int MaxN = 1000 + 5;

int n, BlkSize, Index, Top;
int ID[MaxN], Root[MaxN], S[MaxN];

struct Edge
{
int v;
Edge *Next;
} E[MaxN * 2], *P = E, *Point[MaxN];

inline void AddEdge(int x, int y)
{
++P; P -> v = y;
P -> Next = Point[x]; Point[x] = P;
}

void DFS(int x, int Fa)
{
int Bottom = Top;
for (Edge *j = Point[x]; j; j = j -> Next)
{
if (j -> v == Fa) continue;
DFS(j -> v, x);
if (Top - Bottom >= BlkSize)
{
Root[++Index] = x;
while (true)
{
ID[S[Top--]] = Index;
if (Top == Bottom) break;
}
}
}
S[++Top] = x;
}

int main()
{
scanf("%d%d", &n, &BlkSize);
int a, b;
for (int i = 1; i <= n - 1; ++i)
{
scanf("%d%d", &a, &b);
}
Top = 0;
DFS(1, 0);
while (Top > 0) ID[S[Top--]] = Index;
printf("%d\n", Index);
for (int i = 1; i <= n; ++i) printf("%d ", ID[i]);
printf("\n");
for (int i = 1; i <= Index; ++i) printf("%d ", Root[i]);
printf("\n");
return 0;
}


posted @ 2015-04-24 15:39  JoeFan  阅读(236)  评论(0编辑  收藏  举报