D - Connect the Cities (HDU - 3371)
- 题目大意
某地发洪水,导致某些城市被淹而消失,现在想把剩下的零散的城市通过修路连接起来,已知现在有部分城市是连通的。可选择修的路有m条,城市总共有n个,给出了m条路的起点终点和修路花费,问最少可花多少钱能保证所有的城市连通。
- 解题思路
可以用kruskal。把边权排序然后并查集添加边即可。
- 代码
#include<algorithm>
#include<cstdio>
using namespace std;
int fa[505];struct Edge {int u, v, w;bool operator<(const Edge &rhs)const {return w < rhs.w;}
}e[25005];
void init(int n)
{for (int i = 1; i <= n; i++)fa[i] = i;
}int find(int x)
{if (x == fa[x])return x;else{return fa[x] = find(fa[x]);}
}bool Union(int x, int y)
{int fx = find(x), fy = find(y);if (fx == fy)return false;else{fa[fx] = fy;return true;}
}void kruskal(int m,int k)
{int sum = 0;sort(e, e + m);for (int i = 0; i < m; i++){int u = e[i].u, v = e[i].v, w = e[i].w;if (Union(u, v)){sum += w;k--;}}if (!k)printf("%d\n", sum);else{printf("-1\n");}
}
int main()
{int n,m,t,p,q,c,k,tmp;scanf_s("%d",&t);while (t--){scanf_s("%d%d%d",&n,&m,&k);init(n);for (int i = 0; i < m; i++)scanf_s("%d%d%d",&e[i].u,&e[i].v,&e[i].w);tmp = n-1;for (int j = 0; j < k; j++){scanf_s("%d%d",&p,&q);while (--p){scanf_s("%d", &c);if (Union(q,c)){tmp--;}}}kruskal(m, tmp);}return 0;
}
转载于:https://www.cnblogs.com/alpacadh/p/8449434.html
D - Connect the Cities (HDU - 3371)相关推荐
- hdu 3371 Connect the Cities(prim算法)
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3371 Connect the Cities Time Limit: 2000/1000 MS (Ja ...
- HDU 3371 Kruskal
这里边比较多,而且告诉了所需的边以及它们的权值,所以只要遍历edge,利用Kruskal算法 #include <cstdio> #include <cstring> #inc ...
- 图论500题 慢慢写
题目来源 https://blog.csdn.net/ffq5050139/article/details/7832991 这篇博客用来记录自己刷的图论题 先占个坑 所有题目都来自上面的链接 会慢慢更 ...
- 杭电OJ分类题目(4)-Graph
原题出处:HDOJ Problem Index by Type,http://acm.hdu.edu.cn/typeclass.php 杭电OJ分类题目(4) HDU Graph Theory - U ...
- 【转载】图论 500题——主要为hdu/poj/zoj
转自--http://blog.csdn.net/qwe20060514/article/details/8112550 =============================以下是最小生成树+并 ...
- [Swift]LeetCode1135. 最低成本联通所有城市 | Connecting Cities With Minimum Cost
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ➤微信公众号:山青咏芝(shanqingyongzhi) ➤博客园地址:山青咏芝(https://www.cnblog ...
- Battle over Cities
Battle over Cities Time Limit : 10000/5000ms (Java/Other) Memory Limit : 65536/65536K (Java/Other) ...
- Connect city
Description At the year of 20?? , since some strange reasons, most of the cities disappear. Though s ...
- 【HDOJ图论题集】【转】
1 =============================以下是最小生成树+并查集====================================== 2 [HDU] 3 1213 How ...
最新文章
- vba sub是什么缩写_这些掌握了,你才敢说自己懂VBA
- java nio 消息_java nio消息半包、粘包解决方案
- css3 操作动画要点
- 计算机网络校园网络设计方案,毕业论文--《计算机网络》校园网设计方案
- 删除单链表中的重复节点
- Qt开发之路——基于RedfishAPI的服务器管理小应用
- erlang的又一力作——英雄联盟聊天服务器
- html页面网页打开乱码怎么解决方法,网页乱码怎么解决?
- 计算机开关电源 原理与应用,开关电源原理与应用设计
- DQ77KB刷bios工程小记-old文章备份
- c语言坦克大战程序设计,用纯C语言实现坦克大战
- 得意不张狂失败不气妥
- 习题6-5 使用函数验证哥德巴赫猜想 (20 point(s))
- mysql如何收费,mysql收费吗
- 哈工大计算机系统大作业——hello P2P
- php unix时间戳 秒,UNIX时间戳怎么在php项目中使用
- python爬取图片到本地文件夹
- 老方块 oracle培训,老方块Oracle 11g培训新版小学班 SQL 完整35课 星爷版 OCA OCP
- 2023年工程师中级和高级有什么区别,他们评审的要求有哪些不同?
- 「最通俗易懂」的java数组去重(其他语言通用)