【POJ2631】Roads in the North 树的直径

题目大意:给定一棵 N 个节点的边权无根树,求树的直径。

代码如下

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=1e4+10;

struct node{
    int nxt,to,w;
}e[maxn<<1];
int tot=1,head[maxn];
inline void add_edge(int from,int to,int w){
    e[++tot].nxt=head[from],e[tot].to=to,e[tot].w=w,head[from]=tot;
}
int d1[maxn],d2[maxn],ans;

void dfs(int u,int fa){
    for(int i=head[u];i;i=e[i].nxt){
        int v=e[i].to,w=e[i].w;if(v==fa)continue;
        dfs(v,u);
        if(d1[v]+w>d1[u])d2[u]=d1[u],d1[u]=d1[v]+w;
        else d2[u]=max(d2[u],d1[v]+w);
    }
}

void solve(){
    dfs(1,0);
    for(int i=1;i<=10000;i++)ans=max(ans,d1[i]+d2[i]);
    printf("%d\n",ans);
}

int main(){
    int from,to,w;
    while(scanf("%d%d%d",&from,&to,&w)!=EOF){
        add_edge(from,to,w),add_edge(to,from,w);
    }
    solve();
    return 0;
}

转载于:https://www.cnblogs.com/wzj-xhjbk/p/10020707.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值