[kuangbin带你飞]专题六 最小生成树 B - Networking

﹏ヽ暗。殇╰゛Y 2023-08-17 15:40 229阅读 0赞

B - Networking

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

题目

您被分配设计广泛区域中某些点之间的网络连接。您将获得该区域中的一组点,以及可连接成对点的电缆的一组可能路线。对于两点之间的每条可能路线,您将获得连接该路线上的点所需的电缆长度。请注意,两个给定点之间可能存在许多可能的路径。假设给定的可能路线(直接或间接)连接该区域中的每两个点。
您的任务是为该区域设计网络,以便在每两个点之间存在连接(直接或间接)(即,所有点都是互连的,但不一定是通过直接电缆),并且总长度为用过的电缆很小。
输入
输入文件由许多数据集组成。每个数据集定义一个必需的网络。集合的第一行包含两个整数:第一行定义给定点的数量P,第二行定义点之间给定路径的数量R.以下R行定义了点之间的给定路线,每条线给出三个整数:前两个数字标识点,第三个给出路线的长度。数字用空格分隔。仅给出一个数字P = 0的数据集表示输入的结束。数据集用空行分隔。
最大点数为50.给定路线的最大长度为100.可能的路线数量不受限制。节点用1和P(含)之间的整数标识。两个点i和j之间的路线可以给出为i j或j i。
产量
对于每个数据集,在单独的行上打印一个数字,该行显示用于整个设计网络的电缆的总长度。
样本输入

  1. 1 0
  2. 2 3
  3. 1 2 37
  4. 2 1 17
  5. 1 2 68
  6. 3 7
  7. 1 2 19
  8. 2 3 11
  9. 3 1 7
  10. 1 3 5
  11. 2 3 89
  12. 3 1 91
  13. 1 2 32
  14. 5 7
  15. 1 2 5
  16. 2 3 7
  17. 2 4 8
  18. 4 5 11
  19. 3 5 10
  20. 1 5 6
  21. 4 2 12
  22. 0

样本输出

  1. 0
  2. 17
  3. 16
  4. 26

思路:求最小生成树

  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. using namespace std;
  11. typedef long long ll;
  12. const int maxn=2e5+10;
  13. struct Node{
  14. int from,to,value;
  15. bool operator<(const Node &other)const{
  16. return this->value<other.value;
  17. }
  18. }node[maxn];
  19. int father[maxn];
  20. int find(int x)
  21. {
  22. if(x==father[x])
  23. return x;
  24. return father[x]=find(father[x]);
  25. }
  26. int main()
  27. {
  28. int n,m;
  29. while(~scanf("%d%d",&n,&m))
  30. {
  31. int res=0,point=0;
  32. if(n==0)
  33. break;
  34. for(int i=0;i<=n;i++)
  35. father[i]=i;
  36. for(int i=0;i<m;i++)
  37. scanf("%d%d%d",&node[i].from,&node[i].to,&node[i].value);
  38. sort(node,node+m);
  39. for(int i=0;i<m;i++)
  40. {
  41. if(find(node[i].from)==find(node[i].to))
  42. continue;
  43. else
  44. {
  45. res+=node[i].value;
  46. father[find(node[i].from)]=find(node[i].to);
  47. point++;
  48. if(point==n-1)
  49. break;
  50. }
  51. }
  52. printf("%d\n",res);
  53. }
  54. return 0;
  55. }

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

发表评论

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

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

相关阅读