bzoj 1086 王室联邦 —— 思路题

题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1086

一眼看去很是不会,于是看看TJ...

https://blog.csdn.net/lych_cys/article/details/50165643

也就是这样啦...只要以自己为省会,就可以连接零散的儿子,用栈存下儿子中的零散点即可;

因为尽量让儿子自己成为一个省,所以零散的部分一定和自己相连,到时候就可以连在一起;

最后还剩下的零散的点一定 <= b+1,否则会出去一次;

最后一个省的大小一定 <= 2*b+1,因为一旦满足就成为一个省,最差也就是 b-1 + b-1 + 1 成为一个省;

所以最后剩下的点连进最后一个省即可;

然后...只有 b>n 的时候无解?

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int const xn=1005;
int n,b,sta[xn],top,cnt,col[xn],s[xn],hd[xn],ct,to[xn<<1],nxt[xn<<1];
void add(int x,int y){to[++ct]=y; nxt[ct]=hd[x]; hd[x]=ct;}
int rd()
{
  int ret=0,f=1; char ch=getchar();
  while(ch<'0'||ch>'9'){if(ch=='-')f=0; ch=getchar();}
  while(ch>='0'&&ch<='9')ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar();
  return f?ret:-ret;
}
void dfs(int x,int fa)
{
  int pr=top;
  for(int i=hd[x],u;i;i=nxt[i])
    {
      if((u=to[i])==fa)continue;
      dfs(u,x); 
      if(top-pr>=b)
    {
      cnt++; s[cnt]=x;//x !u
      while(top>pr)col[sta[top]]=cnt,top--;
    }
    }
  sta[++top]=x;
}
int main()
{
  n=rd(); b=rd();
  for(int i=1,x,y;i<n;i++)x=rd(),y=rd(),add(x,y),add(y,x);
  dfs(1,0); while(top)col[sta[top]]=cnt,top--;
  printf("%d\n",cnt);
  for(int i=1;i<=n;i++)printf("%d ",col[i]); printf("\n");
  for(int i=1;i<=cnt;i++)printf("%d ",s[i]); printf("\n");
  return 0;
}

 

posted @ 2018-10-05 21:43  Zinn  阅读(117)  评论(0编辑  收藏  举报