题面:http://poj.org/problem?id=2631
本题是求树的直径裸题。
Code:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<ctime>
using namespace std;
const int MAXN=10005;
struct Node{
int v,Next,w;
}Edge[MAXN*2];
int head[MAXN],maxDis,Cnt,maxInd;
void Push(int u,int v,int w){
++Cnt;
Edge[Cnt].v=v;
Edge[Cnt].w=w;
Edge[Cnt].Next=head[u];
head[u]=Cnt;
}
void dfs(int now,int fa,int dis){
if(dis>maxDis){
maxDis=dis;
maxInd=now;
}
for(int i=head[now];i;i=Edge[i].Next){
if(Edge[i].v!=fa){
dfs(Edge[i].v,now,Edge[i].w+dis);
}
}
}
int main(){
int u,v,w;
while(~scanf("%d%d%d",&u,&v,&w)){
Push(u,v,w);
Push(v,u,w);
}
dfs(1,0,0);
dfs(maxInd,0,0);
printf("%d\n",maxDis);
return 0;
}