POJ 1258
稠密图,如此前博客所总结的,稠密图使用Prim
#include <iostream>
#include <algorithm>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <stack>
#include <map>
#include <set>
using namespace std;
const int maxn= 105;
const int INF= 0x3f3f3f3f;
int vis[maxn], dis[maxn];
int fm[maxn][maxn];
int Prim(const int n)
{
for (int i= 1; i< n; ++i){
dis[i]= fm[0][i];
vis[i]= 0;
}
dis[0]= 0;
vis[0]= 1;
int ans= 0;
int p, minc;
for (int i= 1; i< n; ++i){
minc= INF;
p= -1;
for (int j= 1; j< n; ++j){
if (!vis[j] && minc > dis[j]){
minc= dis[j];
p= j;
}
}
if (-1== p){
return -1;
}
ans+= minc;
vis[p]= 1;
for (int j= 1; j< n; ++j){
if (!vis[j] && dis[j] > fm[p][j]){
dis[j]= fm[p][j];
}
}
}
return ans;
}
int main(int argc, char const *argv[])
{
int n;
while (~scanf("%d", &n)){
for (int i= 0; i< n; ++i){
for (int j= 0; j< n; ++j){
scanf("%d", fm[i]+j);
}
}
printf("%d\n", Prim(n));
}
return 0;
}