Description
有n个点,n-1条边,任意两个不同的点之间有且仅有一条直接或间接边。把n个点分为若干个部分,每个部分最少要b个点,其中有一个点(BOSS)可在此部分内或外。使得此部分内的点到BOSS点的路径上经过的点全在此部分内。
Input
第一行包含两个数N,B(1<=N<=1000, 1 <= B <=N)。接下来N-1行,每行描述一条边,包含两个数,即这条边连接的点的编号。
Output
如果无法满足要求,输出0。否则输出数K,表示你给出的划分方案中部分的个数,编号为1..K。第二行输出N个数,第I个数表示编号为I的点属于的部分编号,第三行输出K个数,表示这K个部分的BOSS点的编号,如果有多种方案,你可以输出任意一种。
Sample Input
8 2
1 2
2 3
1 8
8 7
8 6
4 6
6 5
Sample Output
3
2 1 1 3 3 3 3 2
2 1 8
这道题,大家应该都可以看出来是一棵树,不仅要用dfs,还要用栈,如果那个子树的点超过b,直接划分部分,根为BOSS点,剩下的随便处理。
#include<cstdio>
#include<cstring>
using namespace std;
struct node
{
int x,y,next;
}a[2100];int len,last[2100];
void ins(int x,int y)
{
len++;
a[len].x=x;a[len].y=y;
a[len].next=last[x];last[x]=len;
}
int belong[2100],tot;
int root[2100],n,b;
int sta[2100],top;
void dfs(int fa,int x)
{
int tp=top;
for(int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if(y!=fa)
{
dfs(x,y);
if(top-tp>=b)
{
root[++tot]=x;
while(top!=tp)
{
belong[sta[top--]]=tot;
}
}
}
}
sta[++top]=x;
}
int main()
{
scanf("%d%d",&n,&b);
len=0;memset(last,0,sizeof(last));
if(n<b){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);
}tot=0;top=n;
dfs(0,1);
while(top){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 ",root[i]);
printf("\n");
return 0;
}