HDOJ 1875 畅通工程再续

示例的结果为1414.0,kruskal的返回类型写成了int,查了好几遍都没发现问题;

还是MST,kruskal,并查集,路径压缩;

# include <stdio.h>
# include <stdlib.h>
# include <math.h>

# define MAXN 105

typedef struct
{
    int u, v;
    double d;
} Bridge;

int m;
int p[MAXN], a[MAXN][2];
Bridge b[MAXN*50];

double kruskal(int n);
int find(int x)
{
    return x==p[x] ? x:(p[x] = find(p[x]));
}
int cmp(const void*x, const void*y)
{
    return (*(Bridge*)x).d>(*(Bridge*)y).d ? 1:-1;
}

int main()
{
    double t, ans;
    int T, i, j, k, dx, dy;

    scanf("%d", &T);
    while (T--)
    {
        scanf("%d", &m);
        for (i = 1; i <= m; ++i)
        {
            p[i] = i;
            scanf("%d%d", &a[i][0], &a[i][1]);
        }

        k = 0;
        for (i = 1; i < m; ++i)
            for (j = i+1; j <= m; ++j)
            {
                dx = a[i][0] - a[j][0];
                dy = a[i][1] - a[j][1];
                t = sqrt(dx*dx + dy*dy);
                if (t>=10 && t<=1000)
                {
                    ++k;
                    b[k].u = i;
                    b[k].v = j;
                    b[k].d = 100*t;
                }
            }

        ans = kruskal(k);
        if (ans >= 0) printf("%.1lf\n", ans);
        else puts("oh!");
    }

    return 0;
}

double kruskal(int n)
{
    double cost;
    int i, x, y, cnt;

    qsort(b+1, n, sizeof(b[0]), cmp);

    cnt = 0;
    cost = 0;
    for (i = 1; i <= n; ++i)
    {
        x = find(b[i].u);
        y = find(b[i].v);
        if (x != y)
        {
            ++cnt;
            cost += b[i].d;
            p[x] = y;
        }
    }

    return cnt==m-1 ? cost:-1;
}

 

1A,还很荣幸地登上了GCC的第一版,有图为证:

事实上,这道题用GCC提交的总共就这18个……

posted on 2012-04-22 13:46  getgoing  阅读(474)  评论(0编辑  收藏  举报

导航