链接:https://ac.nowcoder.com/acm/problem/15108
来源:牛客网
题目描述
随着如今社会的不断变化,交通问题也变得越来越重要,所以市长决定建设一些公路来方便各个城市之间的贸易和交易。虽然市长的想法很好,但是他也遇到了一般人也经常头疼的问题,那就是手头的经费有限……在规划过程中,设计师们已经预算出部分城市之间建设公路的经费需求。现在市长想知道,它能不能将他的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
备注:
两个城市之间可能存在多条线路
最小生成树模板题,直接上代码(kruskal算法)。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e5+10;
int par[105];
struct node{
int from,to,cost;
}no[maxn*4];
void init()
{
for(int i=0;i<maxn;i++)
par[i]=i;
}
int find(int x)
{
return par[x]==x?x:par[x]=find(par[x]);
}
void unite(int x,int y)
{
x=find(x);
y=find(y);
if(x!=y)
par[x]=y;
}
bool same(int x,int y)
{
return find(x)==find(y);
}
int n,m,mo;
bool cmp(node x,node y)
{
return x.cost<y.cost;
}
int kruskal()
{
int sum=0;
for(int i=0;i<m;i++)
{
node a=no[i];
if(!same(a.from,a.to)){
unite(a.from,a.to);
sum+=a.cost;
}
}
return sum;
}
int main()
{
ios::sync_with_stdio(false);
while(cin>>mo>>m>>n)
{
init();
for(int i=0;i<m;i++)
{
cin>>no[i].from>>no[i].to>>no[i].cost;
}
sort(no,no+m,cmp);
int p=kruskal();
if(p<=mo)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}