【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;
}
我们开一个栈,遍历一个节点,若该节点的几棵子树的大小>=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;
}
相关文章推荐
- 搜索(DLX):HDU 3663 Power Stations
- 关于内存问题提醒!结构体+protobuf做协议体发送!
- TIJ 复习笔记5
- hibernate循环插入数据
- IntelliJ Idea 常用快捷键列表
- Bootstrap排版
- Bootstrap排版
- leetcode 355 Design Twitte
- 集群配置虚拟主机及部署Hadoop集群碰到的问题
- C和C++中struct的区别 以及C++中struct和class 以及c和c++区别 引用和指针
- BZOJ 1497 最大获利(最大权闭合子图)
- myeclipse中创建struts2的web项目
- 学习进度条十四
- apache配置
- c primer plus第3章总结:数据类型
- 使用DOM4J修改读入的xml文档
- 项目经验教训总结
- hive脚本出现Error: java.lang.RuntimeException: Error in configuring object和Caused by: java.lang.IndexOutOfBoundsException: Index: 9, Size: 9
- MySQL Order by 语句用法与优化详解
- 漫话机器学习大数据那些事儿