hdu1875 畅通工程再续【最小生成树】

来源:互联网 发布:淘宝阿里旺旺卖家版 编辑:程序博客网 时间:2024/06/10 14:32

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1875
题意:中文题
解析:建图后直接跑kruskal最小生成树,然后判断并查集后有是否有多个集合

#include <bits/stdc++.h>using namespace std;const int maxn = 1e5+100;struct node{    int u,v;    double c;    node() {}    node(int _u,int _v,double _c)    {        u = _u;        v = _v;        c = _c;    }    bool operator < (const node &b)const    {        return c<b.c;    }}res[maxn];struct point{    double x,y;}a[maxn];double dis(point p1,point p2){    return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));}int fa[maxn];int getFa(int x){    if(x==fa[x])        return fa[x];    return fa[x] = getFa(fa[x]);}int main(void){    int t;    scanf("%d",&t);    while(t--)    {        int n;        scanf("%d",&n);        for(int i=0;i<=n;i++)            fa[i] = i;        for(int i=1;i<=n;i++)            scanf("%lf %lf",&a[i].x,&a[i].y);        int cnt = 0;        for(int i=1;i<=n;i++)        {            for(int j=i+1;j<=n;j++)            {                double d = dis(a[i],a[j]);                if(d>=10 && d<=1000)                    res[cnt++] = node(i,j,d*100.0);            }        }        sort(res,res+cnt);        double ans = 0;        for(int i=0;i<cnt;i++)        {            int t1 = getFa(res[i].u);            int t2 = getFa(res[i].v);            if(t1!=t2)            {                ans += res[i].c;                fa[t1] = t2;            }        }        cnt = 0;        for(int i=1;i<=n;i++)        {            if(fa[i]==i)                cnt++;        }        if(cnt>1)            puts("oh!");        else            printf("%.1f\n",ans);    }    return 0;}
原创粉丝点击