poj 3625 Building Roads (prim)

来源:互联网 发布:建立党建工作网络平台 编辑:程序博客网 时间:2024/05/18 03:08

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 11 13 12 34 31 4

Sample Output

4.00
#include<stdio.h>#include<string.h>#include<cmath>#include<algorithm>#define inf 0x3f3f3f3fusing namespace std;int pre[10003];int vis[10003];double dis[10003];double x[1003],y[1003];double Side[1003][1003];int n,m;double res=0;double Distance(double x1,double y1,double x2,double y2){    return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));}void prime(){    res=0;    memset(vis,0,sizeof(vis));    for(int i=1;i<=n;i++)        dis[i]=Side[1][i];    dis[1]=0;    vis[1]=1;    int k;    double Min=inf;    for(int i=1;i<n;i++)    {        Min=inf;        for(int j=1;j<=n;j++)        {            if(dis[j]<Min&&!vis[j])                Min=dis[j],k=j;        }        //printf("%.2f\n",Min);        res+=Min;        vis[k]=1;        for(int j=1;j<=n;j++)        {            if(dis[j]>Side[k][j]&&!vis[j])                dis[j]=Side[k][j];        }    }}int main(){    while(~scanf("%d%d",&n,&m))    {        for(int i=1;i<=n;i++)        {            scanf("%lf%lf",&x[i],&y[i]);        }        for(int i=1;i<=n;i++)            for(int j=1;j<=n;j++)            Side[i][j]=inf;        for(int i=1;i<=n;i++)Side[i][i]=0;        for(int i=1;i<=n;i++)        {            for(int j=i+1;j<=n;j++)            {                Side[i][j]=Side[j][i]=Distance(x[i],y[i],x[j],y[j]);            }        }        int a,b;        for(int i=1;i<=m;i++)        {            scanf("%d%d",&a,&b);            Side[a][b]=Side[b][a]=0;        }        prime();        printf("%.2f\n",res);    }}

原创粉丝点击