codeforces acito code challengeC. Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
The first line contains a single integer nn (2≤n≤1052≤n≤105) the number of nodes in the tree.
Each of the next n−1n − 1 lines contains two integers aiai and bibi (1≤ai,bi≤n1≤ai,bi≤n, ai≠biai≠bi) — the edges of the tree. It is guaranteed that the given edges form a tree.
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition mm.
Each of the next mm lines should contain two integers uiui, vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi) denoting that one of the paths in the decomposition is the simple path between nodes uiui and vivi.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
4 1 2 2 3 3 4
Yes 1 1 4
6 1 2 2 3 3 4 2 5 3 6
No
5 1 2 1 3 1 4 1 5
Yes 4 1 2 1 3 1 4 1 5
The tree from the first example is shown on the picture below:The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below:We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below:The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
思路: 思维题。判断从根能走到所有的点,先找根,根节点有两种情况:
(一) 根在中间时:根节点所连的边数必然大于等于 三,如果有两个大于等于三的点显然无法完成题目的要求
(二)根在端点时:所有的点所连的边数必然1<=num<=2 那么从一段开始走即可。
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n,m=0,a,b,rt=0;
int d[maxn];
int main(){
memset(d,0,sizeof(d));
scanf("%d",&n);
for (int i=1;i<n;i++){
scanf("%d%d",&a,&b);
d[a]++,d[b]++;
}
for (int i=1;i<=n;i++){
printf("%d %d\n",i,d[i]);
}
for (int i=1;i<=n;i++){
if(d[i]>2){
if(!rt) rt=i;
else {
printf("No\n");
return 0;
}
}
}
if(!rt) rt=1;
for (int i=1;i<=n;i++)
if(i!=rt&& d[i]==1) m++;
printf("Yes\n%d\n",m);
for (int i=1;i<=n;i++){
if(i!=rt && d[i]==1)
printf("%d %d\n",rt,i);
}
return 0;
}
上一篇: Azamon Web Services
下一篇: Cow and Friend