思路:最小生成树+prime
代码:
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; #define MAXN 2010 #define INF 0xFFFFFFF int n; char ch[MAXN][10]; int vis[MAXN]; int lowcost[MAXN]; int G[MAXN][MAXN]; void init(){ memset(vis , 0 , sizeof(vis)); memset(lowcost , 0 , sizeof(lowcost)); for(int i = 1 ; i <= n ; i++){ for(int j = i+1 ; j <= n ; j++){ int tmp = 0; for(int k = 0 ; k < 7 ; k++){ if(ch[i][k] != ch[j][k]) tmp++; } G[i][j] = G[j][i] = tmp; } } } void prime(){ int ans , pos; ans = 0; vis[1] = 1; for(int i = 1 ; i <= n ; i++) lowcost[i] = G[1][i]; for(int i = 1 ; i <= n ; i++){ pos = -1; for(int j = 1 ; j <= n ; j++){ if(!vis[j] && (pos == -1 || lowcost[j] < lowcost[pos])) pos = j; } if(pos == -1) break; vis[pos] = 1; ans += lowcost[pos]; for(int j = 1 ; j <= n ; j++){ if(!vis[j] && lowcost[j] > G[j][pos]) lowcost[j] = G[j][pos]; } } printf("The highest possible quality is 1/%d.\n" , ans); } int main(){ while(scanf("%d%*c" , &n) && n){ for(int i = 1 ; i <= n ; i++) scanf("%s%*c" , ch[i]); init(); prime(); } return 0; }