Highways POJ

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=800;
int n,m,tot,u,v; 
int pre[maxn];
//存点 
struct Point{
    int x,y;
}point[maxn];
//建边 
struct Edge{
    int a,b;
    double w;
}edge[maxn*maxn];
//答案 
struct Ans{
    int u,v;
}ans[maxn];
bool cmp(struct Edge a,struct Edge b)
{
    return a.w<b.w;
}
double Distance(struct Point a,struct Point b)
{
    int xx=a.x-b.x;
    int yy=a.y-b.y;
    return sqrt(xx*xx+yy*yy);
}
int find(int x)
{
    return pre[x]==x?x:pre[x]=find(pre[x]);
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d%d",&point[i].x,&point[i].y);
    tot=0;
    for(int i=1;i<=n;i++)
        for(int j=i+1;j<=n;j++)
        {
            edge[tot].a=i;
            edge[tot].b=j;
            edge[tot].w=Distance(point[i],point[j]);
            tot++;
        }
    sort(edge,edge+tot,cmp);
    for(int i=0;i<maxn;i++)
        pre[i]=i;
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d",&u,&v);
        int a=find(u);
        int b=find(v);
        if(a!=b) 
            pre[a]=b;
    }
    int tmp=0;
    int a,b;
    for(int i=0;i<tot;i++)
    {
        u=edge[i].a;
        v=edge[i].b;
        a=find(u);
        b=find(v);
        if(a!=b)
        {
            pre[a]=b;
            ans[tmp].u=u;
            ans[tmp].v=v;
            tmp++;
        }
    }
    for(int i=0;i<tmp;i++)
        printf("%d %d
",ans[i].u,ans[i].v);
    return 0;
}
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/12240298.html