題目來源:https://www.interviewstreet.com/challenges/dashboard/#problem/4fffc24df25cd
解題報告:
這道題求一顆樹,最多可以去掉幾條邊,使得被分割成的每顆單獨的樹的節點個數都是偶數。題目蠻有意思,難度適宜。
首先,將輸入轉換為樹的格式,對每個節點,保留它的父親節點和兒子節點的編號。
然後遍曆樹的每個節點,得到以該節點為根的樹的節點個數(包括該節點)
對一個節點R,設它有兒子節點A,如果以A為根的樹的節點個數有偶數個,則代表R與A這條邊可以被去除,否則不可以。這樣依次尋找每個節點,看它與它兒子的邊是否可以被去除,最後得到最多可以刪去多少條邊。
/* Enter your code here. Read input from STDIN. Print output to STDOUT */#include <iostream>#include <queue>using namespace std;int sum[101]; //以i為根的樹的節點個數int s[101][101]; //s[i][j]=1代表j為i的兒子int p[101];int adj[101][101];int k;int getSum(int index){ if (sum[index] != 0) return sum[index]; int sm = 0; for (int i = 0; i <= 100; i++) { if(s[index][i] == 1) { sm += getSum(i); } } sm++; sum[index] = sm; return sm;}void findResult(int root){ for (int i = 0; i <= 100; i++) { if (s[root][i] == 1) { if(getSum(i) % 2 == 0) { k++; } findResult(i); } }}int main(){ int N, M; int root; cin >> N >> M; //initialization k = 0; for(int i = 0; i <= 100; i++) { sum[i] = 0; p[i] = -1; for (int j = 0; j <= 100; j++) { s[i][j] = 0; adj[i][j] = 0; } } for (int i = 0; i < M; i++) { int node1, node2; cin >> node1 >> node2; if (i == 0) root = node1; adj[node1][node2] = 1; adj[node2][node1] = 1; } queue<int> q; q.push(root); while(!q.empty()) { int node = q.front(); q.pop(); for (int i = 0; i <= 100; i++) { if (adj[node][i] == 1 && i!=p[node]) { p[i] = node; s[node][i] = 1; q.push(i); } } } findResult(root); cout << k << endl; }
附錄:
You are given a tree (a simple connected graph with no cycles).You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected
component of the forest contains even number of vertices
Your task is to calculate the number of removed edges in such a forest.
Input:
The first line of input contains two integers N and M. N is the number of vertices and M is the number of edges. 2 <= N <= 100.
Next M lines contains two integers ui and vi which
specifies an edge of the tree. (1-based index)
Output:
Print a single integer which is the answer
Sample Input
10 92 13 14 35 26 17 28 69 810 8
Sample Output :2
Explanation : On removing the edges (1, 3) and (1, 6), we can get the desired result.Original tree:
Decomposed tree:
Note: The tree in the input will be such that it can always be decomposed into components containing even number of nodes.