其他分享
首页 > 其他分享> > prim

prim

作者:互联网

朴素prim

#include<bits/stdc++.h>
using namespace std;
const int N = 550, INF = 0x3f3f3f3f;
int n, m, dis[N], g[N][N];
bool vis[N];

int prim()
{
    memset(dis, 0x3f, sizeof dis);
    int res = 0;

    for(int i = 0; i < n; i ++ )
    {
        int t = -1;
        for(int j = 1; j <= n; j ++ )
            if(!vis[j] && (t == -1 || dis[j] < dis[t])) t = j;

        if(i && dis[t] == INF) return INF;

        if(i) res += dis[t];
        vis[t] = true;

        for(int j = 1; j <= n; j ++ )
            dis[j] = min(dis[j], g[j][t]);
    }
    return res;
}
int main()
{
    cin >> n >> m;
    memset(g, 0x3f, sizeof g);
    while(m -- )
    {
        int f, t, l;
        cin >> f >> t >> l;
        g[f][t] = g[t][f] = min(g[t][f], l);
    }

    int t = prim();

    if(t == INF) puts("impossible");
    else cout << t << endl;

    return 0;
}

 

标签:0x3f,prim,int,memset,sizeof,dis
来源: https://www.cnblogs.com/leyuo/p/16646504.html