題目鏈接:https://vjudge.net/problem/POJ-1789
思路:
題目意思就是說,給定一些長度為7的字串,可以把字串抽象為一個點,
每個點之間的距離就是他們本身字串與其他字串字符不同的個數,
之后就是一個最小生成樹的板子,
1 #include <stdio.h> 2 #include <iostream> 3 #include <queue> 4 using namespace std; 5 6 const int N = (int)2e3+10; 7 const int inf = (int)1e9; 8 char str[N][10]; 9 int g[N][N]; 10 int dis[N]; 11 bool vis[N]; 12 int T; 13 14 struct node{ 15 int loc; 16 int w; 17 18 bool friend operator<(const node& a,const node& b){ 19 return a.w > b.w; 20 } 21 }; 22 23 priority_queue<node > que; 24 25 int prime(){ 26 27 for(int i = 1; i <= T; i++){ 28 vis[i] = 0; 29 dis[i] = inf; 30 } 31 32 while(!que.empty()) que.pop(); 33 34 que.push(node{1,0}); 35 dis[1] = 0; 36 37 while(!que.empty()){ 38 int u = que.top().loc; 39 que.pop(); 40 vis[u] = 1; 41 42 for(int v = 1; v <= T; v++){ 43 if(!vis[v] && dis[v] > g[u][v]){ 44 dis[v] = g[u][v]; 45 que.push(node{v,dis[v]}); 46 } 47 } 48 } 49 50 int ans = 0; 51 for(int i = 1; i <= T; i++) 52 ans += dis[i]; 53 54 return ans; 55 } 56 57 int main(){ 58 59 while(scanf("%d",&T)){ 60 61 if(!T) break; 62 63 for(int i = 1; i <= T; i++) 64 scanf("%s",&str[i]); 65 66 67 int cnt = 0; 68 for(int i = 1; i <= T; i++){ 69 for(int j = i + 1; j <= T; j++){ 70 cnt = 0; 71 72 //每個點與其他點的距離 73 for(int o = 0 ; o < 7; o++) 74 if(str[i][o] != str[j][o]) 75 ++cnt; 76 77 g[i][j] = g[j][i] = cnt; 78 } 79 } 80 81 for(int i = 1; i <= T; i++) 82 g[i][i] = 0; 83 /* 84 for(int i = 1; i <= T; i++){ 85 for(int j = 1; j <= T; j++) 86 printf("%d ",g[i][j]); 87 printf("\n"); 88 } 89 */ 90 printf("The highest possible quality is 1/%d.\n",prime()); 91 } 92 93 return 0; 94 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/128432.html
標籤:其他
