PTA畅通工程之最低成本建设问题c++版——山东科技大学

题目:
某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了有可能建设成快速路的若干条道路的成本,求畅通工程需要的最低成本。
输入格式:
输入的第一行给出城镇数目N (1<N≤1000)和候选道路数目M≤3N;随后的M行,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号(从1编号到N)以及该道路改建的预算成本。
输出格式:
输出畅通工程需要的最低成本。如果输入数据不足以保证畅通,则输出“Impossible”。
输入样例1:

6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3

输出样例1:

12

输入样例2:

5 4
1 2 1
2 3 2
3 1 3
4 5 4

输出样例2:

Impossible
#include<bits/stdc++.h>
using namespace std;
struct LOAD
{
    
    
    int from,to;
    int money;
}load[3005];
int father[1005];
int n,m;
bool cmp(LOAD a,LOAD b)
{
    
    
    return a.money<b.money;
}
int find(int x)
{
    
    
    if(x==father[x])
        return x;
    return father[x]=find(father[x]);
}
int main()
{
    
    
    //freopen("in.txt","r",stdin);
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
    
    
        cin>>load[i].from>>load[i].to>>load[i].money;
    }
    sort(load,load+m,cmp);
    for(int i=0;i<n;i++)
        father[i]=i;
    int sum=0;
    for(int i=0;i<m;i++)
    {
    
    
        if(find(load[i].from)!=find(load[i].to))
        {
    
    
            sum+=load[i].money;
            father[find(load[i].to)]=find(load[i].from);
        }
    }
    for(int i=1;i<n;i++)
    {
    
    
        if(find(i)!=find(0))
        {
    
    
            cout<<"Impossible"<<endl;
            return 0;
        }
    }
    cout<<sum<<endl;
    return 0;
}

每天进步一点点,十天进步十点点,加油!
更多PTA代码请到我的博客里参考

ps:代码仅供参考,请勿抄袭

猜你喜欢

转载自blog.csdn.net/scorpion_legend/article/details/109447186