poj 1789 Truck History MST(最小生成树)

poj 1789 Truck History
//poj 1789 Truck History

//MST(minimum spanning tree)

//It's mean is: there is several type of truck and every truck

//is marked by a string with 7 lowercase character

//and distance between two truck is the number of differnt character

//between two string



#include <stdio.h>

#include <string.h>



#define N 2005

#define INF 1 << 30



int n;

int map[N][N], dis[N], ans;

char type[N][9];

bool vis[N];



void prim()

{

    for(int i = 0; i < n; ++i)

    {

        dis[i] = INF;

        vis[i] = false;

    }

    dis[0] = 0;

    while(1)

    {

        int now = -1, min = INF;

        for(int i = 0; i < n; ++i)

        {

            if(min > dis[i] && vis[i] == false)

            {

                min = dis[i];

                now = i;

            }

        }

        if(now == -1)

            break;

        ans += min;         //accumulate the answer

        vis[now] = true;    //have been visited

        for(int i = 0; i < n; ++i)

            if(vis[i] == false && dis[i] > map[now][i])

                dis[i] = map[now][i];

    }

}



int main()

{

    //freopen("in.txt", "r", stdin);

    while(scanf("%d", &n), n)

    {

        ans = 0;

        memset(map, 0, sizeof(map));

        for(int i = 0; i < n; ++i)

        {

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

            for(int j = 0; j < i; ++j)

            {

                int dist = 0;

                for(int k = 0; k < 7; ++k)

                    if(type[i][k] != type[j][k])

                        dist++;

                map[i][j] = map[j][i] = dist;   //build map

            }

        }

        prim();

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

    }

    return 0;

}

 

你可能感兴趣的:(history)