1024x768 Magic Island Constraints
Time limit:1 secs, Memory limit:32 MB
Description
There is N cities and N-1 roads in Magic-island. You can go from one city to any other. One road is only connects and cities. One day, the king of Magic-island want to visit the No Road is visited twice. Do know the longest distance the king can go.
Input
There is several test cases in the input
A test case is starts with the numbers N and K. (1<=n<=10000, 1<=k<=n). The cities is denoted from 1 to N. K are the capital.
The next N-1 lines each contain three numbers X, Y, D, meaning this there is a road between CIT Y-x and City-y and the distance of the road are d. D is a positive integer which are not bigger than 1000.
Input would 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 11 2 101 3 20
Sample Output
20
Problem Source
ZSUACM Team Member
Note here that there are n points, but only the n-1 path, which is the tree, with the longest path of the Dfs tree:
(Input 0.35s in C + +, input 0.18s with C)
#include <iostream> #include <vector> #include <string.h> #include <cstring> #include < Stdio.h>using namespace Std;struct Road {int to, distance;//destination and distance road (int new_to, int new_distance) {//This is written in order to read in Convenient to = new_to; Distance = new_distance; }};vector<road> roads[10001];//Note Here is a two-dimensional dynamic array bool Vis[10001];int longest_road, n;void dfs (int from, int dis) {if (d is > Longest_road)//update longest path longest_road = dis; Vis[from] = true;//This point has been accessed without repeated access for (int i = 0; i < (int) roads[from].size () i++) {//traverse the point from which the from can be communicated and determine if the 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));//note Here are two points of exchange Roads[temp_to].push_back (road (Temp_from, N Ew_distance)); } dfs (k, 0); printf ("%d\n", longest_road); } return 0;}
Sicily 1024. Magic Island