【bzoj1086】[SCOI2005]王室联邦 树分块

比较有意思的题目,听说这是树分块的裸题?

我们开一个栈,遍历一个节点,若该节点的几棵子树的大小>=B,那么就把他们分到一块,省会为当前节点

这样做会剩下不到B个节点,这时候就利用栈传到上一层节点就可以

最后会剩下不到B个节点,因为我们原来的块都是一定不超过2B的,于是把这B个节点放到最后一个块就可以


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#define maxn 2010

using namespace std;

int head[maxn],to[maxn],next[maxn];
int st[maxn],root[maxn],bel[maxn];
int n,m,num,b,cnt,top;

void addedge(int x,int y)
{
	num++;to[num]=y;next[num]=head[x];head[x]=num;
}

void dfs(int x,int fa)
{
	int now=top;
	for (int p=head[x];p;p=next[p])
	  if (to[p]!=fa)
	  {
	  	dfs(to[p],x);
	  	if (top-now>=b) {root[++cnt]=x;while (top!=now) bel[st[top--]]=cnt;}
	  }
	st[++top]=x;
}

int main()
{
	scanf("%d%d",&n,&b);
	for (int i=1;i<n;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		addedge(x,y);addedge(y,x);
	}
	dfs(1,0);
	while (top) bel[st[top--]]=cnt;
	printf("%d\n",cnt);
	for (int i=1;i<=n;i++) printf("%d ",bel[i]);printf("\n");
	for (int i=1;i<=cnt;i++) printf("%d ",root[i]);printf("\n");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值