Gym 100712F Travelling Salesman

Question:
After leaving Yemen, Bahosain now works as a salesman in Jordan. He spends most of his time travelling
between different cities. He decided to buy a new car to help him in his job, but he has to decide about the
capacity of the fuel tank. The new car consumes one liter of fuel for each kilometer.
Each city has at least one gas station where Bahosain can refill the tank, but there are no stations on the roads
between cities.
Given the description of cities and the roads between them, find the minimum capacity for the fuel tank
needed so that Bahosain can travel between any pair of cities in at least one way.
Input
The first line of input contains T (1 ≤ T ≤ 64)​that represents the number of test cases.
The first line of each test case contains two integers: N (3 ≤ N ≤ 100,000)​and M (N-1 ≤ M ≤ 100,000)​,
where N​is the number of cities, and M​is the number of roads.
Each of the following M​lines contains three integers: X Y C (1 ≤ X, Y ≤ N)(X ≠ Y)(1 ≤ C ≤ 100,000)​, where
C​is the length in kilometers between city X​and city Y​. Roads can be used in both ways.
It is guaranteed that each pair of cities is connected by at most one road, and one can travel between any pair
of cities using the given roads.
Output
For each test case, print a single line with the minimum needed capacity for the fuel tank.
Sample Input Sample Output
input
2
6 7
1 2 3
2 3 3
3 1 5
3 4 4
4 5 4
4 6 3
6 5 5
3 3
1 2 1
2 3 2
3 1 3
output
4
2
題目大意:有n個村莊,其間有m條路,任意兩個村莊之間沒有加油站,只有村莊裏有,問一輛車通往任意兩個村莊其油箱至少爲多大
解題思路:這是一個最小生成樹,對距離升序排序,依次遍歷,在最小生成樹中找到最大的距離
(http://acm.hust.edu.cn/vjudge/contest/130407#problem/F)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=1e5+5;
struct node
{
    int s,d,cost;
}a[MAXN];
int f[MAXN],n,m;
bool cmp(node x,node y)
{
    return x.cost<y.cost;
}
int findx(int n)
{
    if(f[n]!=n)
       return (f[n]=findx(f[n]));
    else return f[n];
}
void Union(int x,int y)
{
    int t1=findx(x),t2=findx(y);
    t1<t2?f[t2]=t1:f[t1]=t2;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<MAXN;i++)
            f[i]=i;
        for(int i=1;i<=m;i++)
            scanf("%d%d%d",&a[i].s,&a[i].d,&a[i].cost);
        sort(a+1,a+m+1,cmp);
        int MAX=-INF;
        for(int i=1;i<=m;i++)
        {
            if(findx(a[i].s)!=findx(a[i].d))
            {
                Union(a[i].s,a[i].d);
                MAX=max(MAX,a[i].cost);
            }
        }
        printf("%d\n",MAX);
    }
}

體會:這道題是最少生成樹的裸題,但當時自己sb了,以爲是dij,啊太痛苦了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章