【Roads in the North】【POJ - 2631】(树的直径)

版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/84389182

题目:

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;
}

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/84389182