bzoj 1086 [SCOI2005]王室联邦——思路

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

于是去看了题解。

要回溯的时候再把自己加进栈里判断。这样才能保证剩下的可以通过自己连到上面。

过程中最大是 (b-1)+(b-1)+1 ,根的时候最大是(b-1)+(b-1)+1+(b-1)。

只有b>n的时候无解?

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1005;
int n,B,hd[N],xnt,to[N<<1],nxt[N<<1];
int sta[N],top,col[N],cnt,prn[N];
int rdn()
{
  int ret=0;bool fx=1;char ch=getchar();
  while(ch>'9'||ch<'0'){if(ch=='-')fx=0;ch=getchar();}
  while(ch>='0'&&ch<='9') ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar();
  return fx?ret:-ret;
}
void add(int x,int y)
{
  to[++xnt]=y; nxt[xnt]=hd[x]; hd[x]=xnt;
  to[++xnt]=x; nxt[xnt]=hd[y]; hd[y]=xnt;
}
void cz(int l,int a)
{
  prn[++cnt]=a;
  for(int i=l+1;i<=top;i++)
    col[sta[i]]=cnt;
  top=l;
}
void dfs(int cr,int f)
{
  int lm=top;
  for(int i=hd[cr],v;i;i=nxt[i])
    if((v=to[i])!=f)
      {
    dfs(v,cr);
    if(top-lm>=B)cz(lm,cr);
      }
  sta[++top]=cr;
  if(top-lm>=B)cz(lm,cr);
}
int main()
{
  n=rdn(); B=rdn();
  for(int i=1,u,v;i<n;i++)
    {
      u=rdn(); v=rdn(); add(u,v);
    }
  dfs(1,0);
  for(int i=1;i<=top;i++) col[sta[i]]=cnt;
  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 ",prn[i]);
  printf("\n");
  return 0;
}

 

posted on 2018-10-05 22:14  Narh  阅读(83)  评论(0编辑  收藏  举报

导航