题意:求树上最远的距离,两次的DFS就行了,保存的是邻接边的信息,还要判断不存在环,不然会RE
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 10110;
struct node{
int to;
int len;
int next;
}eg[2*MAXN];
int head[MAXN];
int idx,nd,Max;
void addEdge(int st,int et,int len){
eg[idx].to = et;
eg[idx].len = len;
eg[idx].next = head[st];
head[st] = idx++;;
}
void dfs(int to,int fr,int dis){
if (dis > Max){
Max = dis;
nd = to;
}
for (int i = head[to]; i != 0; i = eg[i].next){
int a = eg[i].to;
if (a != fr)
dfs(a,to,dis+eg[i].len);
}
}
int main(){
int st,et,len;
idx = 1;
while (scanf("%d%d%d",&st,&et,&len) != EOF){
addEdge(st,et,len);
addEdge(et,st,len);
}
nd = 1;
Max = -1;
dfs(1,0,0);
Max = -1;
dfs(nd,0,0);
printf("%d\n",Max);
return 0;
}