码迷,mamicode.com
首页 > 其他好文 > 详细

sicily1024 Magic Island(图的遍历)

时间:2017-01-07 20:38:37      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:next   store   遍历   res   distance   lan   names   图的遍历   struct   

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

 

城市i对应的连接的路存到vector类型的cities[i]中;

每一条路有对应的id;

用visited[id]来记录是否已经走过这条路;

 

以下是代码:

#include <iostream>
#include <vector>
using namespace std;

struct road{
    int id;            // every road has a unique id 
    int end;        // connect to which city
    int length;        // the length of this road
    road(int i, int e, int l) {
        id = i, end = e, length = l;
    }
};

#define MAX 10001
bool visited[MAX];    // when the road i is visited, visited[i] = true 
vector<road> cities[MAX];    // cities[i] stores all roads connecting the city i
int maxLength;

void dfs(int k, int total = 0) {
    for (int i = 0; i < cities[k].size(); i++) {
        // when the road has not visited
        if (!visited[cities[k][i].id]) {
            // visit the road
            visited[cities[k][i].id] = true;
            total += cities[k][i].length;
            if (total > maxLength) maxLength = total;
            // visit all roads connecting the city ‘cities[k][i].end‘
            dfs(cities[k][i].end, total);
            // unvisit the road
            visited[cities[k][i].id] = false;
            total -= cities[k][i].length;
        }
    }
}

int main() {
    int n, k;
    while (cin>>n>>k) {
        for (int i = 1; i <= n; i++) {    // initial
            visited[i] = false;
            cities[i].clear();
        }
        for (int i = 1; i < n; i++) {
            int x, y, l;
            cin>>x>>y>>l;
            cities[x].push_back(road(i, y, l));
            cities[y].push_back(road(i, x, l));
        }
        maxLength = 0;
        dfs(k);
        cout<<maxLength<<endl;
    }
    return 0;
}

 

sicily1024 Magic Island(图的遍历)

标签:next   store   遍历   res   distance   lan   names   图的遍历   struct   

原文地址:http://www.cnblogs.com/zmj97/p/6260200.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!