【HDU 3848 CC On The Tree】+ 递归

CC On The Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others)
Total Submission(s): 1949 Accepted Submission(s): 681

Problem Description
CC lives on the tree which has N nodes.On every leaf of the tree there is an apple(leaf means there is only one branch connect this node ) .Now CC wants to get two apple ,CC can choose any node to start and the speed of CC is one meter per second.
now she wants to know the shortest time to get two apples;

Input
Thers are many cases;
The first line of every case there is a number N(2<=N<=10000)
if n is 0 means the end of input.
Next there is n-1 lines,on the i+1 line there is three number ai,bi,ci
which means there is a branch connect node ai and node bi.
(1<=ai, bi<=N , 1<=ci<=2000)
ci means the len of the branch is ci meters ;

Output
print the mininum time to get only two apple;

Sample Input
7
1 2 1
2 3 2
3 4 1
4 5 1
3 6 3
6 7 4
0

Sample Output
5

两个叶子节点必有一个相同的父节点,更新父节点的最短和次短叶子节点

AC代码:

#include<cstdio>
#include<algorithm>
using namespace std;
const int K = 1e4 + 10;
const int inf = 0x3f3f3f3f / 2;
struct node{
    int to,vl,next;
}st[K * 2];
int num,n,pr[K],f[K],s[K],head[K];
void add(int a,int b,int c){
    st[num].to = b,st[num].vl = c,st[num].next = head[a],head[a] = num++;
}
void dfs(int a,int b){
    if(pr[a] == 1){ // 叶子节点
        f[a] = 0;
        return ;
    }
    for(int i = head[a]; i != -1; i = st[i].next){
        int ma = st[i].to;
        if(ma == b) continue;
        dfs(ma,a);
        int mb = st[i].vl;
        if(f[a] - f[ma] > mb) s[a] = f[a],f[a] = f[ma] + mb; // 最短
        else if(s[a] - f[ma] > mb) s[a] = f[ma] + mb; // 次短
    }
}
int main()
{
    int a,b,c;
    while(~scanf("%d",&n),n){
        num = 0;
        fill(head,head + n + 1,-1);
        fill(pr,pr + n + 1,0);
        fill(f,f + n + 1,inf);
        fill(s,s + n + 1,inf);
        for(int i = 1; i < n; i++){
            scanf("%d %d %d",&a,&b,&c);
            add(a,b,c),add(b,a,c);
            pr[a]++,pr[b]++;
        }
        if(n == 2){
            printf("%d\n",c);
            continue;
        }
        for(int i = 1; i <= n; i++)
            if(pr[i] > 1){
                dfs(i,-1);
                break;
            }
        int ans = inf;
        for(int i = 1; i <= n; i++)
            if(s[i] && f[i])
                ans = min(ans,s[i] + f[i]);
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值