poj 1258(prim模板题)

代码留存:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<set>
#include<cmath>
#include<queue>
using namespace std;
typedef long long LL;
typedef pair<int,int> P;
const int maxn = 100 + 5;
const int INF = 1000000000;

int M[maxn][maxn];
int n;


priority_queue<P,vector<P>,greater<P> > Q;
int vis[maxn];

int prim(){
    int ret = 0;
    memset(vis,0,sizeof(vis));
    while(!Q.empty()) Q.pop();
    Q.push(P(0,0));
    while(!Q.empty()){
        P p = Q.top();Q.pop();
        if(vis[p.second] == 1) continue;
        vis[p.second] = 1;
        ret += p.first;
        for(int i = 0;i < n;i++){
            if(vis[i] == 0){
                Q.push(P(M[p.second][i],i));
            }
        }
    }
    return ret;
}

/*int mincost[maxn];
bool used[maxn];
int prim(){
    for(int i = 0;i < n;i++){
        mincost[i] = INF;
        used[i] = false;
    }
    mincost[0] = 0;
    int res = 0;
    while(1){
        int v = -1;
        for(int u = 0;u < n;u++){
            if(!used[u] && (v==-1 || mincost[u] < mincost[v])) v = u;
        }
        if(v == -1) break;
        used[v] = true;
        res += mincost[v];
        for(int u = 0;u < n;u++){
            mincost[u] = min(mincost[u],M[v][u]);
        }
    }
    return res;
}*/

int main(){
    while(scanf("%d",&n) != EOF){
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n;j++){
                scanf("%d",&M[i][j]);
            }
        }
        printf("%d\n",prim());
    }
    return 0;
}


你可能感兴趣的:(poj 1258(prim模板题))