码迷,mamicode.com
首页 > 其他好文 > 详细

CF982C Cut 'em all!

时间:2018-05-19 17:01:30      阅读:1028      评论:0      收藏:0      [点我收藏+]

标签:ons   AC   cout   code   vector   sizeof   end   ace   ack   

思路:

在深搜过程中,贪心地把树划分成若干个连通分支就可以了。划分的条件是某个子树有偶数个节点。注意到在一次划分之后并不需要重新计数,因为一个数加上一个偶数并不影响这个数的奇偶性。

实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN = 100005;
 4 vector<int> G[MAXN];
 5 bool vis[MAXN];
 6 int ans = 0;
 7 int dfs(int u)
 8 {
 9     vis[u] = true;
10     int cnt = 0;
11     for (int i = 0; i < G[u].size(); i++)
12     {
13         int tmp = G[u][i];
14         if (!vis[tmp]) cnt += dfs(tmp);
15     }
16     if (cnt & 1) ans++;
17     return cnt + 1;
18 }
19 int main()
20 {
21     int n, x, y;
22     while (cin >> n)
23     {
24         for (int i = 1; i <= n; i++) G[i].clear();
25         memset(vis, 0, sizeof vis);
26         ans = 0;
27         for (int i = 0; i < n - 1; i++)
28         {
29             cin >> x >> y;
30             G[x].push_back(y);
31             G[y].push_back(x);
32         }
33         if (n & 1) { cout << -1 << endl; continue; }
34         dfs(1);
35         cout << ans - 1 << endl;
36     }
37     return 0;
38 }

 

CF982C Cut 'em all!

标签:ons   AC   cout   code   vector   sizeof   end   ace   ack   

原文地址:https://www.cnblogs.com/wangyiming/p/9060464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!