Codeforces 982C(dfs+思维)
You're given a tree with nn 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.
The first line contains an integer nn (1≤n≤1051≤n≤105) denoting the size of the tree.
The next n−1n−1 lines contain two integers uu, vv (1≤u,v≤n1≤u,v≤n) each, describing the vertices connected by the ii-th edge.
It's guaranteed that the given edges form a tree.
Output a single integer kk — the maximum number of edges that can be removed to leave all connected components with even size, or −1−1 if it is impossible to remove edges in order to satisfy this property.
4
2 4
4 1
3 1
1
3
1 2
1 3
-1
10
7 1
8 4
8 10
4 7
6 5
9 3
3 5
2 10
2 5
4
2
1 2
0
In the first example you can remove the edge between vertices 11 and 44. 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个点,有n-1条边让他们相连。
询问最多删除多少边,让他们成为偶数的块
三、思路
DFS,只要能找到一个偶数的块,就使答案++,因为是偶数块的话,就可以在这里断开一次
(其实感觉一点都不裸,太菜,没想到dfs)
#include <iostream> #include<cstring> #include<string> #include<cstdio> #include<algorithm> #include<cmath> #include<deque> #include<vector> #define ll unsigned long long #define inf 0x3f3f3f3f using namespace std; bool used[100005]; int n; vector<int>v[100005]; int ans=0; int dfs(int fa) { used[fa]=1; int s=0; for(int i=0;i<v[fa].size ();i++) { if(used[v[fa][i]]) continue; s=s+dfs(v[fa][i]); } if((s+1)%2==0) ans++;//发现是偶数块,就可以减一刀 return s+1; } int main() { int n; cin>>n; ans=0; memset(used,0,sizeof(used)); for(int i=1;i<=n-1;i++) { int x,y; cin>>x>>y; v[x].push_back (y); v[y].push_back (x); } if(n&1) cout<<"-1"; else { used[1]=1; int s=dfs(1); cout<<ans-1;//原本自己就是偶数,所以要减1 } return 0; }