POJ 1789 Truck History【最小生成树模板题Kruscal】
题目链接:http://poj.org/problem?id=1789
大意:
不同字符串相同位置上不同字符的数目和是它们之间的差距。求衍生出全部字符串的最小差距。
1 #include<stdio.h> 2 #include<math.h> 3 #include<algorithm> 4 using namespace std; 5 const int MAXN = 2100; 6 7 int cnt; 8 int pre[MAXN]; 9 char s[MAXN][10]; 10 11 struct Edge 12 { 13 int from, to; 14 int val; 15 }edge[MAXN * (MAXN - 1) / 2]; 16 17 bool cmp(Edge a, Edge b) 18 { 19 return a.val < b.val; 20 } 21 22 int find(int x) 23 { 24 if(pre[x] == x) 25 return x; 26 else 27 { 28 int root = find(pre[x]); 29 pre[x] = root; 30 return pre[x]; 31 } 32 } 33 34 int main() 35 { 36 int n; 37 while(scanf("%d", &n) != EOF) 38 { 39 if(n == 0) 40 break; 41 getchar(); 42 cnt = 0; 43 for(int i = 1; i <= n; i ++) 44 pre[i] = i; 45 for(int i = 1; i <= n; i ++) 46 scanf("%s", s[i] + 1); 47 for(int i = 1; i < n; i ++) 48 { 49 for(int j = i + 1; j <= n; j ++) 50 { 51 int sum = 0; 52 for(int k = 1; k <= 7; k ++) 53 if(s[i][k] != s[j][k]) 54 sum ++; 55 edge[++ cnt].from = i; 56 edge[cnt].to = j; 57 edge[cnt].val = sum; 58 } 59 } 60 sort(edge + 1, edge + 1 + cnt, cmp); 61 int ans = 0; 62 for(int i = 1; i <= cnt; i ++) 63 { 64 int xx = find(edge[i].from), yy = find(edge[i].to); 65 if(xx != yy) 66 { 67 pre[yy] = xx; 68 ans += edge[i].val; 69 } 70 } 71 printf("The highest possible quality is 1/%d.\n", ans); 72 } 73 return 0; 74 }