uva 10308 Roads in the North 北方的道路

原题:
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

你可能感兴趣的:(uva)