Tree2cycle
Time Limit: 15000/8000 MS (Java/Others) Memory Limit: 102400/102400 K (Java/Others)
Total Submission(s): 1005 Accepted Submission(s): 234
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
3HintIn the sample above, you can disconnect (2,4) and then connect (1, 4) and (3, 4), and the total cost is 3.
Source
思路来源于:男神博客
题意:
给一棵树,去掉一条边和增加一条边的花费都为1,求最小的花费,使该树变成一个环。
思路:
对任意一点dfs,如果一个节点的分支数>=2,则该节点需与其父节点断开(当然根节点就不用了),即
去掉一条边
形成一个游离的链,所有游离的链需要增加一条边连接在根节点所在的链上,然后再用一条边将这条长链首位相连就够了,具体操作实现见代码。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#include <queue>
#include <vector>
#include <cmath>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 1000005
#define INF 0x3f3f3f3f
using namespace std;
int n,m,ans,cnt;
bool vis[maxn];
int pp[maxn];
struct Node
{
int v,next;
}edge[maxn*2];
void addedge(int u,int v)
{
cnt++;
edge[cnt].v=v;
edge[cnt].next=pp[u];
pp[u]=cnt;
}
int dfs(int u) // 返回分支个数 若与父节点断开则返回0
{
int i,j,v,sum=0;
for(i=pp[u];i;i=edge[i].next)
{
v=edge[i].v;
if(!vis[v])
{
vis[v]=1;
sum+=dfs(v);
}
}
if(sum>=2) // 统计ans
{
if(u==1) ans=ans+2*(sum-2); // 根节点形成sum-2个游离链
else ans=ans+2*(sum-1); // 其他点形成sum-1个游离链
return 0;
}
return 1;
}
int main()
{
int i,j,t,u,v;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
cnt=0;
memset(pp,0,sizeof(pp));
for(i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
addedge(u,v);
addedge(v,u);
}
ans=0;
memset(vis,0,sizeof(vis));
vis[1]=1;
dfs(1);
printf("%d\n",ans+1);
}
return 0;
}