POJ-1789 Truck History 最小生成树

 

 

计算整个汽车演化过程中所要改变的最少的字符数。改变的字符数的计算方式为1-7位不同位的个数。

 

代码如下:

 

#include <cstdlib>

#include <cstring>

#include <algorithm>

#include <cstdio>

using namespace std;



int N, pos, set[2005];



char s[2005][10];



struct Node

{

    int x, y, diff;

    bool operator < (Node t) const

    {

        return diff < t.diff;

    }

}e[4000005];



int diff(int x, int y)

{

    int cnt = 0;

    for (int i = 0; i < 7; ++i) {

        if (s[x][i] != s[y][i]) {

            ++cnt;

        }

    }

    return cnt;

}



int find(int x)

{

    return set[x] = x == set[x] ? x : find(set[x]);

}



void merge(int x, int y) 

{

    set[x] = y;

}



int main()

{

    int a, b, ans, cnt;

    while (scanf("%d", &N), N) {

        pos = ans = cnt = 0;

        for (int i = 1; i <= N; ++i) {

            scanf("%s", s[i]); 

            set[i] = i;

        }

        for (int i = 1; i <= N; ++i) {

            for (int j = i+1; j <= N; ++j) {      

                ++pos;

                e[pos].x = i, e[pos].y = j;

                e[pos].diff = diff(i, j);;

            }

        }

        sort(e+1, e+1+pos);

        for (int i = 1; i <= pos; ++i) {

            a = find(e[i].x), b = find(e[i].y);

            if (a != b) {

                printf("%d %d\n", e[i].x, e[i].y);

                ++cnt;

                merge(a, b);

                ans += e[i].diff;

                if (cnt == N-1) {

                    break;

                }

            }

        }

        printf("The highest possible quality is 1/%d.\n", ans);

    }

    return 0;   

}

你可能感兴趣的:(history)