hdu 3848 CC On The Tree 求树上最近的叶子节点距离

本文探讨了在一个具有N个节点的树形结构中寻找两个叶子节点间的最短路径问题。通过深度优先搜索算法(DFS),实现了计算从任意起点到两特定叶子节点所需最短时间的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

//


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int inf=(1<<28);
const int maxn=21000;
struct Node
{
    int t,w;
    int next;
};
int n;
int p[maxn];
int du[maxn];
int l;
Node G[maxn];
int ans;
int min1[maxn],min2[maxn];
void init()
{
    memset(du,0,sizeof(du));
    memset(p,-1,sizeof(p));
    l=0;
    ans=inf;
}
void addedge(int u,int t,int w)
{
    G[l].t=t;
    G[l].w=w;
    G[l].next=p[u];
    p[u]=l++;
}
int temp[4];
int pl;
void dfs(int u,int fath)
{
    if(du[u]==1&&u!=1)
    {
        min1[u]=0;min2[u]=inf;
        return ;
    }
    min1[u]=min2[u]=inf;
    for(int i=p[u];i!=-1;i=G[i].next)
    {
        int t=G[i].t,w=G[i].w;
        if(t==fath) continue;
        dfs(t,u);
        temp[0]=min1[u],temp[1]=min2[u];
        temp[2]=min1[t]+w,temp[3]=min2[t]+w;
        sort(temp,temp+4);
        min1[u]=temp[0],min2[u]=temp[1];
    }
    ans=min(ans,min1[u]+min2[u]);
}
int main()
{
    while(scanf("%d",&n)==1&&n)
    {
        init();
        for(int i=0;i<n-1;i++)
        {
            int u,t,w;scanf("%d%d%d",&u,&t,&w);
            addedge(u,t,w);
            addedge(t,u,w);
            du[u]++,du[t]++;
        }
        dfs(1,-1);
        if(du[1]==1) ans=min(ans,min1[1]);
        printf("%d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值