先算出节点之间的直接距离,然后再用Prim就能算出来了
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define LLEN 2005
#define MMAX 0x3fffffff
int map[LLEN][LLEN];
char node[LLEN][10];
int t;
int dis(int i, int j) {
int num = 0;
for(int k = 0; k < 7; k++) {
if(node[i][k] != node[j][k]) num++;
}
return num;
}
void prim() {
int lowcost[LLEN];
int nearvex[LLEN];
int sum = 0;
memset(lowcost, 0, sizeof(lowcost));
memset(nearvex, 0, sizeof(nearvex));
lowcost[0] = -1;
for(int i = 0; i < t; i++) {
lowcost[i] = map[0][i];
}
for(int i = 1; i < t; i++) {
int min = MMAX;
int imin;
for(int j = 0; j < t; j++) {
if(lowcost[j] != -1 && lowcost[j] < min) {
imin = j;
min = lowcost[j];
}
}
lowcost[imin] = -1;
sum += min;
for(int j = 0; j < t; j++) {
if(lowcost[j] > map[imin][j]) {
lowcost[j] = map[imin][j];
}
}
}
printf("The highest possible quality is 1/%d.\n", sum);
}
int main() {
while(scanf("%d", &t), t != 0) {
for(int i = 0; i < t; i++) {
scanf("%s", node[i]);
for(int j = 0; j <= i; j++) {
if(i == j) {
map[i][j] = map[j][i] = -1;
}
else {
map[i][j] = map[j][i] = dis(i, j);
}
}
}
prim();
}
return 0;
}