练习四1004
来源:互联网 发布:linux最大连接数65536 编辑:程序博客网 时间:2024/05/21 06:23
题意:在乡村之间修公路,给定n个乡村,然后是n行,每行给定两个数代表了两个乡村和第三个数代表这两个村之间修路的费用,求使公路联通的修路的最小的费用。
思路:根据kruskal算法,写find函数,再写一个结构体,再写一个merge函数,把两村之间的权值排序求和即可。
感悟:好好学算法,做题也很爽。
AC代码:
#include<iostream>#include<stdio.h>#include<algorithm>using namespace std;const int N=1005;int father[N];int find(int x){ if(x!=father[x]) father[x]=find(father[x]); return father[x];}struct edge{ int x,y,v;}e[N*(N-1)/2];int cmp(edge e1,edge e2){ return e1.v<e2.v;}int main(){ int n; while(scanf("%d",&n),n) { for(int i=1;i<=n;i++) father[i]=i; n=n*(n-1)/2; for(int i=0;i<n;i++) scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].v); sort(e,e+n,cmp); int res=0; for(int i=0;i<n;i++) { int x=find(e[i].x); int y=find(e[i].y); if(x!=y) { res+=e[i].v; father[x]=y; } } printf("%d\n",res); } return 0;}
0 0
- 练习四 1004
- 练习四 1004
- 练习四1004
- 练习四
- 数据库练习四
- 查询练习(四)
- Scala练习(四)
- 听课练习(四)
- 笔试练习四
- 笔试练习四
- 练习四1001
- 练习四 1001
- 练习四 1003
- 练习四 1002
- 练习四 1005
- 练习四 1001
- 练习四 1002
- 练习四 1003
- 第30课:集群运行模式下的Spark Streaming日志和Web监控台实战演示彻底解密
- dp斜率优—2
- 客服端.1
- 路径匹配模块-glob
- 【mysql索引学习一】mysql索引使用
- 练习四1004
- Android学习路线
- CSS
- 浅谈学习JS和JQuery中的几点收获
- 微信小店,微店,微盟店,淘宝的区别以及微店和微商城的区别
- GEEK编程练习— —有效括号问题
- js自动触发事件
- mybatis_user_guide(4) Mapper XML 文件
- 九宫格均匀布局