Swordfish
2013-10-15 16:33
281 查看
zoj1203:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1203
题意:给定平面上N个城市的位置,计算连接这N个城市所需线路长度总和的最小值
题解:每两个点之间建一条边,然后求这一棵最小生成树。
View Code
题意:给定平面上N个城市的位置,计算连接这N个城市所需线路长度总和的最小值
题解:每两个点之间建一条边,然后求这一棵最小生成树。
#include<cstring> #include<cstdio> #include<algorithm> #include<iostream> #include<cmath> using namespace std; int n,pa[102],cnt,num;//分别记录点的个数 ,并查集,边的个数,以及处理的边的个数 struct Node{ double x; double y; }node[102];//记录每个点 struct Edge{ int u; int v; double w; bool operator<(const Edge &a)const{ return w<a.w;} }edge[10000];//记录每一条边,以及定义排序规则 void UFset(){ for(int i=1;i<=n;i++) pa[i]=-1; }//初始化 int Find(int x){//查找 int s; for(s=x;pa[s]>=0;s=pa[s]); while(s!=x){ int temp=pa[x]; pa[x]=s; x=temp; }//路径压缩,便于后面的查找 return s; } void Union(int R1,int R2){//合并,把个数的集合作为子树加到另一棵树上 int r1=Find(R1); int r2=Find(R2); int temp=pa[r1]+pa[r2]; if(pa[r1]>pa[r2]){ pa[r1]=r2; pa[r2]=temp; } else{ pa[r2]=r1; pa[r1]=temp; } } double dist(Node a,Node b){//计算每两个点之间距离 return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } double kruska(){//克鲁斯卡尔算法 UFset();//初始化 num=0; double sum=0.0; for(int i=0;i<cnt;i++){ int u=edge[i].u; int v=edge[i].v; if(Find(u)!=Find(v)){ sum+=edge[i].w; num++; Union(u,v); } if(num>=n-1)break; } return sum; } int main(){ int t=0; while(~scanf("%d",&n)&&n){ cnt=0;//初始化 for(int i=1;i<=n;i++) scanf("%lf%lf",&node[i].x,&node[i].y);//存边 for(int i=1;i<=n;i++){ for(int j=i+1;j<=n;j++){ edge[cnt].u=i; edge[cnt].v=j; edge[cnt++].w=dist(node[i],node[j]); } }//建边,每两个点之间建一条边 sort(edge,edge+cnt);//排序 if(t)printf("\n"); printf("Case #%d:\n",++t); printf("The minimal distance is: %.2f\n",kruska()); } }
View Code
相关文章推荐
- 2014校招-百度研发笔试-厦门站
- JavaScript中prototype为对象添加属性的误区介绍
- 第8周项目(1)求简化分段函数的值
- java对txt文本文件的复制粘贴(对文件内容进行了简单的修改)以行为一个处理单位
- linux下安装tomcat
- SRAM和DRAM的区别和联系
- 有用的国外开源项目网址
- POJ 1473 There's Treasure Everywhere!
- 指针的复杂声明
- 第八周 计算函数值的程序
- 从程序员到CTO的Java技术路线图
- K-Means 算法
- 点击立方体弹出GUI窗口
- 日期是NaN 转化成UTC格式时间
- Mysql 表分区
- js获取select标签选中的值
- C++ STL入门
- 把mac地址转换为标准mac地址
- ORACLE directory 目录
- 求分段函数值