Codeforces 982 C. Cut 'em all! 图的遍历
C. Cut 'em all!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output
You're given a tree with?n vertices.
Your task is to determine the maximum possible number of edges that can be removed?
in such a way that all the remaining connected components will have even size.
InputThe first line contains an integer?n?(1≤n≤105) denoting the size of the tree.
The next?n?1?lines contain two integers?u,?v?(1≤u,v≤n) each, describing the vertices connected by the?i-th edge.
It's guaranteed that the given edges form a tree.
OutputOutput a single integer?k?— the maximum number of edges that can be removed to leave all connected components with even size, or??1
if it is impossible to remove edges in order to satisfy this property.
ExamplesinputCopy4 2 4 4 1 3 1 outputCopy1inputCopy3 1 2 1 3 outputCopy-1inputCopy10 7 1 8 4 8 10 4 7 6 5 9 3 3 5 2 10 2 5 outputCopy4inputCopy2 1 2 outputCopy0 NoteIn the first example you can remove the edge between vertices?1 and?4.?
The graph after that will have two connected components with two vertices in each.
In the second example you can't remove edges in such a way that all components have even number of vertices,?
so the answer is??1
.
題目描述:
? ? 給你一個有n個結(jié)點的樹,其中有n-1條邊,詢問你最多你可以移動多少條邊,使得每個強連通分量的個數(shù)均為偶數(shù)。
題目分析:
? ? 因為我們知道,如果所給的結(jié)點的個數(shù)是奇數(shù),那么,因為奇數(shù)必定是由一個偶數(shù)和一個奇數(shù)組成,故總會有一個強連通分量的個數(shù)為奇數(shù),因此當(dāng)n為奇數(shù)使,答案為-1。
? ? 那么當(dāng)n等于偶數(shù)的時,我們只需要進行dfs遍歷整張圖,統(tǒng)計一下某個結(jié)點以及其兒子結(jié)點的數(shù)量,如果遞歸到最底時統(tǒng)計出的數(shù)量為偶數(shù),則答案+1即可。
#include<bits/stdc++.h> using namespace std; const int maxn=2e5+5; struct edge {int to,next; }q[maxn]; int head[maxn]; int size[maxn]; int cnt=0; int ans=0; void init() {memset(head,-1,sizeof(head));cnt=0; } void add_edge(int from,int to) {q[cnt].next=head[from];q[cnt].to=to;head[from]=cnt++; } void dfs(int x,int fa) {size[x]=1;for(int i=head[x];i!=-1;i=q[i].next){if(q[i].to==fa) continue;dfs(q[i].to,x);size[x]+=size[q[i].to];}if(size[x]%2==0){ans++;size[x]=0;} } int main() {int n,u,v;scanf("%d",&n);init();for(int i=0;i<n-1;i++){scanf("%d%d",&u,&v);add_edge(u,v);add_edge(v,u);}if(n&1){printf("-1\n");return 0;}dfs(1,-1);printf("%d\n",ans-1);return 0; }總結(jié)
以上是生活随笔為你收集整理的Codeforces 982 C. Cut 'em all! 图的遍历的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU1048 盐水的故事 精度问题
- 下一篇: Floyd算法的动态规划本质