码迷,mamicode.com
首页 > 其他好文 > 详细

1002

时间:2016-06-24 20:26:11      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

题目大意:

根据一张图的n个点求最短路径

解题思路:

用prim或kruskal算法求最小生成数

代码:

#include<cstdio>
#include<iostream>
 #include<cmath>
 #include<algorithm>
 using namespace std;
 struct Node
 { int x,y;
   double cost;
 }g[5005];
 int pre[105];
 int find(int n){return n==pre[n]? n: find(pre[n]);}
 bool cmp(Node a,Node b){return a.cost < b.cost;}
 int main()
 {
     int n;
     while(scanf("%d",&n) != EOF){
         int k=0;
         double sum=0;
         double x[105],y[105];
         for(int i = 1; i <= n; i++)scanf("%lf%lf",&x[i],&y[i]);
         for(int i = 1;i <= n; i++)
             for(int j = i+1; j <= n; j++){
                  g[k].x = i;
                  g[k].y = j;
                  g[k++].cost = sqrt(abs((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])));
         }
         for(int i = 1;i <= n; i++)pre[i] = i;
         sort(g,g+k,cmp);
         for(int i = 0; i < k; i++){
                 int x = find(g[i].x);
                 int y = find(g[i].y);
                 double z = g[i].cost;
                 if(x != y){
                     sum += z;
                     pre[x]=y;
                 }

         }
         printf("%.2f\n",sum);
     }
     return 0;
 }

 

1002

标签:

原文地址:http://www.cnblogs.com/Sikaozhe/p/5615218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!