POJ 3625 Building Roads

Building Roads
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 1204 Accepted: 307

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 (Xi, Yi) on the plane (0 ≤ Xi ≤ 1,000,000; 0 ≤ Yi ≤ 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: Xi and Yi
* 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

USACO 2007 December Silver
 
题目要求求出最短的路使得所有的村庄都可达,最小生成树.不过构图的时候要注意它给的是坐标,算出左边之间的距离当成权重就OK了
  1. #include<iostream>
  2. #include <math.h>
  3. using namespace std;
  4. struct _point
  5. {
  6.     double x,y;
  7. }p[1001];
  8. #define MAXN 1001
  9. #define inf 1000000000
  10. typedef double elem_t;
  11. double mat[MAXN][MAXN];
  12. elem_t prim(int n,elem_t mat[][MAXN]){
  13.     elem_t min[MAXN],ret=0;
  14.     int v[MAXN],i,j,k;
  15.     for (i=0;i<n;i++)
  16.         min[i]=inf,v[i]=0;
  17.     for (min[j=0]=0;j<n;j++){
  18.         for (k=-1,i=0;i<n;i++)
  19.             if (!v[i]&&(k==-1||min[i]<min[k]))
  20.                 k=i;
  21.         for (v[k]=1,ret+=min[k],i=0;i<n;i++)
  22.             if (!v[i]&&mat[k][i]<min[i])
  23.                 min[i]=mat[k][i];
  24.     }
  25.     return ret;
  26. }
  27. int main()
  28. {
  29.     int n,m,i,j,a,b;
  30.     cin>>n>>m;
  31.     for(i=0;i<=n;i++)
  32.         for(j=0;j<=n;j++)
  33.             mat[i][j]=inf;
  34.     for(i=0;i<n;i++)
  35.         {
  36.             cin>>p[i].x>>p[i].y;
  37.         }
  38.     for(i=0;i<n;i++)
  39.         for(j=0;j<n;j++)
  40.             {
  41.                 if(i==j) continue;
  42.                 mat[i][j]=sqrt((p[i].x-p[j].x)*(p[i].x-p[j].x)+(p[i].y-p[j].y)*(p[i].y-p[j].y));
  43.             }
  44.         for(i=0;i<m;i++)
  45.             {
  46.                 cin>>a>>b;
  47.                 mat[a-1][b-1]=mat[b-1][a-1]=0;
  48.             }
  49.     printf("%.2lf/n",prim(n,mat));
  50.     return 0;
  51. }
 

你可能感兴趣的:(POJ 3625 Building Roads)