[kuangbin带你飞]专题六 最小生成树 D - Constructing Roads

傷城~ 2023-08-17 15:41 214阅读 0赞

D - Constructing Roads

题目链接:https://vjudge.net/contest/66965#problem/D

题目:

**有N个村庄,编号从1到N,你应该建造一些道路,使每两个村庄可以相互连接。我们说两个村A和B是相连的,当且仅当A和B之间有一条道路,或者存在一个村C以便在A和C之间有一条道路,并且C和B相连。

  1. 我们知道一些村庄之间已经有一些道路,你的工作就是修建一些道路,使所有村庄都连通起来,所有道路的长度都是最小的。

输入
第一行是整数N(3 <= N <= 100),这是村庄的数量。然后是N行,其中第i个包含N个整数,这些N个整数中的第j个是村庄i和村庄j之间的距离(距离应该是[1,1000]内的整数)。

  1. 然后是整数Q0 <= Q <= N \*N + 1)/ 2)。然后是Q行,每行包含两个整数ab1 <= a <b <= N),这意味着村庄a和村庄b之间的道路已经建成。

产量
您应该输出一个包含整数的行,该整数是要构建的所有道路的长度,以便连接所有村庄,并且此值最小。
样本输入

  1. 3
  2. 0 990 692
  3. 990 0 179
  4. 692 179 0
  5. 1
  6. 1 2

样本输出

  1. 179**

思路:只要求最小生成树就行,运用到并查集,详解

  1. //
  2. // Created by hy on 2019/7/30.
  3. //
  4. #include<algorithm>
  5. #include <iostream>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <queue>
  9. #include <set>
  10. #include<math.h>
  11. using namespace std;
  12. typedef long long ll;
  13. const int maxn=2e5+10;
  14. int father[maxn];
  15. struct Node{
  16. int u,v,w;
  17. bool operator<(const Node &other)const{
  18. return this->w<other.w;
  19. }
  20. }node[maxn];
  21. int find(int x)
  22. {
  23. if(x==father[x])
  24. return x;
  25. return father[x]=find(father[x]);
  26. }
  27. int main()
  28. {
  29. int n;
  30. scanf("%d",&n);
  31. for(int i=0;i<n;i++)
  32. father[i]=i;
  33. int m=0;
  34. int t;
  35. for(int i=1;i<=n;i++) {
  36. for (int j = 1; j <= n; j++) {
  37. scanf("%d", &t);
  38. node[m].u = i;
  39. node[m].v = j;
  40. node[m++].w = t;
  41. }
  42. }//加权值
  43. sort(node,node+m);//排序m条边
  44. int q;
  45. scanf("%d",&q);
  46. int x,y;
  47. for(int i=1;i<=q;i++)
  48. {
  49. scanf("%d%d",&x,&y);
  50. int xx=find(x);
  51. int yy=find(y);
  52. if(xx==yy)
  53. continue;
  54. else
  55. father[xx]=yy;//如果输入的不连通,则合并
  56. }
  57. int ans=0;
  58. for(int i=1;i<=m;i++)
  59. {
  60. int aa=find(node[i].u);
  61. int bb=find(node[i].v);
  62. if(aa!=bb)
  63. {
  64. ans+=node[i].w;
  65. father[aa]=bb;
  66. }//找每条路,如果不连通,则累加权值,并合并起来
  67. }
  68. printf("%d\n",ans);
  69. return 0;
  70. }

见注释

转载于:https://www.cnblogs.com/Vampire6/p/11273198.html

发表评论

表情:
评论列表 (有 0 条评论,214人围观)

还没有评论,来说两句吧...

相关阅读