HDU 1875 畅通工程再续



    大致思路:基础最小生成树,kruskal。循环两遍把每两个点的距离计算出来即可,注意是浮点型。


#include
#include
#include
#include
#include
using namespace std;
int per[105],dian[2][105];
double jsjl(int a,int b, int c, int d)//计算两点之间的距离;
{
    return sqrt((a-c)*(a-c) + (b-d)*(b-d));
}
void init()//初始化;
{
    for(int i = 0; i < 105; i ++)
    {
        per[i] = i;
    }
    memset(dian,0,sizeof(dian));
}
struct Edge
{
    int x;
    int y;
    double dis;
}edge[10005];

bool cmp(Edge a, Edge b)
{
    return a.dis < b.dis;
}
int find(int x)
{
    if(x != per[x])
        per[x] = find(per[x]);
    return per[x];
}
void join(int x, int y)
{
    int s = find(x);
    int e = find(y);
    if(s != e)
    {
        per[s] = e;
    }
}
double kruskal(int n,int c)
{
    sort(edge,edge+c,cmp);
    double sum = 0;//注意不要设成整型;刚开始很zz的设错了,找了半天的bug;
    int cnt = 0;
    for(int i = 0; i < c; i ++)
    {
        if(edge[i].dis > 1000 || edge[i].dis < 10 )
            continue;
        int s = find(edge[i].x);
        int e = find(edge[i].y);
        if(s != e)
        {
            join(s,e);
            cnt ++;
            sum += edge[i].dis;
        }
        if(cnt == n-1)
            break;
    }
    if(cnt < n-1)
        return -1;
    return sum;
}
int main()
{
    int T,n;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        init();
        for(int i = 1; i <= n; i ++)
        {
            scanf("%d%d",&dian[0][i],&dian[1][i]);
        }
        int c = 0;
        for(int i =1; i <= n; i ++)
        {
            for(int j = i+1; j <= n; j ++)
            {
                edge[c].x = i;
                edge[c].y = j;
                edge[c].dis = jsjl(dian[0][i],dian[1][i],dian[0][j],dian[1][j]);
                c++;
            }
        }
        double d = kruskal(n,c);
        if(d < 0)
        {
            printf("oh!\n");
            continue;
        }

        printf("%.1lf\n",d*100);
    }
    return 0;
}

    如有错误,欢迎指出~


你可能感兴趣的:(acm,图论)