hdu 4714 Tree2cycle

Tree2cycle

Time Limit: 15000/8000 MS (Java/Others) Memory Limit: 102400/102400 K (Java/Others)
Total Submission(s): 748 Accepted Submission(s): 172

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.
 

 

Source
 

 

Recommend
liuyiding
这题 我们主要,根据一点,如果,一个树,它的子树,有一个是超过2个结点的,我们就可以把这个子树,分离开来,子树化成一条直线,最终把所有的小直线相连,就可以得到一个环,而且,得到的一定 是最小值 !
#pragma comment(linker,"/STACK:1024000000,1024000000")

#include <iostream>

#include <stdio.h>

#include <vector>

#include <string.h>

using namespace std;

#define MAXN 1000050

int visit[MAXN],ans;

vector<int> vec[MAXN];

int dfs(int u)

{

    visit[u]=1;

    int i,res=0;

    for(i=0;i<vec[u].size();i++)

    {

        if(!visit[vec[u][i]])

        res+=dfs(vec[u][i]);

    }

    if(res>=2)

    {

        if(u==1)

        ans+=res-2;

        else

        ans+=res-1;

        return 0;

    }

    else

    return 1;

}

int main()

{

    int n,i,tcase,s,e;

    scanf("%d",&tcase);

    while(tcase--)

    {

        scanf("%d",&n);

        for(i=1;i<=n;i++)

        vec[i].clear();

        for(i=1;i<n;i++)

        {

            scanf("%d%d",&s,&e);

            vec[s].push_back(e);

            vec[e].push_back(s);

        }

        ans=0;

        memset(visit,0,sizeof(visit));

        dfs(1);

        printf("%d\n",2*ans+1);

    }

    return 0;

}



 

 

你可能感兴趣的:(tree)