标签:
题目大意:
根据一张图的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; }
标签:
原文地址:http://www.cnblogs.com/Sikaozhe/p/5615218.html