数据结构实验之图论六:村村通公路

阳光穿透心脏的1/2处 2022-06-05 08:30 260阅读 0赞

数据结构实验之图论六:村村通公路
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description

当前农村公路建设正如火如荼的展开,某乡镇政府决定实现村村通公路,工程师现有各个村落之间的原始道路统计数据表,表中列出了各村之间可以建设公路的若干条道路的成本,你的任务是根据给出的数据表,求使得每个村都有公路连通所需要的最低成本。
Input

连续多组数据输入,每组数据包括村落数目N(N <= 1000)和可供选择的道路数目M(M <= 3000),随后M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个村庄的编号和修建该道路的预算成本,村庄从1~N编号。
Output

输出使每个村庄都有公路连通所需要的最低成本,如果输入数据不能使所有村庄畅通,则输出-1,表示有些村庄之间没有路连通。
Example Input

5 8
1 2 12
1 3 9
1 4 11
1 5 3
2 3 6
2 4 9
3 4 4
4 5 6
Example Output

19
Hint

Author

xam

  1. #include <iostream>
  2. #include <cstring>
  3. #include <queue>
  4. using namespace std;
  5. int const MAX = 10056;
  6. typedef struct
  7. {
  8. int u, v, c;
  9. } city;
  10. int sum;
  11. int num;
  12. int bin[MAX];
  13. int fd(int x)
  14. {
  15. if(x != bin[x])
  16. x = fd(bin[x]);
  17. return x;
  18. }
  19. int main()
  20. {
  21. int n, m;
  22. while(cin >> n >> m)
  23. {
  24. int flag = 1;
  25. city arr[MAX], t;
  26. sum = 0;
  27. num = 0;
  28. for(int i = 1; i <= n; i++)
  29. {
  30. bin[i] = i;
  31. }
  32. for(int i = 0; i < m; i++)
  33. {
  34. cin >> arr[i].u >> arr[i].v >> arr[i].c;
  35. }
  36. for(int i = 0; i < m - 1; i++)
  37. {
  38. for(int j = i + 1; j < m; j++)
  39. {
  40. if(arr[i].c > arr[j].c)
  41. {
  42. t = arr[i];
  43. arr[i] = arr[j];
  44. arr[j] = t;
  45. }
  46. }
  47. }
  48. for(int i = 0; i < m; i++)
  49. {
  50. int x = fd(arr[i].u);
  51. int y = fd(arr[i].v);
  52. if(x != y)
  53. {
  54. sum += arr[i].c;
  55. bin[y] = arr[i].u;
  56. num++;
  57. }
  58. if(num == n - 1)
  59. {
  60. flag = 0;
  61. break;
  62. }
  63. }
  64. if(flag)
  65. cout << -1 << endl;
  66. else cout << sum << endl;
  67. }
  68. return 0;
  69. }

发表评论

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

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

相关阅读