文章标题

来源:互联网 发布:12123app网络请求失败 编辑:程序博客网 时间:2024/06/05 14:52

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 X, Y, D, 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
Copy sample input to clipboard
3 1
1 2 10
1 3 20
Sample Output
20

#include <iostream>#include <vector>#include <cstring>using namespace std;int MAX;bool visit[11000];struct Edge {    int x, y, dis;    Edge (int xx, int yy, int dist) {        x = xx;        y = yy;        dis = dist;    }};vector<Edge> vec[11000];void DFS(int x, int dis1) {    if (dis1 > MAX) MAX = dis1;    visit[x] = true;    for (int i = 0; i < vec[x].size(); i++) {        if (visit[vec[x][i].y]) continue;        DFS(vec[x][i].y, dis1+vec[x][i].dis);    }    visit[x] = false;}int main(int argc, char **argv){    int N, K;    int x, y, dis;    while (cin >> N >> K) {        MAX = 0;         memset(visit, 0, sizeof(visit));         memset(vec, 0, sizeof(vec));         for (int i = 0; i < N-1; i++) {               cin >> x >> y >> dis;               vec[x].push_back(Edge(x, y, dis));               vec[y].push_back(Edge(y, x, dis));          }          DFS(K, 0);          cout << MAX << endl;    }    return 0;}
0 0