zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    对象中属性 加锁 用:volatile 关键词修饰 而 不用 synchronized 加锁
    利用URL重写实现参数目录化
    外部联接
    快速获取表的记录数
    SQL SEVER 元年是1900年
    SQL SERVER的浮点数类型及与C#的对应关系
    接口中包含抽象类demo
    接口的实际应用demo
    多态demo2
    抽象类的实际应用demo
  • 原文地址:https://www.cnblogs.com/ciel/p/2876761.html
Copyright © 2011-2022 走看看