Give a tree and find the longest distance between two points.
Idea: the diameter of the bare earth tree. For the first BFs, you can search for a specific point width for the first time. Then, you can use the farthest point in the width search for the last time. The longest distance obtained is the diameter of the tree.
Code:
#include <queue>#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define MAX 80010using namespace std;int points,edges;int head[MAX],total;int next[MAX],aim[MAX],length[MAX];int f[MAX];char s[10];inline void Add(int x,int y,int len);inline void BFS(int start);int main(){cin >> points >> edges;for(int x,y,len,i = 1;i <= edges; ++i) {scanf("%d%d%d%s",&x,&y,&len,s);Add(x,y,len),Add(y,x,len);}BFS(1);int _max = 0;for(int i = 1;i <= points; ++i)if(f[i] > f[_max])_max = i;BFS(_max);int ans = 0;for(int i = 1;i <= points; ++i)if(f[i] > ans)ans = f[i];cout << ans << endl;return 0;}inline void Add(int x,int y,int len){next[++total] = head[x];aim[total] = y;length[total] = len;head[x] = total;}inline void BFS(int start){static queue<int> q;while(!q.empty())q.pop();memset(f,0x3f,sizeof(f));f[0] = f[start] = 0;q.push(start);while(!q.empty()) {int x = q.front(); q.pop();for(int i = head[x];i;i = next[i])if(f[aim[i]] > f[x] + length[i]) {f[aim[i]] = f[x] + length[i];q.push(aim[i]);}}}
Bzoj 3363 poj 1985 cow marathon tree diameter