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
Hint
In the sample above, you can disconnect (2,4) and then connect (1, 4) and
(3, 4), and the total cost is 3.
思路:这个题目很多博客都说是树形dp,确实可以用树形dp去做,但是很多博客写的方法,更像是贪心的算法。说一说我的做法:
对于子分支大于等于2的点来说,首先我们需要将子分支都连成一条链,假如说有三个分支,那么两个分支连成一条链,剩下的那一个就要断掉,同时还要将这个点与父亲节点的边也断掉。也就是说断掉了sum-2+1条边。但是如果这个点是根节点的话,就不用断和父节点的了,那么也就是断掉了sum-2条边。我们计算出一共断掉了多少条边,假设是ans条,这些条还要再连接上,总共的花费就是ans * 2,最终再首尾相连,最终答案是ans * 2+1.
为什么这样断是最优的呢?我说一下我的理解:对于一个子分支大于等于2的节点来说,如果不断掉与父节点之间的边,那么就要断掉sum1-1个子分支,但是对于父节点来说,也要断掉sum2-1个子分支.但是如果断掉的话,可能父节点就不会断这些子分支,如图所示:
我们按照正解,做法是断掉3-5,3-1,将5链接到6上,将5-7这条链链接到4上,再链接2-7,这样花费是2*2+1=5;
误解:断掉3-5,3-7,2-1,2-4,这样做法是4 * 2+1=9,明显不如上一种解法优。
正解做法尽可能的使得边能不删就不删。
这个题的坑点(hdu的锅)
①c++交题
②手动扩栈
③数组开2e6.
代码如下:
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#define ll long long
using namespace std;
const int maxx=1e6+100;
struct edge{
int to,next;
}e[maxx<<1];
int head[maxx];
int n,tot;
inline void init()
{
tot=0;
for(int i=0;i<2*n+1;i++) head[i]=-1;
}
inline void add(int u,int v)
{
e[tot].next=head[u],e[tot].to=v,head[u]=tot++;
}
inline int dfs(int u,int f,int &ans)
{
int sum=0;
for(int i=head[u];i!=-1;i=e[i].next)
{
int to=e[i].to;
if(to==f) continue;
sum+=dfs(to,u,ans);
}
if(sum>=2)
{
if(u==1) ans+=sum-2;
else ans+=sum-1;
return 0;
}
return 1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
init();
int x,y;
for(int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
int ans=0;
dfs(1,0,ans);
printf("%d\n",ans*2+1);
}
return 0;
}
努力加油a啊,(o)/~