题目大意:裸的树的直径。
思路:随便用一个点跑BFS,求出这个点到所有点的距离,取距离最长的那个点,再用那个点跑BFS,最远的距离就是这棵树的直径。
CODE:
#include <queue> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAX 20010 using namespace std; int x,y,z; int points; int head[MAX],total; int next[MAX],aim[MAX],length[MAX]; int dis[MAX]; bool v[MAX]; inline void Add(int x,int y,int len); void BFS(int start); int main() { while(scanf("%d%d%d",&x,&y,&z) != EOF) { Add(x,y,z),Add(y,x,z); points = max(max(x,y),points); } BFS(1); int pos_max = 1; for(int i = 1;i <= points; ++i) if(dis[i] > dis[pos_max]) pos_max = i; memset(dis,0,sizeof(dis)); memset(v,false,sizeof(v)); BFS(pos_max); int _max = 0; for(int i = 1;i <= points; ++i) if(dis[i] > _max) _max = dis[i]; cout << _max << 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; } void BFS(int start) { static queue<int> q; while(!q.empty()) q.pop(); q.push(start); while(!q.empty()) { int x = q.front(); q.pop(); v[x] = true; for(int i = head[x];i;i = next[i]) if(!v[aim[i]]) { dis[aim[i]] = dis[x] + length[i]; q.push(aim[i]); } } }
POJ 2631 Roads in the North 树的直径
原文地址:http://blog.csdn.net/jiangyuze831/article/details/39779111