Prim

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
using namespace std;
int map[1000][1000],dis[10000],book[10000];
int main()
{
    int cnt=1,sum=0;
    int n,m;
    cin>>n>>m;
    int i,j,k;
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
        {
            if(i==j)
                map[i][j]=0;
            else map[i][j]=99999999;
        }
    while(m--)
    {
        int x,y,z;
        cin>>x>>y>>z;
        map[x][y]=z;
        map[y][x]=z;
    }
    for(i=1;i<=n;i++)
    {
        dis[i]=map[1][i];
    }
    book[1]=1;
    while(cnt<n)
    {
        int u;
        int minn=99999999;
        for(j=1;j<=n;j++)
        {
            if(dis[j]<minn&&book[j]==0)
            {
                minn=dis[j];
                u=j;
            }
        }
        book[u]=1;
        cnt++;
        sum+=dis[u];
        for(j=2;j<=n;j++)
        {
            if(dis[j]>map[u][j])
                dis[j]=map[u][j];
        }
    }
    cout<<sum;
    //system("pause");
    return 0;
}
/*
6 9
2 4 11
3 5 13
4 6 3
5 6 4
2 3 6
4 5 7
1 2 1
3 4 9
1 3 2
*/
蒟蒻总是更懂你✿✿ヽ(°▽°)ノ✿
原文地址:https://www.cnblogs.com/WWHHTT/p/7570174.html