sicily 1024. Magic Island

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 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

3 1
1 2 10
1 3 20

Sample Output

20


题目分析

典型的深搜题目,大意是m座城市有m-1条路,把国王从首都放出去走,一条路只能走一次,看他最多能跑多远
首先这是无向图
注意到m座城市只有m-1条路,同时题目中暗示了这是个联通图,
所以不存在环路,即不可能走过同一个城市两次
这样题目在搜索前的判断条件就简单很多,只需要开一个数组存储每个城市是否visited即可
同时城市上界是10000,如果开10000*10000的数组来存储每两个城市的联通情形会内存爆炸,所以采用struct来进行存储,结构如下
struct Path {
  std::vector<int> end; // 存储可达城市
  std::vector<int> length; // 存储与上对应的路径长度
} paths[10002];
最后在无路可走的时候更新最大值即可
如果存在环的话,只要结构体里加上std::vector<bool> visited来记录这条路是否走过即可

#include <cstdio>
#include <memory.h>
#include <iostream>
#include <vector>

struct Path {
  std::vector<int> end; // record which city could be reached
  std::vector<int> length; // record the length of the path
} paths[10002];
bool visited[10002];
int max;
int tempmax;

void dfs(int start) {
  bool isEnd = true;
  visited[start] = true;
  std::vector<int>::iterator endit, lenit;
  for (endit = paths[start].end.begin(), lenit = paths[start].length.begin();
         endit != paths[start].end.end(), lenit != paths[start].length.end();
         ++endit, ++lenit) {
    if (!visited[*endit]) {
      isEnd = false;
      tempmax += *lenit;
      dfs(*endit);
      tempmax -= *lenit;
    }
  }
  if (isEnd) // record whether there is not any way could be visited
    max = max > tempmax ? max : tempmax;
  visited[start] = false;
}

int main()
{
  int num, capital;
  while (EOF != scanf("%d%d", &num, &capital)) {
    for (int i = 1; i <= num; ++i) {
      if (!paths[i].end.empty())
        paths[i].end.clear();
      if (!paths[i].length.empty())
        paths[i].length.clear();
    }
    tempmax = max = 0;
    memset(visited, 0, sizeof(visited));

    int Start, End, Len;
    for (int i = 0; i < num-1; ++i) {
      scanf("%d%d%d", &Start, &End, &Len);
      paths[Start].end.push_back(End);
      paths[Start].length.push_back(Len);
      paths[End].end.push_back(Start);
      paths[End].length.push_back(Len);
    }
    dfs(capital);

    printf("%d\n", max);
  }
}


你可能感兴趣的:(sicily 1024. Magic Island)