【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
",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