SDUT 4178 最小生成树(Kruskal)

Problem Description

在一个无向图中,求最小生成树。

Input

多组测试数据,对于每组测试数据,第1行输入正整数n(1 <= n <= 1000)、m,表示n个顶点(编号从1开始)和m条边。之后m行每行输入u(1 <= u <= n)、v(1 <= v <= n)、w(1 <= w <= 100),表示在顶点u和顶点v之间存在无向边,且权值为w。

Output

对于每组测试数据,若存在最小生成树则输出最小生成树的权值和,若不存在最小生成树则输出-1。

Sample Input
3 7
1 2 19
2 3 11
3 1 7
1 3 5
2 3 89
3 1 91
1 2 32
Sample Output
16
#include<iostream>
#include<stdlib.h>
#include<string.h>

using namespace std;

typedef struct node
{
    int u, v, w;
}Sj;

Sj f[1000000];

int q[10001];

int cmp(const void *a, const void *b)
{
    Sj *aa = (Sj*)a;
    Sj *bb = (Sj*)b;
    return aa->w > bb->w ? 1:-1;
}

int cz(int i)
{
    int c = i;
    for(; q[c] >= 0; c = q[c]);
    while(c != i)
    {
        int t = q[i];
        q[i] = c;
        i = t;
    }
    return c;
}

void jh(int a, int b)
{
    int f1 = cz(a);
    int f2 = cz(b);
    int t = q[f1] + q[f2];
    if(q[f1] > q[f2])
    {
        q[f1] = f2;
        q[f2] = t;
    }
    else
    {
        q[f2] = f1;
        q[f1] = t;
    }
}

int main()
{
    int n, m;
    while(cin>>n>>m)
    {
        for(int i = 0; i < m; i++)
            cin>>f[i].u>>f[i].v>>f[i].w;

        qsort(f, m, sizeof(f[0]), cmp);
        memset(q, -1, sizeof(q));

        int ans = 0;
        int c = 0;
        for(int i = 0; i < m; i++)
        {
            int u = f[i].u;
            int v = f[i].v;
            if(cz(u) != cz(v))
            {
                c++;
                ans += f[i].w;
                jh(u, v);
            }
        }
        if(c == n-1)
            cout<<ans<<endl;
        else
            cout<<"-1"<<endl;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值