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

73 篇文章 21 订阅
56 篇文章 0 订阅

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.




但还是有些要注意的。

比如 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[N],cnt;
bool visit[N];
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;
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值