传送门:http://poj.org/problem?id=2631
这题是求树的直径的裸题,没啥的,原理也挺简单,两次BFS就出了,需要注意的可能就是数据范围,数据读入吧,没判断重边也没啥坑好像……
上一波C艹实现
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 20010;
struct node{
int v, w, next;
}edge[MAXN];
int head[MAXN], cnt = 0, dis[MAXN];
void add(int u, int v, int w){
edge[++cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt;
}
int BFS(int x){
memset(dis, 0x3f, sizeof(dis));
queue<int> q;
dis[x] = 0;
q.push(x);
while(!q.empty()){
int temp = q.front();
q.pop();
for(int i = head[temp]; i != 0;i = edge[i].next){
if(dis[edge[i].v] > dis[temp] + edge[i].w){
dis[edge[i].v] = dis[temp] + edge[i].w;
q.push(edge[i].v);
if(dis[edge[i].v] > dis[x])
x = edge[i].v;
}
}
}
return x;
}
int main()
{
//freopen("input.txt", "r", stdin);
int u, v, w;
memset(head, 0, sizeof(head));
while(scanf("%d %d %d", &u, &v, &w) != EOF){
add(u, v, w);
add(v, u, w);
}
int z = BFS(1);
int e = BFS(z);
printf("%d\n", dis[e]);
return 0;
}