Tree2cycle
Time Limit: 15000/8000 MS (Java/Others) Memory Limit: 102400/102400 K (Java/Others)
Total Submission(s): 2174 Accepted Submission(s): 516
Problem Description
A
tree with N nodes and N-1 edges is given. To connect or disconnect one
edge, we need 1 unit of cost respectively. The nodes are labeled from 1
to N. Your job is to transform the tree to a cycle(without superfluous
edges) using minimal cost.
A cycle of n nodes is defined as follows: (1)a graph with n nodes and n edges (2)the degree of every node is 2 (3) each node can reach every other node with these N edges.
A cycle of n nodes is defined as follows: (1)a graph with n nodes and n edges (2)the degree of every node is 2 (3) each node can reach every other node with these N edges.
Input
The first line contains the number of test cases T( T<=10 ). Following lines are the scenarios of each test case.
In the first line of each test case, there is a single integer N( 3<=N<=1000000 ) - the number of nodes in the tree. The following N-1 lines describe the N-1 edges of the tree. Each line has a pair of integer U, V ( 1<=U,V<=N ), describing a bidirectional edge (U, V).
In the first line of each test case, there is a single integer N( 3<=N<=1000000 ) - the number of nodes in the tree. The following N-1 lines describe the N-1 edges of the tree. Each line has a pair of integer U, V ( 1<=U,V<=N ), describing a bidirectional edge (U, V).
Output
For each test case, please output one integer representing minimal cost to transform the tree to a cycle.
Sample Input
1
4
1 2
2 3
2 4
Sample Output
3
题意:
给你一颗树,问用多少步才能使这棵树成为一个圈。
思路:
对于人一个节点,只能有一个儿子,除了树根,其他的统统剪掉
AC代码:
1 # include <bits/stdc++.h> 2 using namespace std; 3 const int MAX = 1000010; 4 struct node 5 { 6 int to; 7 int next; 8 }tree[MAX * 2]; 9 int head[MAX]; 10 int tol; 11 int sum = 0; 12 void add(int a, int b) 13 { 14 tree[tol].to = b; 15 tree[tol].next = head[a]; 16 head[a] = tol++; 17 } 18 19 int dfs(int root, int f) 20 { 21 int tmp = 0; 22 for(int i = head[root]; i != -1; i = tree[i].next) 23 { 24 int son = tree[i].to; 25 if(son == f) 26 continue; 27 tmp += dfs(son, root); 28 29 } 30 if(tmp >= 2) 31 { 32 if(root == 1) 33 sum += 2 * (tmp - 2); 34 else 35 sum += 2 * (tmp - 1); 36 return 0; // 被剪断了 37 } 38 return 1; 39 } 40 41 int main() 42 { 43 int T; 44 scanf("%d", &T); 45 while(T--) 46 { 47 tol = 0; 48 sum = 0; 49 memset(head, -1, sizeof(head)); 50 51 int n; 52 scanf("%d", &n); 53 int a, b; 54 for(int i = 1; i < n; i++) 55 { 56 scanf("%d%d", &a, &b); 57 add(a, b); 58 add(b, a); 59 } 60 dfs(1, -1); 61 printf("%d ", sum + 1); 62 } 63 return 0; 64 }