POJ 1789 Prim

给定N个字符串,某个字符串转为另一个字符串的花费为他们每一位不相同的字符数。 求最小花费Q。

Input

多组输入,以0结束。 保证N不超过2000。

Output

每组输出"The highest possible quality is 1/Q."。

Sample Input

4
aaaaaaa
baaaaaa
abaaaaa
aabaaaa
0

Sample Output

The highest possible quality is 1/3.

由于是完全图,所以用prim

1.strlen或者str.length最好用int强制转化一下,要追求0warning
2.distance函数是里面的,不要再include它了
3.判断相等要敲两个等号.
4.'int' is not a class, struct, or union type如果出了这种bug基本就是命名空间混淆了.


#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <bitset>
#include <stack>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define ll long long
#define mm0(a) memset(a,0,sizeof(a))
#define mm(a,b) memset(a,b,sizeof(a))
#define each(a,b,c) for(int a=b;a<=c;a++)
#define de(x) cout << #x << " " << (x) <<endl
//#define de(x) cout <<""
#define rush() int T;scanf("%d",&T);each(kase,1,T)
#define scan(a,b) scanf("%d%d",&a,&b)
#define fin(a) scanf("%d",&a)
#include <iostream>

using namespace std;

//const int maxn = 400+5;
const int maxn = 2e3+5;
const int INF = 0x3f3f3f3f;
inline int read(){int s=0;char ch=getchar();for(; ch<'0'||ch>'9'; ch=getchar());for(; ch>='0'&&ch<='9'; ch=getchar())s=s*10+ch-'0';return s;}


bool vis[maxn];
int lowc[maxn];
int Prim(int cost[][maxn],int n)
{
    int ans=0;
    memset(vis,false,sizeof(vis));
    vis[0]=true;//从0开始的
    for(int i=1;i<n;i++)lowc[i]=cost[0][i];
    for(int i=1;i<n;i++)
    {
        int minc=INF;
        int p=-1;
        for(int j=0;j<n;j++)
        {
            if(!vis[j]&&minc>lowc[j])
            {
                minc=lowc[j];
                p=j;
            }
        }
        //de(minc);
            if(minc==-1)return -1;//又把==敲成一个等号了
            ans+=minc;
            vis[p]=true;
            for(int j=0;j<n;j++)
            {
                if(!vis[j]&&lowc[j]>cost[p][j])
                    lowc[j]=cost[p][j];
            }

    }
    return ans;
}
char str[maxn][8];
int cost[maxn][maxn];
int dist(int i,int j)
{
    int ans=0;
    for(int k=0;k<7;k++)///这里
    {
        if(str[i][k]!=str[j][k])
            ans++;
    }
    return ans;
}
/*
4
aaaaaaa
baaaaaa
abaaaaa
aabaaaa
0
*/
int main()
{
    int m;
    while(scanf("%d",&m)!=EOF&&m!=0)
    {
        //getchar();//吃掉回车
        for(int i=0;i<m;i++)
            cin>>str[i];
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(i==j)
                {
                    cost[i][j]=0;
                }
                else
                    cost[i][j]=dist(i,j);
                    //de(cost[i][j]);
            }
        }

        int ans=Prim(cost,m);
        //de(ans);
        printf("The highest possible quality is 1/%d.
",ans);

    }
}
原文地址:https://www.cnblogs.com/Tony100K/p/11658742.html