【Roads in the North】【POJ - 2631】(樹的直徑)
題目:
Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such that there is only one route from a village to a village that does not pass through some other village twice.
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area.
The area has up to 10,000 villages connected by road segments. The villages are numbered from 1.
Input
Input to the problem is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way.
Output
You are to output a single integer: the road distance between the two most remote villages in the area.
Sample Input
5 1 6 1 4 5 6 3 9 2 6 8 6 1 7
Sample Output
22
解題報告:樹的直徑的求解,詳解見:https://blog.csdn.net/qq_42505741/article/details/81358771
ac程式碼:
#include<queue> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; //樹的直徑 bfs搜尋 const int maxn =1e5+8; struct node{ int id; int d; int nxet; }side[maxn];//存放邊的起始點,長度 int head[maxn];//定義頭節點 int cnt=0; void init() { memset(head,-1,sizeof(head)); cnt=0; } void add(int x,int y,int d) { side[cnt].id=y; side[cnt].d=d; side[cnt].nxet=head[x]; head[x]=cnt++;//head陣列的不斷更新 使side的next始終保持指向下一節點的狀態 }//head在每次更新 將之前的位置送給next 自己再存放新的數值 struct Node{ int id; int d; }; int mark[maxn]; int bfs(int x,int &d) { memset(mark,0,sizeof(mark)); queue<Node> q; Node tmp; tmp.id=x; tmp.d=0; q.push(tmp); mark[x]=1; int mx=0,ans=x; while(q.size()) { tmp=q.front(); q.pop(); for(int i=head[tmp.id];i!=-1;i=side[i].nxet) { int y=side[i].id; if(mark[y]) continue; mark[y]=1; Node nd; nd.id=y; nd.d=tmp.d+side[i].d; if(nd.d>mx) { mx=nd.d; ans=y; } q.push(nd); } } d=mx; return ans; } int main() { init(); int x,y,w; while(scanf("%d%d%d",&x,&y,&w)!=EOF) { add(x,y,w); add(y,x,w); } int d; int u=bfs(1,d); int v=bfs(u,d); printf("%d\n",d); return 0; }