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.
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).
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
题意:题目的意思转化一下就是让你求分支树*2+1
如何求分支数?直接考虑每个子树对答案的贡献就行(注意根节点要选择2条作为非分支,因为这样可以保证主干最长)
代码:(友情提示,交c++)
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<map>
#include<string>
#include<cstring>
#include<vector>
#include<algorithm>
#include<set>
#include<sstream>
#include<cstdio>
#include<unordered_map>
#include<unordered_set>
#include<cmath>
#include<climits>
using namespace std;
const int maxn=2e6+9;
int head[maxn];
int num;
int ans;
int n,m;
struct Edge
{
int u,v,w,next;
}edge[maxn];
void addEdge(int u,int v,int w)
{
edge[num].u=u;
edge[num].v=v;
edge[num].w=w;
edge[num].next=head[u];
head[u]=num++;
}
void init()
{
memset(head,-1,sizeof(head));
ans=0;
num=0;
}
int dfs(int u,int fa)
{
int tmp=0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==fa) continue;
tmp+=dfs(v,u);
}
if(tmp>=2)
{
if(u==1)
{
ans+=tmp-2;
}
else
{
ans+=tmp-1;
}
return 0;
}
else
{
return 1;
}
}
int main(int argc, char const *argv[])
{
int T;
cin>>T;
while(T--)
{
init();
scanf("%d",&n);
for(int i=1;i<n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
addEdge(u,v,0);
addEdge(v,u,0);
}
dfs(1,-1);
printf("%d\n",ans*2+1);
}
return 0;
}
本文介绍了一种算法,用于解决给定一棵N个节点的树,如何以最小的成本将其转化为一个环的问题。通过深度优先搜索计算分支数目,并最终得出转换所需的最小成本。
2910

被折叠的 条评论
为什么被折叠?



