就是不断选择最小的 不断更新最短距离,本题要注重问题的转换
4
aaaaaaa
baaaaaa
abaaaaa
aabaaaa
0
#include <stdio.h> #define MAX 2005 int vis[MAX]; int distans[MAX]; char str[MAX][7]; int n; int sum,min; int dist(char *str1,char *str2) { int d,i; for(i=0,d=0;i<7;i++) { if(str1[i]!=str2[i]) d++; } return d; } int prim() { int i,v,j; sum=0; vis[0]=1; for(i=1;i<n;i++) distans[i]=dist(str[0],str[i]); for(j=1;j<n;j++) { min=9; for(i=0;i<n;i++) { if(!vis[i]&&distans[i]<min) { min=distans[i]; v=i; } } vis[v]=1; sum+=min; for(i=0;i<n;i++) { int k=dist(str[v],str[i]); if(distans[i]>k&&!vis[i]) { distans[i]=k; } } } return sum; } int main() { int i; while(scanf("%d",&n),n) { for(i=0;i<n;i++) { scanf("%s",&str[i]); vis[i]=0; } printf("The highest possible quality is 1/%d.\n",prim()); } return 0; }