ZOJ 2158 POJ 1789 Truck History

最小生成树,主要是题目比较难懂。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const int Maxn=2000+10;
const int maxn=2000*2000+10;
int Father[Maxn];
struct Edge
{
    int from,to,w;
}edge[maxn];
int n,tot;
char s[maxn][10];

int Find(int x)
{
    if(x!=Father[x]) Father[x]=Find(Father[x]);
    return Father[x];
}

void init()
{
    for(int i=0;i<=n;i++) Father[i]=i;
    tot=0;
}

bool cmp(const Edge&a,const Edge&b)
{
    return a.w<b.w;
}

int main()
{
    freopen("in.txt","r",stdin);
    while(~scanf("%d",&n)){
        if(!n) break;
    init();
    for(int i=0;i<n;i++)
        scanf("%s",s[i]);

    for(int i=0;i<n;i++)
        for(int j=i+1;j<n;j++)
        {
            edge[tot].from=i;
            edge[tot].to=j;
            edge[tot].w=0;
            for(int k=0;k<7;k++)
                if(s[i][k]!=s[j][k])
                    edge[tot].w++;
            tot++;
        }

    sort(edge,edge+tot,cmp);

    int W=0;
    for(int i=0;i<tot;i++)
    {
        int Fu=Find(edge[i].from);
        int Fv=Find(edge[i].to);
        if(Fu!=Fv)
        {
            Father[Fu]=Fv;
            W=W+edge[i].w;
        }
    }
    printf("The highest possible quality is 1/%d.\n",W);}
    return 0;
}

 

posted @ 2015-08-13 10:04  Fighting_Heart  阅读(133)  评论(0编辑  收藏  举报