HDU 1875-kruskal

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1875

思路:還是簡單的最小生成樹;

代碼:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include<cmath>
using namespace std;
const int  maxn=10009;
struct Node
{
    int x,y;
    double w;
    bool operator<(const Node &a)const
    {
        return w<a.w;
    }
} sd[maxn];
struct node
{
    int a,b;
} sk[maxn];
int p[maxn],n,m;
int Find(int x)
{
    if(p[x]==-1)
    {
        return x;
    }
    return p[x]=Find(p[x]);
}
void Kruskal(int k)
{
    double ans=0;
    int  cnt=0;
    for(int i=0; i<k; i++)
    {
        int x=Find(sd[i].x);
        int y=Find(sd[i].y);
        if(x!=y)
        {
            cnt++;
            ans+=sd[i].w;
            p[x]=y;
        }
    }
    if(cnt<n-1)
        printf("oh!\n");
    else printf("%.1lf\n",ans);
}
double gh(double a,double b,double c,double d)
{
    return sqrt((a-c)*(a-c)+(b-d)*(b-d));
}
int main()
{
    while(scanf("%d",&m)!=EOF)
    {
        for(int i=0; i<m; i++)
        {
            scanf("%d",&n);
            memset(p,-1,sizeof(p));
            for(int i=0; i<n; i++)
                scanf("%d%d",&sk[i].a,&sk[i].b);
            int k=0;
            for(int i=0; i<n-1; i++)
            {
                for(int j=i+1; j<n; j++)
                {
                    double df=gh(sk[i].a,sk[i].b,sk[j].a,sk[j].b);
                   // printf("&&&%d\n",df);
                    if(df>=10&&df<=1000)
                    {

                        sd[k].w=df*100.0;
                        sd[k].x=i;
                        sd[k].y=j;
                        k++;
                    }
                }
            }
            sort(sd,sd+k);
            Kruskal(k);
        }
    }
    return 0;
}

發佈了34 篇原創文章 · 獲贊 8 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章