poj 3625 (最小生成树算法)

Building Roads
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12203 Accepted: 3448

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

#include<iostream>
#include<stdio.h>
#include<cmath>
#define MAX_V 1005
using namespace std;


double cost[MAX_V][MAX_V];
double mincost[MAX_V];
bool used[MAX_V];
double X[MAX_V];double Y[MAX_V];
int V;
double min(double d1,double d2)
{
    return d1<d2?d1:d2;
}
double prim()
{
    for(int i=0;i<V;++i)
    {
        mincost[i]=1000000000.0;
        used[i]=false;
    }
    mincost[0]=0;
    double res=0;
    while(true)
    {
        int v=-1;
        for(int u=0;u<V;u++)
        {
            if(!used[u]&&(v==-1||mincost[u]<mincost[v]))v=u;
        }
        if(v==-1)break;
        used[v]=true;
        res+=mincost[v];
        for(int u=0;u<V;u++)
        {
            mincost[u]=min(mincost[u],cost[v][u]);
        }
    }
    return res;
}


double  dis(int i,int j)
{
    return sqrt((X[i]-X[j])*(X[i]-X[j])+(Y[i]-Y[j])*(Y[i]-Y[j]));
}


int main()
{
    freopen("in.txt","r",stdin);
    int M;
    cin>>V>>M;


    for(int i=0;i<V;i++)
    {
        cin>>X[i]>>Y[i];
    }


    for(int i=0;i<V;i++)
    {
        for(int j=i+1;j<V;j++)
        {
            cost[i][j]=cost[j][i]=dis(i,j);
        }
    }
    for(int i=0;i<V;i++)cost[i][i]=1000000000.0;
    int temp1,temp2;
    while(M--)
    {
        cin>>temp1>>temp2;
        //已经修建好的路则应理解为花费cost值为0
        cost[temp1-1][temp2-1]=cost[temp2-1][temp1-1]=0;
    }
    double ans=prim();
    printf("%.2f ",ans);
    return 0;
}

原文地址:https://www.cnblogs.com/linruier/p/9485184.html