Even Tree 小议

原题链接:https://www.hackerrank.com/challenges/even-tree/problem

思路:把树还原出来,对每个结点,计算以该结点为根的子树结点数。子树结点数为偶数的结点数量就是所求森林中树木的数量。结点数量减去一就是所求结果。

 1 #include <cmath>
 2 #include <cstdio>
 3 #include <vector>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 struct node{
 9     int index, num_subtree;
10     vector<node*> children;
11     node(int i=0,int n=0):
12         index(i),num_subtree(n), children(vector<node*>()){}
13 };
14 
15 node* construct_tree(int parent, int index, const vector<vector<int>>& adjLsit);
16 void count_even(node* root, int& cnt);
17 
18 int main() {
19     /* Enter your code here. Read input from STDIN. Print output to STDOUT */
20     int N, M; cin >> N >> M;
21     vector<vector<int>> adjList(N + 1);
22     for(int i = 0; i < M; i++){
23         int n1, n2; cin >> n1 >> n2;
24         adjList[n1].push_back(n2);
25         adjList[n2].push_back(n1);
26     }
27     node* root = construct_tree(0, 1, adjList);
28     int cnt = 0;
29     count_even(root, cnt);
30     cout << cnt - 1 << endl;
31     return 0;
32 }
33 
34 node* construct_tree(int parent, int index, const vector<vector<int>>& adjList){
35     node* tmp = new node(index);
36     tmp->num_subtree = 1;
37     for(int i = 0; i < adjList[index].size(); i++){
38         if(adjList[index][i] != parent){
39             tmp->children.push_back(construct_tree(index, adjList[index][i], adjList));
40             tmp->num_subtree += tmp->children.back()->num_subtree;
41         }
42     }
43     return tmp;
44 }
45 
46 void count_even(node* root, int& cnt){
47     for(auto vit: root->children){
48         count_even(vit, cnt);
49     }
50     if(root->num_subtree%2==0){
51         cnt++;
52     }
53 }
View Code

 

posted on 2017-08-23 09:49  不敢为天下先  阅读(196)  评论(0)    收藏  举报

导航