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
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
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; }