不得不说,题目太难看懂了。 就是每个卡车都一个编码,每两个卡车的距离是编码不同的位数。 求的是最小生成树。 用prime算法。 AC代码: #include <iostream> #include <stdio.h> #include <string.h> using namespace std; char s[2001][8]; int a[2001][2001]; bool b[2001]; int value[2001]; int length(char *a, char *b) { int sum = 0; for (int i = 0; i < 7; ++i) if (a[i] != b[i]) ++sum; return sum; } int main() { int n; while (scanf("%d", &n) && n) { int i, j; for (i = 0; i < n; ++i) scanf("%s", s + i); for (i = 0; i < n-1; ++i) for (j = i + 1; j < n; ++j) { a[i][j] = length(s[i],s[j]); a[j][i] = a[i][j]; } memset(b,false,sizeof(b)); b[0] = true; for (i = 1; i < n; ++i) value[i] = a[0][i]; int sum = 0; for (i = 1; i < n; ++i) { int min = 0xffffff; int temp; for (j = 1; j < n; ++j) if (min > value[j] && !b[j]) /*在树的顶点中选一条最小边*/ { min = value[j]; temp = j; } sum += min; b[temp] = true; for (j = 1; j < n; ++j) { if (!b[j] && value[j] > a[temp][j]) value[j] = a[temp][j]; } } printf("The highest possible quality is 1/%d./n", sum); } return 0; }