您的位置:首页 > 其它

HDU 4714 Tree2cycle 构造出一种链的方法

2013-09-08 23:59 232 查看


Tree2cycle

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.

http://blog.csdn.net/dongdongzhang_/article/details/11395305 可以看他的博客喔。。

但还是有些要注意的。

比如 dfs 深搜时,由于栈内存只有1M。所以要用

#pragma comment(linker,"/STACK:102400000,102400000")


这条语句,而且这种是c++编译器的加法,gcc不是这种。。

然后还要注意的是,边的内存是顶点数*2-2

代码

//
//  4714.cpp
//  ACM_HDU
//
//  Created by ipqhjjybj on 13-9-8.
//  Copyright (c) 2013年 ipqhjjybj. All rights reserved.
//

#pragma comment(linker,"/STACK:102400000,102400000")
#include <cstdio>
#include <iostream>
using namespace std;
const int N=1111111;
int n;
struct node{
int to,next;
}Edge[N<<1];
int head
,cnt;
bool visit
;
void addEdge(int u,int v){
Edge[cnt].to=v;
Edge[cnt].next=head[u];
head[u]=cnt++;
}
int ans;
int dfs(int u){
int sum=0;
visit[u]=true;
for(int q=head[u];q!=-1;q=Edge[q].next){
if(!visit[Edge[q].to])
sum+=dfs(Edge[q].to);
}
if(sum>1){
if(u==1)
ans+=(sum-2)*2;
else ans+=(sum-1)*2;
return 0;
}
return 1;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
cnt=0;
memset(head,-1,sizeof(int)*(n+10));
memset(visit,false,sizeof(false)*(n+10));
for(int i=1,u,v;i<n;i++){
scanf("%d %d",&u,&v);
addEdge(u,v);
addEdge(v,u);
}
ans=0;
dfs(1);
printf("%d\n",ans+1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU ACM 构造图形