POJ1789 Truck History

最小生成树(kruskal)

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 2e3 + 5;
char s[maxn][8];
int prt[maxn], n, cnt;
struct node
{
    int u, v, w;
    bool operator < (const node &b) const{
        return w < b.w;
    }
} a[maxn*maxn];
int weight(int x,int y)
{
    int res = 0;
    for(int i = 0; i < 7; i++){
        if(s[x][i] != s[y][i]) res++;
    }
    return res;
}
int getpa(int x){return prt[x] == x ? x : prt[x] = getpa(prt[x]);}
int kruskal()
{
    int pa1, pa2, tmp = 0, ans = 0;
    for(int i = 1; i <= n; i++) prt[i] = i;
    for(int i = 1; i <= cnt; i++){
        pa1 = getpa(a[i].u);
        pa2 = getpa(a[i].v);
        if(pa1 != pa2){
            prt[pa2] = pa1;
            ans += a[i].w;
            tmp++;
            if(tmp == n-1) break;
        }
    }
    return ans;
}
int main()
{
    while(scanf("%d",&n) && n){
        for(int i = 1; i <= n; i++){
            scanf("%s",s[i]);
        }
        cnt = 0;
        for(int i = 1; i < n; i++){
            for(int j = i+1; j <= n; j++){
                a[++cnt].u = i;
                a[cnt].v = j;
                a[cnt].w = weight(i,j);
            }
        }
        sort(a+1,a+cnt+1);
        printf("The highest possible quality is 1/%d.\n",kruskal());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/kkjy_00/article/details/87919054