POJ 1789
做题的感受,稠密图的MST问题还是推荐使用Prim算法,尤其是这种完全图,直接设置dist函数计算距离而非实现构建好一个数组计算时间上没什么差别(此题)空间上优化
#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= 2005;
const int l_code= 8;
const int INF= 0x3f3f3f3f;
char codes[maxn][l_code];
int vis[maxn], dis[maxn];
int Dist(const int i, const int j)
{
if (i== j){
return 0;
}
int ret= 0;
for (int k= 0; k< l_code; ++k){
if (codes[i][k]!= codes[j][k]){
++ret;
}
}
return ret;
}
int Prim(const int n)
{
memset(vis, 0, sizeof(vis));
dis[0]= 0;
vis[0]= 0;
for (int i= 1; i< n; ++i){
dis[i]= Dist(0, i);
}
int ans= 0;
int minc, p;
int t;
for (int i= 1; i< n; ++i){
minc= INF;
p= -1;
for (int j= 1; j< n; ++j){
if (!vis[j] && dis[j]< minc){
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]> (t= Dist(p, j))){
dis[j]= t;
}
}
}
return ans;
}
int main()
{
int n;
while (~scanf("%d", &n) && n){
for (int i= 0; i< n; ++i){
scanf(" %s" ,codes[i]);
}
printf("The highest possible quality is 1/%d.\n", Prim(n));
}
return 0;
}