POJ 1789 Truck History(Prim+邻接矩阵)

( ̄▽ ̄)"

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;

const int MAXN=2010;
const int INF=10e8;
int n,k,minn;
char str[MAXN][10];
int c[MAXN][MAXN],lc[MAXN];
bool vis[MAXN];

int get_distance(char s1[],char s2[])
{
    int dis=0;
    for(int i=0;i<7;i++)
        if(s1[i]!=s2[i])
            dis++;
    return dis;
}

int Prim()
{
    int ans=0;
    memset(vis,0,sizeof(vis));
    vis[1]=1;

    for(int i=1;i<=n;i++)
        lc[i]=c[1][i];
    for(int i=1;i<=n-1;i++)
    {
        k=-1,minn=INF;
        for(int j=1;j<=n;j++)
            if(!vis[j]&&minn>lc[j])
            {
                minn=lc[j];k=j;
            }
        if(k==-1) break;
        ans+=minn;vis[k]=1;
        for(int j=1;j<=n;j++)
            if(!vis[j]&&lc[j]>c[k][j])
                lc[j]=c[k][j];
    }
    return ans;
}

int main()
{
    while(scanf("%d",&n)&&n)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%s",str[i]);
            c[i][i]=0;
        }
        for(int i=1;i<=n;i++)
            for(int j=i+1;j<=n;j++)
                c[i][j]=c[j][i]=get_distance(str[i],str[j]);
        printf("The highest possible quality is 1/%d.\n",Prim());
    }
    return 0;
}

你可能感兴趣的:(POJ 1789 Truck History(Prim+邻接矩阵))