最小生成树 POJ 3625Building Roads解题报告

来源:互联网 发布:windows任务栏不见了 编辑:程序博客网 时间:2024/04/24 23:21

Building Roads
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10099 Accepted: 2857
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
最小生成树的变型。在POJ2349基础上稍做改变。
如果farm i 、j在输入时就连接,那么令farm i、j之间距离为0。
接下来,正常Prim,寻找生成树,记录所有路径长度。长度为0的路径一定会在生成树中,且该路径不会改变ans,符合题意。
一个细节:将minPath定义成int WA了N次,改成double后才AC

 #include <iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<cmath>#define MAXN 1005#define INF 0xffffffusing namespace std;int N,M;int X[MAXN];//X[i]=1表示点i在最小生成树上double DisX[MAXN];//DisX[i]表示点i(非生成树点)到生成树所有点的最短距离double ans;double G[MAXN][MAXN];struct point{    int x,y;    point(){        x=0;y=0;    }}Point[MAXN];double GetDis(point a,point b){    return sqrt((double)(a.x-b.x)*(a.x-b.x)+(double)(a.y-b.y)*(a.y-b.y));}void prim(){   ans=0;   memset(X,0,sizeof(X));   //先将第一个点放到生成树中   X[1]=1;   for(int i=2;i<=N;i++) DisX[i]=G[i][1];   int nextPoint;   //再将剩下N-1个点放到生成树中   for(int i=1;i<=N-1;i++){      double minPath=INF;      for(int i=1;i<=N;i++){        if(!X[i]&&DisX[i]<minPath){          nextPoint=i;          minPath=DisX[i];        }      }      X[nextPoint]=1;      ans+=minPath;      for(int i=2;i<=N;i++){         if(!X[i]&&DisX[i]>G[nextPoint][i])         DisX[i]=G[nextPoint][i];        }  }  printf("%.2lf\n",ans);}int main(){    freopen("input.txt","r",stdin);    freopen("output.txt","w",stdout);    while(scanf("%d%d",&N,&M)!=EOF){     for(int i=1;i<=N;i++)        scanf("%d%d",&Point[i].x,&Point[i].y);     for(int i=1;i<=N;i++){        for(int j=1;j<=N;j++){            if(j>i) G[i][j]=GetDis(Point[i],Point[j]);            else if(j<i) G[i][j]=G[j][i];        }     }     int a,b;     for(int i=1;i<=M;i++){        scanf("%d%d",&a,&b);        G[a][b]=G[b][a]=0;     }     prim();    }    return 0;}
0 0
原创粉丝点击