10308 - Roads in the North (树形dp)

Problem I

Roads in the North

Input: standard input

Output: standard output

Time Limit: 2 seconds

Memory Limit: 32 MB

 

Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are built in such a way 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

The input contains several sets of input. Each set of input 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. Two consecutive sets are separated by a blank line.

Output

For each set of input, you are to output a single line containing 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
题意:给定一个图,要求出图中距离最远两点的距离。。不知道为什么LRJ把这题归入数论

思路:给定的是一个无根图,我们现在任意选一点做根,我是选1这个点因为从1开始1必然存在,然后进行深搜。可以从该点找到最远的两个叶子节点,距离和便是经过1这个点的最远距离。然后在遍历到其他点的时候,可以记录下以其他点为根的最大和情况。这样减少时间复杂度。

代码:

#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
const int N = 10005;

struct M {
	int id, value;
} m;
vector<M> map[N];
char str[105];
int vis[N];
int ans = 0;

int max(int a, int b) {return a > b ? a : b;}

int dfs(int x) {
	int Max = 0;
	int n = map[x].size();
	vis[x] = 1;
	for (int i = 0; i < n; i ++) {
		if (vis[map[x][i].id]) continue;
		int save = dfs(map[x][i].id) + map[x][i].value;
		ans = max(Max + save, ans);
		Max = max(Max, save);
	}
	vis[x] = 0;
	return Max;
}

int main() {
	while (gets(str)) {
		int a, b, value;
		ans = 0;
		memset(vis, 0, sizeof(vis));
		for (int i = 0; i < N; i ++)
			map[i].clear();
		while (str[0] != '\0') {
			sscanf(str, "%d%d%d", &a, &b, &value);
			m.id = b; m.value = value;
			map[a].push_back(m);
			m.id = a; m.value = value;
			map[b].push_back(m);
			if (gets(str) == NULL)
				break;
		}
		dfs(1);
		printf("%d\n", ans);
	}
	return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值