地址 http://poj.org/problem?id=1789
解析
aaaaaaa
baaaaaa
abaaaaa
aabaaaa
aaaaaaa 和 baaaaaa 差别度为1
abaaaaa 和 baaaaaa 差别度为2
其余同理
那么以字符串为点差别度作为连点的边权
就有下图(作画工具限制,双箭头看做无向图的一条线即可)
根据此无向图生成最小树,得到的最小权值和就是答案
#include <iostream> #include <vector> #include <memory.h> #include <string> #include <algorithm> using namespace std; /* 样例输入: 样例输出: 4 aaaaaaa baaaaaa abaaaaa aabaaaa 7 baaaaaa abaaaaa aabaaaa aaabaaa aaaabaa aaaaaba aaaaaab 10 bbaaaaa abbaaaa aaabbaa baaaaaa abaaaaa aabaaaa aaabaaa aaaabaa aaaaaba aaaaaab 10 bbbaaaa abbbaaa aaabbba baaaaab abaaaab aabaaab aaabaab aaaabab aaaaabb aaaaaab 0 The highest possible quality is 1/3. */ int n; const int N = 2010; vector<string> vs; int g[N][N]; const int INF = 0x3f3f3f3f; int dist[N]; int st[N]; int prim() { memset(dist, 0x3f, sizeof dist); int res = 0; for (int i = 0; i < n; i++) { int t = -1; for (int j = 1; j <= n; j++) if (!st[j] && (t == -1 || dist[t] > dist[j])) t = j; if (i && dist[t] == INF) return INF; if (i) res += dist[t]; st[t] = true; for (int j = 1; j <= n; j++) dist[j] = min(dist[j], g[t][j]); } return res; } int main() { while (1) { cin >> n; if (n == 0) break; memset(g, 0x3f, sizeof(g)); memset(st, 0, sizeof st); vs.clear(); vs.push_back("no_use,place_holder"); for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 1; j < vs.size(); j++) { int difCount = 0; for (int idx = 0; idx < 7; idx++) { if (s[idx] != vs[j][idx]) difCount++; } g[j][vs.size()] = g[vs.size()][j] = difCount; } vs.push_back(s); } /* for (int i = 1; i < vs.size(); i++) { for (int j = i + 1; j < vs.size(); j++) { int difCount = 0; for (int idx = 0; idx < 7; idx++) { if (vs[i][idx] != vs[j][idx]) difCount++; } g[j][i] = g[i][j] = difCount; } }*/ int ret = prim(); cout << "The highest possible quality is 1/" << ret <<"."<< endl; } }