提交:bzoj1086
题目↑↑
大神思路:
题目要求该区域所有的点到根的路径上的点都属于该区域。很明显,就是一棵树,所以题意其实就是把一棵多叉树分成若干个区域,然而又不用输出最小方案,所以弱爆了。这个玩意我也不知道它算什么,应该属于dfs的范畴吧。
一种简单粗暴的想法就是dfs,每找到B个就分一块,但是这样连通性不能保证(一颗子树的下半截和另一棵子树的上半截组成一块)。所以我们就想:能不能从底部往上组块,每棵子树较深的部分自己成块,然后靠近根的部分组成一个大块。
所以我们这么做:对于一个点x,以初次访问它时,栈的栈顶作为相对栈底,每遍历完它的一个子节点所在的子树,判断此时栈顶-相对栈底得到的元素个数是否大于或等于b,若成立,那么弹栈至相对栈顶。当访问完所有子节点要回溯到x的父节点时,把x压入栈。
代码↓↓
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int x,y,next;
}a[21000];int len,first[11000];
void ins(int x,int y)
{
len++;
a[len].x=x;a[len].y=y;
a[len].next=first[x];first[x]=len;
}
int sta[11000],top;
int belong[11000],tot;
int rt[11000],n,L;
void dfs(int fa,int x)
{
int now=top;
for(int k=first[x];k>0;k=a[k].next)
{
int y=a[k].y;
if(y!=fa)
{
dfs(x,y);
if(top-now>=L)
{
rt[++tot]=x;
while(top!=now)
{
belong[sta[top--]]=tot;
}
}
}
}
sta[++top]=x;
}
int main()
{
scanf("%d%d",&n,&L);
if(n<L){printf("0\n");return 0;}
for(int i=1;i<n;i++)
{
int x,y;scanf("%d%d",&x,&y);
ins(x,y);ins(y,x);
}
dfs(0,1);
while(top>0)belong[sta[top--]]=tot;
printf("%d\n",tot);
for(int i=1;i<=n;i++)printf("%d ",belong[i]);printf("\n");
for(int i=1;i<=tot;i++)printf("%d ",rt[i]);printf("\n");
return 0;
}