【POJ】1985 - Cow Marathon(树的直径)

点击打开题目

Cow Marathon
Time Limit: 2000MS Memory Limit: 30000K
Total Submissions: 4846 Accepted: 2371
Case Time Limit: 1000MS

Description

After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms. 

Input

* Lines 1.....: Same input format as "Navigation Nightmare".

Output

* Line 1: An integer giving the distance between the farthest pair of farms. 

Sample Input

7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S

Sample Output

52

Hint

The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52. 

Source




这里用邻接表来存图,读图的时候效率高了很多。

树的直径用了两次dfs,第一次求距任意一点最远的点,第二次从这个点开始dfs到最远点,这个就是直径了。


第一次初始化的函数忘了调用了居然都AC了,被媳妇儿检查出来了,还是改改吧。


代码如下:

#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define MAX 40000
int n,m;
vector<int> mapp[MAX+5];
vector<int> dis[MAX+5];
int f[MAX+5];		//距离当前点的距离 
bool vis[MAX+5];
void init()
{
	for (int i = 1 ; i <= n ; i++)
	{
		mapp[i].clear();
		dis[i].clear();
	}
}
int dfs(int x)
{
	int ans;		//最远点 
	int maxx = 0;		//最大距离 
	queue<int> q;		//存放根 
	CLR(vis,false);
	CLR(f,0);
	f[x] = 0;
	q.push(x);
	vis[x] = true;
	while (!q.empty())
	{
		int st = q.front();
		q.pop();
		for (int i = 0 ; i < mapp[st].size() ; i++)
		{
			if (!vis[mapp[st][i]])		//该点没有用过 
			{
				q.push(mapp[st][i]);
				f[mapp[st][i]] = f[st] + dis[st][i];
				vis[mapp[st][i]] = true;
				if (f[mapp[st][i]] > maxx)
				{
					maxx = f[mapp[st][i]];
					ans = mapp[st][i];		//记录节点 
				}
			}
		}
	}
	return ans;
}
int main()
{
	while (~scanf ("%d %d",&n,&m))
	{
		init();
		for (int i = 1 ; i <= m ; i++)
		{
			int t1,t2,t3;
			char t4[3];
			scanf ("%d %d %d %s",&t1,&t2,&t3,t4);
			mapp[t1].push_back(t2);
			dis[t1].push_back(t3);
			mapp[t2].push_back(t1);		//求树的直径一定要双向存图 
			dis[t2].push_back(t3);
		}
		int st = dfs(1);		//任意从一点开始bfs
		int ans = dfs(st);
		printf ("%d\n",f[ans]);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值