UVA 10369 - Arctic Network

最小生成树问题,kruskal算法的变形。

代码如下:

#include<stdio.h>

#include<math.h>

#include<stdlib.h>

#define MAXN1 500+10

#define MAXN 3000000



int z, n, s, m, x[MAXN1], y[MAXN1], u[MAXN], v[MAXN], p[MAXN1], r[MAXN];

double w[MAXN], flag[MAXN];



int cmp(const void *_p, const void *_q)

{

    int *p = (int *)_p;

    int *q = (int *)_q;

    return w[*p] > w[*q] ? 1: -1;

}

int find(int o) {return p[o] == o ? o : p[o] = find(p[o]);}

double kruskal()

{

    int q = 0;

    for(int i = 0; i <= m; i ++) p[i] = i;

    for(int i = 0; i <= z; i ++) r[i] = i;

    qsort(r, z, sizeof(r[0]), cmp);

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

    {

        int e = r[i]; int x1 = find(u[e]); int y1 = find(v[e]);

        if(x1 != y1) { p[x1] = y1;flag[q++] = w[e];}

    }

    return flag[q-s];

}

void init()

{

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

        while(n --)

        {

            scanf("%d%d",&s,&m);

            for(int i = 1; i <= m; i ++)

                scanf("%d%d",&x[i],&y[i]);

            z = 0; 

            for(int i = 1; i <= m; i ++)

                for(int j = i+1; j <= m; j ++)

                {

                    u[z] = i; v[z] = j;

                    w[z++] = sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));

                }

            printf("%.2lf\n",kruskal());

        }

}

int main()

{

    init();

    return 0;

}

你可能感兴趣的:(NetWork)