您的位置:首页 > 其它

POJ:1751 Highways

2013-10-09 12:45 281 查看
最小生成树。这个题POJ上要用G++交,C++会超时。再就是注意到是special judge就行了,

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define MAXN  1000
using namespace std;
struct Edge
{
    int a,b;
    double weight;
};
struct Point
{
    int x,y;
};
int father[MAXN];
int find(int p)
{
    return p==father[p]?p:(father[p]=find(father[p]));
}
double Dist(Point a,Point b)
{
    double ll=(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
    return sqrt(ll);
}
bool cmp(Edge a,Edge b)
{
    return a.weight<b.weight;
}
Edge e[MAXN*MAXN];
Point po[MAXN];
int main()
{
    int n,m;
    while(scanf("%d",&n)!=EOF&&n)
    {
        for(int i=1; i<=n; ++i)
            scanf("%d%d",&po[i].x,&po[i].y);
        scanf("%d",&m);
        int u,v;
        for(int i=0; i<=n; ++i)
            father[i]=i;
        for(int i=0; i<m; ++i)
        {
            scanf("%d%d",&u,&v);
            if(find(u)!=find(v))
                father[find(u)]=find(v);
        }
        int N=0,cou=0;
        for(int i=1; i<n; ++i)
            for(int j=i+1; j<=n; ++j)
            {
                e
.a=i;
                e
.b=j;
                e[N++].weight=Dist(po[i],po[j]);
            }
        sort(e,e+N,cmp);
        Edge ans[MAXN];
        for(int i=0; i<N; ++i)
        {
            int ta=find(e[i].a),tb=find(e[i].b);
            if(ta!=tb)
            {
                father[ta]=tb;
                printf("%d %d\n",e[i].a,e[i].b);
                cou++;
                if(cou>n-1) break;
            }
        }
        if(cou) printf("\n");
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: