Tree2cycle
Time Limit: 15000/8000 MS (Java/Others) Memory Limit: 102400/102400 K (Java/Others)Total Submission(s): 1946 Accepted Submission(s): 444
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
思路:其实就是把一棵树变成许多链再连成环,求最小代价。一个结点如果有两个子结点,如果有父结点,删除与其中一个儿子的连边和删除与父节点的连边效果都一样。如果有三个子节点必然删除其中一条与子节点的连边。注意加扩栈语句(用c++交)。
详细见代码:
#pragma comment(linker, "/STACK:10240000")
#include<iostream>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=1e6+100;
int head[maxn];
int Next[maxn*2];
int info[maxn*2];
int dp[maxn];
int tot=0;
void init()
{
memset(head,-1,sizeof head);
memset(dp,0,sizeof dp);
tot=0;
}
void add(int fr,int to)
{
Next[tot]=head[fr];
info[tot]=to;
head[fr]=tot++;
}
bool dfs(int a,int f)
{
int ans=0;
for(int i=head[a];i!=-1;i=Next[i])
{
int b=info[i];
if(b==f) continue;
if(dfs(b,a))
{
dp[a]+=dp[b]+1;
}
else{
dp[a]+=dp[b];
ans++;
}
}
if(ans==0||ans==1) return false;
if(ans>2) dp[a]+=ans-2;
return true;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int i,j,k;
init();
for(i=1;i<n;i++)
{
scanf("%d%d",&j,&k);
add(j,k);
add(k,j);
}
dfs(1,-1);
printf("%d\n",dp[1]*2+1);
}
return 0;
}