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
城市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; }