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

Sicily 1024. Magic Island

时间:2015-03-31 09:03:59      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:sicily

1024. Magic Island

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

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

Problem Source

ZSUACM Team Member


这里要注意到,有n个点,但是只有n-1条路径,说明是树,用dfs求树的最长路径:

(用c++输入0.35s,用c输入0.18s)

#include <iostream>
#include <vector>
#include <string.h>
#include <cstring>
#include <stdio.h>
using namespace std;

struct Road {
    int to, distance;//目的地和距离
    Road(int new_to, int new_distance) {//这样写为了读入方便
        to = new_to;
        distance = new_distance;
    }
};

vector<Road> roads[10001];//注意这里是二维动态数组
bool vis[10001];
int longest_road, n;

void dfs(int from, int dis) {
    if (dis > longest_road)//更新最长的路径
        longest_road = dis;
    
    vis[from] = true;//这个点已经访问过,不重复访问
    
    for (int i = 0; i < (int)roads[from].size(); i++) {//遍历from所能连通的点并判断是否dfs
        if (!vis[roads[from][i].to]) {
            dfs(roads[from][i].to, dis + roads[from][i].distance);
        }
    }
}

int main() {
    int k, i, temp_from, temp_to, new_distance;
    
    while (cin >> n >> k) {
        
        longest_road = 0;
        memset(vis, false, sizeof(vis));
        memset(roads, 0, sizeof(roads));
        
        for (i = 0; i < n - 1; i++) {
            scanf("%d%d%d", &temp_from, &temp_to, &new_distance);
            roads[temp_from].push_back(Road(temp_to, new_distance));//注意这里两点是互通的
            roads[temp_to].push_back(Road(temp_from, new_distance));
        }
        
        dfs(k, 0);
        printf("%d\n", longest_road);
    }
    return 0;
}


Sicily 1024. Magic Island

标签:sicily

原文地址:http://blog.csdn.net/u012925008/article/details/44763237

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