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; }