POJ 1258 -Agri-Net- 最小生成树

裸生成树

#/*--------------------------------------------------------------------------------------*/
//        Helica's header
//        Second Edition
//        2015.11.7
//
#include <algorithm>
#include <iostream>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>

//debug function for a N*M array
#define debug_map(N,M,G) printf("
");for(int i=0;i<(N);i++)
{for(int j=0;j<(M);j++){
printf("%d",G[i][j]);}printf("
");}
//debug function for int,float,double,etc.
#define debug_var(X) cout<<#X"="<<X<<endl;
/*--------------------------------------------------------------------------------------*/
using namespace std;

const int maxn = 100+10;
const int INF = 0x3f3f3f3f;
int N,cost[maxn][maxn],lowc[maxn];
bool vis[maxn];

int Prim()
{
    int ans = 0;
    memset(vis,false,sizeof vis);
    vis[0] = true;
    for(int i=1;i<N;i++) lowc[i] = cost[0][i];
    for(int i=1;i<N;i++)
    {
        int minc = INF,p=-1;
        for(int j=0;j<N;j++) if(!vis[j] && minc > lowc[j])
        {
                minc = lowc[j];
                p = j;
        }
        if(minc == INF) return -1;
        ans += minc;
        vis[p] = true;
        for(int j=0;j<N;j++) if(!vis[j] && lowc[j]>cost[p][j])
            lowc[j] = cost[p][j];
    }
    return ans;
}

int main()
{
    //freopen("input.in","r",stdin);
    while(~scanf("%d",&N))
    {
        for(int i=0;i<N;i++)
        {
            for(int j=0;j<N;j++)
            {
                scanf("%d",&cost[i][j]);
            }
        }
        printf("%d
",Prim());
    }
}
原文地址:https://www.cnblogs.com/helica/p/5265871.html