- Time: 2016-04-14-20:36:55 Thursday
- Title number: [2016-04-14][poj][1258][agri-net]
- The main idea: to find the minimum spanning tree
- Analysis: Direct PRIM algorithm
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100 + 10 ;
int g[maxn][maxn],vis[maxn],lowc[maxn];
int prim(int n){
int ans = 0;
memset(vis,0,sizeof(vis));
Vis [ 0 ] = 1 ;
for ( int i = 1 ; I < n ++ i ) LOWC [ i ] = g [ 0 ][ i ;
for(int i = 1 ; i < n ;++i){
int minc = 0x3f3f3f3f;
int p = -1;
for(int j = 0 ; j < n ; ++j){
if(!vis[j] && minc > lowc[j]){
minc = lowc[j];
p = j;
}
}
if(minc == 0x3f3f3f3f) return -1;
ans += minc;
vis[p] = 1;
for(int j = 0 ; j < n ; ++j){
if (! vis [ j ] && LOWC [ j ] > g [ p ][ j ]) {
lowc[j] = g[p][j];
}
}
}
return ans;
}
int main(){
int n,a;
while(~scanf("%d",&n)){
memset(g,0x3f,sizeof(g));
for(int i = 0 ; i < n ; ++i){
for(int j = 0 ; j < n ; ++j){
scanf("%d",&a);
g[i][j] = min(g[i][j],a);
}
}
printf("%d\n",prim(n));
}
return 0;
}
From for notes (Wiz)
[2016-04-14] [POJ] [1258] [Agri-net]