Gym 100712F Travelling Salesman

来源:互联网 发布:三国之数据辅助 编辑:程序博客网 时间:2024/05/20 10:55

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,啊太痛苦了

0 0
原创粉丝点击