Prim算法模版

例题:POJ1798-Truck History

题目链接:点击做题

AC代码:

#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long LL;
const double INF = 0x3f3f3f3f;
const int N = 2005;
int n, ans;
char s[N][N];
int dis[N],ar[N][N];
int vis[N];
void Prim() {
    ans=0;
    memset(vis,0,sizeof(vis));
    for (int i = 1; i <= n;++i) {
        dis[i] = ar[1][i];
    }
    vis[1]=1;
    for (int i = 1; i < n; ++i) {
        int L = INF,m=-1;
        for (int j = 1; j <= n; ++j) {
            if (dis[j] && dis[j] < L&&vis[j]==0) {
                L = dis[j];
                m = j;
            }
        }
        if (L != INF) {
            ans += L;
        }
        vis[m]=1;
        for (int j = 1; j <= n; ++j) {
            if (ar[m][j] < dis[j]&&vis[j]==0) {
                dis[j] = ar[m][j];
            }
        }
    }
    printf("The highest possible quality is 1/%d.\n", ans);
}
int getval(int x,int y){
    int an=0;
    for(int i=0;i<=6;++i){
        if(s[x][i]!=s[y][i])an++;
    }
    return an;
}
int main() {
    while (~scanf("%d", &n)&&n) {
        for(int i=1;i<=n;++i){
            scanf("%s",s[i]);
        }
        for(int i=1;i<=n;++i){
            for(int j=1;j<=n;++j){
                if(i==j)ar[i][j]=0;
                else ar[i][j]=getval(i,j);
            }
        }
        Prim();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39599067/article/details/80092440