Prim算法求最小生成树

给定一个 nn 个点 mm 条边的无向图,图中可能存在重边和自环,边权可能为负数。

求最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible

给定一张边带权的无向图 G=(V,E)G=(V,E),其中 VV 表示图中点的集合,EE 表示图中边的集合,n=|V|n=|V|,m=|E|m=|E|。

由 VV 中的全部 nn 个顶点和 EE 中 n−1n−1 条边构成的无向连通子图被称为 GG 的一棵生成树,其中边的权值之和最小的生成树被称为无向图 GG 的最小生成树。

输入格式

第一行包含两个整数 nn 和 mm。

接下来 mm 行,每行包含三个整数 u,v,wu,v,w,表示点 uu 和点 vv 之间存在一条权值为 ww 的边。

输出格式

共一行,若存在最小生成树,则输出一个整数,表示最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible

数据范围

1≤n≤5001≤n≤500,

1≤m≤1051≤m≤105,

图中涉及边的边权的绝对值均不超过 1000010000。

输入样例:
复制代码
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
输出样例:
复制代码
6
cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 510,M=100010,INF=0x3f3f3f3f;
int n,m;
int g[N][N],dist[N];
bool st[N];
int prim()
{
    memset(dist,0x3f,sizeof (dist));
    dist[1]=0;
    int res=0;
    for(int i=0;i<n;i++)
    {
        int t=-1;
        for(int j=1;j<=n;j++)
        if(!st[j]&&(t==-1||dist[t]>dist[j]))
          t=j;
        if(dist[t]==INF) return INF; 
        st[t]=true;
        res += dist[t];
        for(int j=1;j<=n;j++)
        dist[j]=min(dist[j],g[t][j]);
    }
    return res;
}
int main()
{
    scanf("%d%d",&n,&m);
    memset(g,0x3f,sizeof (g));
    while(m--)
    {
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        g[a][b]=g[b][a]=min(g[a][b],c);
    }
    int res=prim();
    if(res==INF) puts("impossible");
    else printf("%d\n",res);
    return 0;
}
相关推荐
wadesir2 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi9878382 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill2 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit3 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung3 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
wifi chicken3 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
胡楚昊3 小时前
NSSCTF动调题包通关
开发语言·javascript·算法
Gold_Dino4 小时前
agc011_e 题解
算法
bubiyoushang8884 小时前
基于蚁群算法的直流电机PID参数整定 MATLAB 实现
数据结构·算法·matlab
风筝在晴天搁浅4 小时前
hot100 240.搜索二维矩阵Ⅱ
算法·矩阵