Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased:
Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.
The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105).
Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.
If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.
6 1 2 2 3 2 4 4 5 1 6
3
7 1 2 1 3 3 4 1 5 5 6 6 7
-1
In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.
It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
从叶子节点bfs,对于每一个节点用set保存从他下方的节点到这个节点的长度,如果有相同长度的就会自动“合并”。所以,只有两种情况是满足条件的:
1.有一个节点的set的大小是2,其余的都是1
2.全部节点的set的大小都是1
对于情况1,答案就是set中两个数的和;对于情况2,答案就是所有节点中set中的值最大的那个。
若答案为偶数,则根据题意,一定可以再进行一次合成,所以将答案除2直到为奇数即为最终答案。
#include<iostream>
#include<vector>
#include<queue>
#include<set>
#include<string.h>
using namespace std;
vector<int>V[200005];
queue<int>Q;
set<int>S[200005];
int degree[200005];
int vis[200005];
void bfs()
{
while(!Q.empty())
{
int t=Q.front();
Q.pop();
vis[t]=1;
for(int i=0;i<V[t].size();i++)
{
if(vis[V[t][i]]==0)
{
S[V[t][i]].insert((*S[t].begin())+1);
degree[V[t][i]]--;
if(degree[V[t][i]]==1&&S[V[t][i]].size()==1)
Q.push(V[t][i]);
}
}
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(vis,0,sizeof(vis));
memset(degree,0,sizeof(degree));
int u,v;
for(int i=0;i<n-1;i++)
{
scanf("%d%d",&u,&v);
V[u].push_back(v);
V[v].push_back(u);
degree[u]++;
degree[v]++;
}
for(int i=1;i<=n;i++)
{
if(degree[i]==1)
{
Q.push(i);
S[i].insert(0);
}
}
bfs();
int ans=0;
int f=1;
int nn=0;
//cout<<S[1].size()<<endl;
for(int i=1;i<=n;i++)
{
if(S[i].size()>2)
{
f=0;
break;
}
if(S[i].size()==1)
{
ans=max(ans,*S[i].begin());
}
if(S[i].size()==2)
{
ans=max(ans,*S[i].begin()+*S[i].rbegin());
nn++;
}
}
if(nn>=2)
{
f=0;
}
if(f==0)
{
puts("-1");
continue;
}
while(ans%2==0)
{
ans=ans/2;
}
cout<<ans<<endl;
}
}