您的位置:首页 > 其它

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

2016-06-12 19:29 239 查看
比较有意思的题目,听说这是树分块的裸题?

我们开一个栈,遍历一个节点,若该节点的几棵子树的大小>=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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: