poj 2485 Highways 最小生成树

poj 2485 Highways
//poj 2485 Highways

//MST(minimum spanning tree)

//here is want to get the longest road



#include <stdio.h>

#include <string.h>



#define N 505

#define INF 1<<30



int n;

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

bool vis[N];



void prim()

{

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

    {

        dis[i] = INF;

        vis[i] = false;

    }

    dis[0] = 0;

    while(1)

    {

        int min = INF, index = -1;

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

        {

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

            {

                min = dis[i];

                index = i;

            }

        }

        if(index == -1)

            return;

        vis[index] = true;



        if(ans < min)   //保存MST中的最长路

            ans = min;



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

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

                dis[i] = map[index][i];

    }

}



int main()

{

    int n_case;

    scanf("%d", &n_case);

    while(n_case--)

    {

        ans = 0;

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

        scanf("%d", &n);

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

        {

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

            {

                scanf("%d", &map[i][j]);

                map[j][i] = map[i][j];

            }

        }

        prim();

        printf("%d\n", ans);

    }

    return 0;

}

 

你可能感兴趣的:(最小生成树)