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. node
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. ios
3 1 1 2 10 1 3 20
20
本題要求指定起點到全部其餘點的最長路徑,須要遍歷全部頂點,但不必定是全部的邊,DFS更好些,而後直接套用DFS不斷更新長度記錄比較得出最大值便可。 api
// Problem#: 1024 // Submission#: 1788079 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include <iostream> #include <vector> #include <cstring> using namespace std; #define MAX 10010 struct node{ int e,d; node( int a, int b ){ e = a; d = b; } }; vector<node> buffer[MAX]; bool visit[MAX]; int re; void dfs( int v, int len ){ if( len>re ) re = len; visit[v] = true; for( int i=0 ; i<buffer[v].size() ; i++ ){ node temp = buffer[v][i]; if( !visit[temp.e] ){ visit[temp.e] = true; len += temp.d; dfs(temp.e,len); visit[temp.e] = false; len -= temp.d; } } } int main(){ int n,k; int x,y,z; while( cin>>n ){ cin >> k; for( int i=0 ; i<n-1 ; i++ ){ cin >> x >> y >> z; buffer[x].push_back(node(y,z)); buffer[y].push_back(node(x,z)); } memset(visit,0,sizeof(visit)); re = 0; dfs(k,0); cout << re << endl; for( int i=1 ; i<=n ; i++ ) buffer[i].clear(); } return 0; }