1. 程式人生 > >【POJ2631】Roads in the North 樹的直徑

【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;
}