poj2349

最小生成树,克鲁斯卡尔

View Code
//poj2349
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;

const    int        maxp = 501, maxdist = 20000;

struct
{
    int        x, y;
}point[maxp];

struct edge
{
    int        v;
    double    w;
    edge(double w, int v):w(w),v(v){}
};

int        s, p, lencount;
bool    vused[maxp];
double    len[maxp * maxp], vdist[maxp];

bool operator<(edge a, edge b)
{
    return a.w > b.w;
}

void init()
{
    int        i;

    scanf("%d%d", &s, &p);
    for (i = 0; i < p; i++)
    {
        scanf("%d%d", &point[i].x, &point[i].y);
        vdist[i] = maxdist;
    }
    memset(vused, 0, sizeof(vused));
    lencount = 0;
}

double distance(int a, int b)
{
    return sqrt(double((point[a].x - point[b].x) * (point[a].x - point[b].x) + (point[a].y - point[b].y) * (point[a].y - point[b].y)));
}

void maketree()
{
    int        i, ncount;
    edge    temp(0, 0);
    double    dis;

    priority_queue<edge> pq;
    vdist[0] = 0;
    vused[0] = true;
    ncount = 1;
    pq.push(edge(0, 0));
    while (ncount <= p)
    {
        do
        {
            temp = pq.top();
            pq.pop();
        }while (vused[temp.v] && !pq.empty());
        len[lencount++] = temp.w;
        vused[temp.v] = true;
        ncount++;
        for (i = 0; i < p; i++)
            if (!vused[i])
            {
                dis = distance(temp.v, i);
                if (dis < vdist[i])
                {
                    vdist[i] = dis;
                    pq.push(edge(dis, i));
                }
            }
    }
    sort(len, len + lencount);
    printf("%.2f\n", len[p - s]);
}

int main()
{
    int        t;

    //freopen("t.txt", "r", stdin);
    scanf("%d", &t);
    while (t--)
    {
        init();
        maketree();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/rainydays/p/2777700.html