HDOJ 1875 畅通工程再续

来源:互联网 发布:数据库系统基础 编辑:程序博客网 时间:2024/05/19 02:39

~~~题目链接~~~


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;}


原创粉丝点击