码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 2631 Roads in the North 树的直径

时间:2014-10-04 16:32:56      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:poj   poj2631      树的直径   

题目大意:裸的树的直径。


思路:随便用一个点跑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 树的直径

标签:poj   poj2631      树的直径   

原文地址:http://blog.csdn.net/jiangyuze831/article/details/39779111

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!