HDOJ 1875 暢通工程再續

~~~題目鏈接~~~


code:

#include <stdio.h>
#include <math.h>
#include <algorithm>
using namespace std;
struct node1
{
    int x, y;
}num[102];
struct node2
{
    int s, t;
    double c;
    bool operator <(const node2 &s) const
    {
        return c<s.c;
    }
}edge[5005];
int cnt = 0, r[102], f[102];

void init(int n)
{
    int i = 0, j = 0, x1 = 0, y1 = 0, x2 = 0, y2 = 0;
    double c = 0;
    for(i = 0; i<n; i++)
    {
        x1 = num[i].x;
        y1 = num[i].y;
        r[i] = 0;
        f[i] = i;
        for(j = i+1; j<n; j++)
        {
            x2 = num[j].x;
            y2 = num[j].y;
            c = sqrt(pow(x1-x2, 2)+pow(y1-y2, 2));
            if(c>=10 && c<1000)
            {
                edge[cnt].s = i;
                edge[cnt].t = j;
                edge[cnt++].c = c*100;
            }
        }
    }
}

int find(int x)
{
    if(f[x] != x)
        f[x] = find(f[x]);
    return f[x];
}

void Union(int x, int y)
{
    if(r[x]<r[y])
        f[x] = y;
    else
    {
        if(r[x] == r[y])
            r[x]++;
        f[y] = x;
    }
}

double Kruskal()
{
    int i = 0, x = 0, y = 0, fx = 0, fy = 0;
    double c = 0, sum = 0;
    for(i = 0; i<cnt; i++)
    {
        x = edge[i].s;
        y = edge[i].t;
        c = edge[i].c;
        fx = find(x), fy = find(y);
        if(fx == fy) continue;
        Union(fx, fy);
        sum += c;
    }
    return sum;
}

int judge(int n)
{
    int cnt = 0;
    for(int i = 0; i<n; i++)
    {
        if(cnt == 0 && f[i] == i) cnt++;
        else if(cnt == 1 && f[i] == i) return 1;
    }
    return 0;
}

int main()
{
    int i = 0, n = 0, t = 0;
    double ans = 0;
    scanf("%d", &t);
    while(t--)
    {
        cnt = 0;
        scanf("%d", &n);
        for(i = 0; i<n; i++)
            scanf("%d %d", &num[i].x, &num[i].y);
        init(n);
        sort(edge, edge+cnt);
        ans = Kruskal();
        if(judge(n))
            printf("oh!\n");
        else
            printf("%.1lf\n", ans);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章