PTA 5-10 公路村村通 (30)

题目:http://pta.patest.cn/pta/test/18/exam/4/question/630

PTA - 数据结构与算法题目集(中文) - 5-10

现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。

输入格式:

输入数据包括城镇数目正整数N(≤1000)和候选道路数目M(≤3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。

输出格式:

输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出−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

输出样例:

12

直接上代码了 =.=
#include <fstream>
#include <iostream>
#include <cstring>    //memset(tree,-1,sizeof(tree))
#include <algorithm>
using namespace std;
const int maxn=1005;
const int maxl=3005;

struct Edge
{
    int a, b;
    int cost;
    bool operator <(const Edge &way)const
    {
        return cost<way.cost;
    }
};
Edge lu[maxl];
int tree[maxn]; //并查集
int n,m;

int findRoot(int x)
{
    if(tree[x]==-1) //根
        return x;
    else
    {
        int root=findRoot(tree[x]);
        tree[x]=root;   //可缩短树的高度
        return root;
    }
}

int main()
{
    //ifstream fin("test.txt");
    cin >> n >> m;
    if(n==0)
    {
        cout << "-1";
        return 0;
    }
    for(int i=1; i<=m; i++) //存每条路的信息,并按cost从小到大排序
    {
        cin >> lu[i].a >> lu[i].b >> lu[i].cost;
    }
    sort(lu+1, lu+1+m);
    memset(tree,-1,sizeof(tree));   //初始的点都是孤立的(每个点都作为根)
    
    int allcost=0;
    for(int i=1; i<=m; i++)
    {
        int roota=findRoot(lu[i].a);
        int rootb=findRoot(lu[i].b);
        if(roota!=rootb)
        {
            tree[rootb]=roota;
            allcost+=lu[i].cost;
        }
    }
    int cnt=0;    //tree[m]中-1的个数,即根的个数
    for(int i=1; i<=n; i++)
    {
        if(tree[i]==-1)
            cnt++;
    }
    if(cnt!=1)
        cout << "-1";
    else
        cout << allcost;

    return 0;
}

原文地址:https://www.cnblogs.com/claremore/p/4993724.html