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

来源:互联网 发布:人工智能有哪些分支 编辑:程序博客网 时间:2024/06/05 10:15

点击打开题目

Roads in the North
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 2526 Accepted: 1241

Description

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 61 4 56 3 92 6 86 1 7

Sample Output

22

Source

The UofA Local 1999.10.16



清新脱俗的邻接表 + 队列 + 两次dfs就可以啦。


代码如下:

#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 10000int n;vector<int> mapp[MAX+5];vector<int> dis[MAX+5];int f[MAX+5];//距离当前点的距离 bool vis[MAX+5];int dfs(int x){int ans;//最远点 int maxx = 0;//最大距离 queue<int> q;//存放根 CLR(vis,false);CLR(f,0);f[x] = 0;vis[x] = true;q.push(x);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]);vis[mapp[st][i]] = true;f[mapp[st][i]] = f[st] + dis[st][i];if (f[mapp[st][i]] >= maxx){maxx = f[mapp[st][i]];ans = mapp[st][i];//记录节点 }}}}return ans;}int main(){int t1,t2,t3;for (int i = 0 ; i <= MAX ; i++){mapp[i].clear();dis[i].clear();}n = 0;while (scanf ("%d %d %d",&t1,&t2,&t3) != EOF){mapp[t1].push_back(t2);mapp[t2].push_back(t1);dis[t1].push_back(t3);dis[t2].push_back(t3);n = max(max(t1,t2),n);}if (n == 0)//POJ的编译器没这个就RE,我的就可以(哭) {printf ("0\n");return 0;}int st = dfs(n);int ans = dfs(st);printf ("%d\n",f[ans]);return 0;}


0 0
原创粉丝点击