题目意思:
给出n给长度为7的由小写字母组成的字符串,每两个字符串之间的距离是这两个字符串不同的字母的个数。
每个字符串看成是一个点,n 个点两两相连,求这个图的最小生成树的所有边的总和
本题要点:
1、 n == 2000, 用邻接矩阵来存图,用 prim 算法计算最小生成树。 裸题。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MaxN = 2010;
int a[MaxN][MaxN], d[MaxN], n;
long long ans;
bool vis[MaxN];
char str[MaxN][8];int calc_dist(char a[], char b[], int len)
{
int dist = 0;for(int i = 0; i < len; ++i){
if(a[i] != b[i]){
++dist;}}return dist;
}void prim()
{
memset(d, 0x3f, sizeof d);memset(vis, false, sizeof vis);d[1] = 0;for(int i = 1; i < n; ++i){
int x = 0;for(int j = 1; j <= n; ++j){
if(!vis[j] && (0 == x || d[j] < d[x])){
x = j;}}vis[x] = true;for(int y = 1; y <= n; ++y){
if(!vis[y]) {
d[y] = min(d[y], a[x][y]);}}}ans = 0;for(int i = 1; i <= n; ++i){
ans += d[i];}
}int main()
{
while(scanf("%d", &n) && n){
for(int i = 1; i <= n; ++i){
scanf("%s", str[i]);}for(int i = 1; i <= n; ++i){
for(int j = i + 1; j <= n; ++j){
a[i][j] = a[j][i] = calc_dist(str[i], str[j], 7); }}prim();printf("The highest possible quality is 1/%lld.\n", ans);}return 0;
}/* 4 aaaaaaa baaaaaa abaaaaa aabaaaa 0 *//* The highest possible quality is 1/3. */