[bzoj 2526]Poi2011 Inspection

25 篇文章 0 订阅

water,water,water。。。。

树上维护几个值就好了(NOIP模拟赛上的常见题。。。。)

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
const int Maxn=1000006;
int node[Maxn*2],next[Maxn*2],a[Maxn],q[Maxn];
int se1[Maxn],se2[Maxn],de1[Maxn],de2[Maxn],fa[Maxn];
int n,m,l,r,x,y,i,tot;
LL ms1[Maxn],ms2[Maxn],md1[Maxn],md2[Maxn],size[Maxn],cnt[Maxn],ans[Maxn],tmp;

void add(int x,int y){
  node[++tot]=y; next[tot]=a[x]; a[x]=tot;
  node[++tot]=x; next[tot]=a[y]; a[y]=tot;
}

void bfs(){
  for (q[l=r=1]=1;l<=r;l++)
    for (i=a[q[l]];i;i=next[i])
    if (node[i]!=fa[q[l]])
      fa[ q[++r]=node[i] ]=q[l];

  for (;r>0;r--){
  	x=q[r]; y=fa[x];
  	size[x]++; size[y]+=size[x];
  	cnt[y]+=size[x]+cnt[x];
  	if (ms1[y]<size[x]){            //节点数 
  	  ms2[y]=ms1[y]; se2[y]=se1[y];
  	  ms1[y]=size[x]; se1[y]=x;
  	} else
  	if (ms2[y]<size[x])
  	{ ms2[y]=size[x]; se2[y]=x; }
  	
  	if (md1[y]<md1[x]+1){           //深度 
  	  md2[y]=md1[y]; de2[y]=de1[y];
  	  md1[y]=md1[x]+1; de1[y]=x;
  	} else
  	if (md2[y]<md1[x]+1)
  	{ md2[y]=md1[x]+1; de2[y]=x; }
  	
  }
  
  for (i=2;i<=n;i++){                //连上父亲 
  	x=q[i]; y=fa[x];
  	cnt[x]+=cnt[y]-size[x]+n-size[x]-cnt[x];
  	
  	if (ms1[x]<n-size[x]){
  	  ms2[x]=ms1[x]; se2[x]=se1[x];
  	  ms1[x]=n-size[x]; se1[x]=y;
  	} else
  	if (ms2[x]<n-size[x])
  	{ ms2[x]=n-size[x]; se2[x]=y; }
  	
  	if (de1[y]==x) tmp=md2[y];
	  else tmp=md1[y];
  	if (md1[x]<tmp+1){
  	  md2[x]=md1[x]; de2[x]=de1[x];
  	  md1[x]=tmp+1; de1[x]=y;
  	} else
  	if (md2[x]<tmp+1)
  	{ md2[x]=tmp+1; de2[x]=y; }
  	
  }
}

void work(){
  for (i=1;i<=n;i++){
  	x=q[i];
  	if (ms1[x]>n/2) ans[x]=-1;
    else
    {
  	  if (ms1[x]>(n-1)/2){
  	  	if (de1[se1[x]]!=x)
  	      ans[x]=cnt[x]*2-md1[se1[x]]-1;
  	    else ans[x]=cnt[x]*2-md2[se1[x]]-1;
  	  } else ans[x]=cnt[x]*2-md1[x];
    }
  }
}

int read(){
  int ret=0;
  char ch=getchar();
  while (ch<'0'||ch>'9') ch=getchar();
  while (ch>='0'&&ch<='9')
    ret=ret*10+ch-'0', ch=getchar();
  return ret;
}

int main(){
  freopen("ins.in","r",stdin);
  freopen("ins.out","w",stdout);
  n=read();
  for (i=1;i<n;i++){
  	x=read(); y=read();
  	add(x,y);
  }
  bfs();
  work();
  for (i=1;i<=n;i++)
    printf("%I64d\n",ans[i]);
  return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值