原題:
Building and maintaining roads among communities in the far North is an expensive business. With
this in mind, the roads are built in such a way that there is only one route from a village to a village
that does not pass through some other village twice.
Given is an area in the far North comprising a number of villages and roads among them such that
any village can be reached by road from any other village. Your job is to find the road distance between
the two most remote villages in the area.
The area has up to 10,000 villages connected by road segments. The villages are numbered from 1.
Input
The input contains several sets of input. Each set of input is a sequence of lines, each containing three
positive integers: the number of a village, the number of a different village, and the length of the road
segment connecting the villages in kilometers. All road segments are two-way. Two consecutive sets
are separated by a blank line.
Output
For each set of input, you are to output a single line containing a single integer: the road distance
between the two most remote villages in the area.
Sample Input
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
Sample Output
22
題目大意:
要給村莊修路,給出的路線比較特別。任意兩個村莊之間只有一條通路,不會經過一個村莊兩次。問你相距最遠的兩個村莊的距離是多少。
思路見代碼下方:
#include<iostream>#include<algorithm>#include<cstdio>#include<vector>#include<cstring>#include<string>#include<cmath>#include <iomanip>#include<queue>#include<cstring>#include<sstream>using namespace std;const int maxn=10001;int ans=0;vector<pair<int,int> > vp[maxn];//與i串連的村莊號和距離int dfs(int to,int from){ int Aroad=0,tem; for(int i=0;i<vp[to].size();i++) { int go=vp[to][i].first; if(go!=from) { tem=dfs(go,to)+vp[to][i].second; ans=max(ans,tem+Aroad); Aroad=max(tem,Aroad); } } return Aroad;}int main(){ ios::sync_with_stdio(false); int a,b,c; string s; while(!cin.eof()) { for(int i=0;i<maxn;i++) vp[i].clear(); ans=0; getline(cin,s); while(s.length()>0&&!cin.eof()) { stringstream ss; ss<<s; ss>>a>>b>>c; vp[a].push_back(make_pair(b,c)); vp[b].push_back(make_pair(a,c)); getline(cin,s); } dfs(1,0); cout<<ans<<endl; } return 0;}
思路:
這題剛拿來的時候上來我就用floyed,結果肯定逾時。實在不會做了,看別人的題解知道這是一個類似於最小產生樹的一個無根樹。就是任意一個節點都可以當成是根,然後在這個樹上找到的最長距離的兩個節點叫做樹的直徑,仿照別人的代碼寫的。思路就是,找一個節點,例如節點i進行搜尋找到一條最遠的路徑,這條路徑現在記為Aroad,然後回溯搜尋從i出發的另外一條離i最遠的路徑,記為Broad。答案就是相當於以i節點為中介,找到的兩條路的和。剛開始還納悶為什一次搜尋,而且選任意一個點作為搜尋起點就可以,其實還是自己對回溯法理解的比較差,找一個資料自己在紙上類比一下就明白了。
比如如下資料:
1 2 1
2 3 10
2 4 10