首页 > 技术文章 > [luoguP2325] [SCOI2005]王室联邦(树分块乱搞)

zhenghaotian 2017-10-18 19:11 原文

传送门

 

想了半小时,没什么思路。。

看了题解,是个叫做树分块的奇奇怪怪的操作。。

题解

树分块的研究

 

#include <cstdio>
#include <cstring>
#define N 2001

int n, b, size, cnt, tot;
int head[N], to[N], nex[N], belong[N], s[N], root[N];
bool vis[N];

inline void add(int x, int y)
{
	to[cnt] = y;
	nex[cnt] = head[x];
	head[x] = cnt++;
}

inline void dfs(int u)
{
	int i, v, bottom = size;
	vis[u] = 1;
	for(i = head[u]; ~i; i = nex[i])
	{
		v = to[i];
		if(!vis[v])
		{
			dfs(v);
			if(size - bottom >= b)
			{
				root[++tot] = u;
				while(size > bottom)
					belong[s[size--]] = tot;
			}
		}
	}
	s[++size] = u;
}

int main()
{
	int i, x, y;
	scanf("%d %d", &n, &b);
	memset(head, -1, sizeof(head));
	for(i = 1; i < n; i++)
	{
		scanf("%d %d", &x, &y);
		add(x, y);
		add(y ,x);
	}
	dfs(1);
	while(size) belong[s[size--]] = tot;
	printf("%d\n", tot);
	for(i = 1; i <= n; i++) printf("%d ", belong[i]);
	puts("");
	for(i = 1; i <= tot; i++) printf("%d ", root[i]);
	return 0;
}

  

推荐阅读