POJ 2349 Arctic Network(Kruskal求最小生成树第k条边的长度)

//
//  main.cpp
//  Richard
//
//  Created by 邵金杰 on 16/8/17.
//  Copyright © 2016年 邵金杰. All rights reserved.
//


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
const int maxn=250000+100;
struct Point{
    double x,y;
    Point(double x,double y): x(x),y(y) {}
};
struct edge{
    int u,v;
    double dist;
    edge(int u,int v,double dist): u(u),v(v),dist(dist) {}
    bool operator < (const edge &e) const {
        return dist<e.dist;
    }
};
int pa[maxn],sum[maxn];
int total;
int s,p;
int getroot(int a) {return pa[a]==a?a:pa[a]=getroot(pa[a]);}
double dist(Point p1,Point p2)
{
    double x=p1.x-p2.x;
    double y=p1.y-p2.y;
    return hypot(x,y);
}
void Kruskal(vector<edge> ve)
{
    sort(ve.begin(),ve.end());
    for(int i=0;i<p;i++) pa[i]=i,sum[i]=1;
    double maxdist=0;
    int ncount1=s-1;
    int ncount2=p-1;
    int q=0;
    for(int i=0;i<ve.size();i++)
    {
        int root1=getroot(ve[i].u);
        int root2=getroot(ve[i].v);
        if(root1==root2) continue;
        q++;
        pa[root2]=root1;
        if(q==ncount2-ncount1) {maxdist=ve[i].dist;break;}
    }
    printf("%.2f\n",maxdist);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(pa,0,sizeof(pa));
        memset(sum,0,sizeof(sum));
        vector<Point> vp;
        vector<edge>  ve;
        vp.clear();
        ve.clear();
        double x,y;
        scanf("%d%d",&s,&p);
        for(int i=0;i<p;i++)
        {
            scanf("%lf%lf",&x,&y);
            vp.push_back(Point(x,y));
        }
        for(int i=0;i<vp.size();i++)
        {
            for(int j=i+1;j<vp.size();j++)
            {
                edge e(i,j,dist(vp[i],vp[j]));
                ve.push_back(e);
            }
        }
        Kruskal(ve);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值