POJ 1789 卡车的历史(Truck History) 最小树
地址 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; } }
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力