HDU - 4714 Tree2cycle

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.

 

 

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。对于每一个节点,判断它的度,如果度超过2,则每个多余的度需要删除一条边和增加一条边。所以结果是2*sum,同时对于根节点需要有一条边构成圆,因此最终结果是2 * sum + 1。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
 
const int MAXN = 1e6 + 10;
struct edge
{
	int to, next;
}edge[MAXN << 1];
 
int tot, head[MAXN], n, num;
 
void init()
{
    tot = 0;
    memset(head, -1, sizeof(head));
}
 
void addEdge(int u, int v)
{
	tot++;
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot;
}
 
int dfs(int node, int fa)
{
    int degree = 0;
    for (int i = head[node]; i > 0; i = edge[i].next)
    {
        int peer = edge[i].to;
		if (peer != fa)
		{
			degree += dfs(peer, node);
		}
    }
    
    if (degree > 1)
    {
        if (fa == -1)
		{
			num += degree - 2;
		}
        else
		{
			num += degree - 1;
		}
 
        return 0;
    }
 
    return 1;
}
 
int main()
{
	int t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d", &n);
        init();
        num = 0;
        for (int i = 1; i < n; i++)
        {
            int u, v;
            scanf("%d%d", &u, &v);
            addEdge(u, v);
            addEdge(v, u);
        }
        int temp = dfs(1, -1);
        printf("%d\n", 2 * num + 1);
    }
 
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值