题目
题解
题意:给你一棵树,可以在这棵树上进行若干次操作,每次操作可以把两条长度相同的链,根据一个中点合并在一起。然后问你经过若干次合并之后,最后的最短链长度是多少
Solution
先从节点1开始dfs。
对于每一个节点,用一个set记录:以该点为根的子树的深度。
a) 如果此节点的某个子节点打出了GG,则此节点直接打出GG。
b) 若set的元素个数<=1,那么,以该点为根的子树,显然是可以
缩成一条链滴!且该点为链的端点。
c) 若set元素个数=2,以该点为根的子树,也可以收缩成一条链,
且该点不是链的端点。此时,我们继续分类讨论。
i) 该点没有父亲。我们成功找到了一条链~岂不美哉。
ii) 该点有父亲,那么在链上会长出一根奇怪的东西。那我们赶紧报警,把该点赋给root,并打出GG
d)若set中元素个数>2,直接打出GG!
如果从1开始dfs求索未得,那一定是root的打开方式不对。我萌以root为起点再来一遍dfs。
如果还不行,那就真GG。
Code
#include<bits/stdc++.h>
using namespace std;
const int N=200002;
struct node{
int to,ne;
}e[N<<1];
int n,i,x,y,s,rt,h[N],tot;
inline char gc(){
static char buf[100000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int rd(){
int x=0,fl=1;char ch=gc();
for (;ch<48||ch>57;ch=gc())if(ch=='-')fl=-1;
for (;48<=ch&&ch<=57;ch=gc())x=(x<<3)+(x<<1)+(ch^48);
return x*fl;
}
inline void wri(int a){if(a<0)a=-a,putchar('-');if(a>=10)wri(a/10);putchar(a%10|48);}
inline void wln(int a){wri(a);puts("");}
int dfs(int u,int fa){
set<int>S;
for(int i=h[u],v;i;i=e[i].ne)
if ((v=e[i].to)!=fa){
int t=dfs(v,u);
if (t==-1) return -1;
S.insert(t+1);
}
if (S.size()>2) return -1;
if (!S.size()) return 0;
if (S.size()==1) return *S.begin();
if (S.size()==2 && !fa) return *S.rbegin()+*S.begin();
rt=u;
return -1;
}
void add(int x,int y){
e[++tot]=(node){y,h[x]};
h[x]=tot;
}
int main(){
n=rd();
for (i=1;i<n;i++) x=rd(),y=rd(),add(x,y),add(y,x);
s=dfs(1,0);
if (s==-1 && rt) s=dfs(rt,0);
printf("%d",s/(s&-s));
}