POJ1789 prim算法
题目分析
http://poj.org/problem?id=1789
两个卡车之间id字符不同的位置数量视为两卡车之间边的权重,任意两个点均直接相连,为稠密图
注意字符串的输入与输出,https://blog.csdn.net/sinat_37592533/article/details/79266182
数组最好定义在main函数外面
#include<stdio.h>
#include<vector>
#include<string.h>
using namespace std;
const int MAXN = 2200;
const int INF = 0x3f3f3f;
int mat[MAXN][MAXN];
bool vis[MAXN];
int lowc[MAXN];
int prim(int mat[][MAXN],int n){
int sum = 0;
memset(vis,false,sizeof(vis));
memset(lowc,INF,sizeof(lowc));
vis[0] = true;
for(int i = 0;i < n;i++){
lowc[i] = mat[0][i];
}
for(int i = 0;i < n-1;i++){
int p =-1;
int min = INF;
for(int j =0;j < n;j++){
if(!vis[j]&&min>lowc[j]){
min = lowc[j];
p = j;
}
}
if(p == -1) return -1;
sum+=min;
vis[p] = true;
for(int j = 0;j < n;j++){
if(lowc[j]>mat[p][j])
lowc[j] = mat[p][j];
}
}
return sum;
}
int main(){
int N;
while(true){
scanf("%d",&N);
if(N==0) break;
char str[N][7];
// printf("%d\n",N);
for(int i = 0;i < N;i++){
scanf("%s",str[i]);
}
// for(int i = 0;i < N;i++){
// for(int j = 0;j < 7;j++)
// printf("%c",str[i][j]);
// printf("\n");
// }
for(int i = 0;i < N;i++)
for(int j = 0;j < N;j++){
int cos = 0;
for(int k = 0;k < 7;k++){
if(str[i][k]!=str[j][k])cos++;
}
mat[i][j] = cos;
}
printf("The highest possible quality is 1/%d.\n",prim(mat,N));
}
return 0;
}