POJ  3625  Building Roads

Building Roads
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 6392Accepted: 1842

Description

Farmer John had just acquired several new farms! He wants to connect the farms with roads so that he can travel from any farm to any other farm via a sequence of roads; roads already connect some of the farms.

Each of the N (1 ≤ N ≤ 1,000) farms (conveniently numbered 1..N) is represented by a position (XiYi) on the plane (0 ≤ X≤ 1,000,000; 0 ≤ Y≤ 1,000,000). Given the preexisting M roads (1 ≤ M ≤ 1,000) as pairs of connected farms, help Farmer John determine the smallest length of additional roads he must build to connect all his farms.

Input

* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Two space-separated integers: Xand Y
* Lines N+2..N+M+2: Two space-separated integers: i and j, indicating that there is already a road connecting the farm i and farm j.

Output

* Line 1: Smallest length of additional roads required to connect all farms, printed without rounding to two decimal places. Be sure to calculate distances as 64-bit floating point numbers.

Sample Input

4 1 
1 1 
3 1 
2 3 
4 3 
1 4

Sample Output

4.00

Source

发现做题真是极度考验心理承受能力,明明结果对,却非得转换一下数据类型用sqrt的时候请注意了,具体格式见我的代码:
#include<stdio.h>
#include<math.h>
double map[1008][1008],num;
int x[1008],y[1008],n;
double Distance(int i,int j)
{
        return sqrt((x[i]-x[j]+0.0)*(x[i]-x[j]+0.0)+(y[i]-y[j]+0.0)*(y[i]-y[j]+0.0));
}
void Prime()
{
        int flag[1008],dir[1008],i,j,k;
        double lenth[1008],min;
        for(i=1;i<=n;i++)
        {
         dir[i]=i;
         flag[i]=0;
         lenth[i]=map[1][i];
        }
        flag[1]=1;
        for(i=1;i<=n;i++)
        {
         min=100000000.0;
         for(j=1;j<=n;j++)
         if(flag[j]==0&&lenth[j]<min)
         {
         min=lenth[j];
         k=j;
         }
         if(min==100000000.0)break;
         flag[k]=1;
         num+=min;
         for(j=1;j<=n;j++)
         if(flag[j]==0&&lenth[j]>map[k][j])
         lenth[j]=map[k][j];
        }
}
int main()
{
        int m,i,j,a,b;
        while(scanf("%d%d",&n,&m)!=EOF)
        {
         for(i=1;i<=n;i++)
         scanf("%d%d",&x[i],&y[i]);
       for(i=1;i<=n;i++)
         {
         map[i][i]=0;
         for(j=1;j<i;j++)
         map[i][j]=map[j][i]=Distance(i,j);
         }
         for(i=1;i<=m;i++)
         {
         scanf("%d%d",&a,&b);
         map[a][b]=map[b][a]=0;
         }
                num=0;
                Prime();
            printf("%.2lf\n",num);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值