牛客网多校训练 道路问题

题目描述 

随着如今社会的不断变化,交通问题也变得越来越重要,所以市长决定建设一些公路来方便各个城市之间的贸易和交易。虽然市长的想法很好,但是他也遇到了一般人也经常头疼的问题,那就是手头的经费有限……在规划过程中,设计师们已经预算出部分城市之间建设公路的经费需求。现在市长想知道,它能不能将他的m个城市在有限的经费内实现公路交通。如果可以的话,输出Yes,否则输出No(两个城市不一定要直接的公路相连,间接公路到达也可以。)

输入描述:

测试输入包含多条测试数据
每个测试数据的第1行分别给出可用的经费c(<1000000),道路数目n(n<10000),以及城市数目m(<100)。
接下来的n行给出建立公路的成本信息,每行给出三个整数,分别是相连的两个城市v1、v2(0<v1,v2<=m)以及建设公路所需的成本h(h<100)。

输出描述:

对每个测试用例,输出Yes或No。
示例1

输入

20 10 5
1 2 6
1 3 3
1 4 4
1 5 5
2 3 7
2 4 7
2 5 8
3 4 6
3 5 9
4 5 2

输出

Yes
示例2

输入

10 2 2
1 2 5
1 2 15

输出

Yes

备注:

两个城市之间可能存在多条线路


这是我看到的一个题解
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
int c,m,n,p,q,cost;
int theold[101];//theold[i]的值为i的老大
struct roads
{
    int a,b,cost;
}road[10001];
int cmp(roads x,roads y)//用于使所有道路按照费用从小到大排列
{
    return x.cost<y.cost;
}
void let(int x,int y)//使y的团伙 都认x的老大为老大
{
    for(int i=1;i<=n;i++)
        if(theold[i]==theold[y])
        theold[i]=theold[x];
    return;
}
int main()
{

    cin>>c>>m>>n;
    for(int i=1;i<=n;i++)//各自封王。。。
        theold[i]=i;
    for(int i=0;i<m;i++)
    {
        cin>>p>>q>>cost;
        road[i].a=p,road[i].b=q,road[i].cost=cost;
    }
    sort(road,road+m,cmp);
    for(int i=0;i<m;i++)
    {
        p=road[i].a;q=road[i].b;
        if(theold[p]==theold[q])//如果老大相同,即他们已经相通了,就没必要修路了
            continue;
        c-=road[i].cost;
        let(p,q);
    }
    if(c>=0)cout<<"Yes
";
    else cout<<"No
";
    return 0;
}
原文地址:https://www.cnblogs.com/carcar/p/8445584.html