sicily 1024 Magic Island

Description

There are N cities and N-1 roads in Magic-Island. You can go from one city to any other. One road only connects two cities. One day, The king of magic-island want to visit the island from the capital. No road is visited twice. Do you know the longest distance the king can go.

Input

There are several test cases in the input
A test case starts with two numbers N and K. (1<=N<=10000, 1<=K<=N). The cities is denoted from 1 to N. K is the capital.

The next N-1 lines each contain three numbers XYD, meaning that there is a road between city-X and city-Y and the distance of the road is D. D is a positive integer which is not bigger than 1000.
Input will be ended by the end of file.

Output

One number per line for each test case, the longest distance the king can go. 

Sample Input

3 1
1 2 10
1 3 20

Sample Output

20

分析:

本题要求指定起点到所有其他点的最长路径,需要遍历所有顶点,但不一定是所有的边,DFS更好些,然后直接套用DFS不断更新长度记录比较得出最大值即可。

代码:

 1 // Problem#: 1024
 2 // Submission#: 1788079
 3 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
 4 // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
 5 // All Copyright reserved by Informatic Lab of Sun Yat-sen University
 6 #include <iostream>
 7 #include <vector>
 8 #include <cstring>
 9 using namespace std;
10 
11 #define MAX 10010
12 
13 struct node{
14     int e,d;
15     node( int a, int b ){
16     e = a; d = b;
17     }
18 };
19 
20 vector<node> buffer[MAX];
21 bool visit[MAX];
22 int re;
23 
24 void dfs( int v, int len ){
25     if( len>re ) re = len;
26     visit[v] = true;
27     for( int i=0 ; i<buffer[v].size() ; i++ ){
28     node temp = buffer[v][i];
29     if( !visit[temp.e] ){
30         visit[temp.e] = true;
31         len += temp.d;
32         dfs(temp.e,len);
33         visit[temp.e] = false;
34         len -= temp.d;
35     }
36     }
37 }
38 
39 int main(){
40     int n,k;
41     int x,y,z;
42     while( cin>>n ){
43     cin >> k;
44     for( int i=0 ; i<n-1 ; i++ ){
45         cin >> x >> y >> z;
46         buffer[x].push_back(node(y,z));
47         buffer[y].push_back(node(x,z));
48     }
49     memset(visit,0,sizeof(visit));
50     re = 0;
51     dfs(k,0);
52     cout << re << endl;
53     for( int i=1 ; i<=n ; i++ )
54         buffer[i].clear();
55     }
56     return 0;
57 }

 

转载于:https://www.cnblogs.com/ciel/archive/2013/01/25/2876761.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值