Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. struct Edge {
  7. int weight;
  8. int from;
  9. int to;
  10. };
  11.  
  12. class CGraph {
  13. public:
  14. CGraph(int size) : rank(size, 0), cheapest(size, -1), size(size) {
  15. parent.resize(size);
  16. for (int i = 0; i < size; ++i) {
  17. parent[i] = i;
  18. }
  19. components_num = size;
  20. };
  21. ~CGraph() {};
  22. void add(Edge temp) {
  23. edges.push_back(temp);
  24. }
  25. int find_root(int vertex) {
  26. if (parent[vertex] == vertex) {
  27. return vertex;
  28. }
  29. return parent[vertex] = find_root(parent[vertex]);
  30. }
  31. void union_set(int a, int b) {
  32. a = find_root(a);
  33. b = find_root(b);
  34. if (a != b) {
  35. if (rank[a] < rank[b]) {
  36. swap(a, b);
  37. }
  38. parent[b] = a;
  39. if (rank[a] == rank[b]) {
  40. ++rank[a];
  41. }
  42. }
  43. }
  44.  
  45. int count_mst_weight() {
  46. while (components_num > 1) {
  47. for (int i = 0; i < edges.size(); ++i) {
  48. int pupa = find_root(edges[i].from);
  49. int lupa = find_root(edges[i].to);
  50.  
  51. if (pupa != lupa) { //вроде это должно работать но сэмпл выдает 5
  52. if (cheapest[pupa] == -1 || (edges[cheapest[pupa]].weight >= edges[i].weight && edges[cheapest[pupa]].to < cheapest[pupa])) {
  53. cheapest[pupa] = i;
  54. }
  55. if (cheapest[lupa] == -1 || (edges[cheapest[lupa]].weight >= edges[i].weight && edges[cheapest[lupa]].to < cheapest[lupa])) {
  56. cheapest[lupa] = i;
  57. }
  58. }
  59. }
  60. for (int i = 0; i < size; ++i) {
  61. if (cheapest[i] != -1) {
  62. int pupa = find_root(edges[cheapest[i]].from);
  63. int lupa = find_root(edges[cheapest[i]].to);
  64. if (pupa != lupa) {
  65. mst_weight += edges[cheapest[i]].weight;
  66. union_set(pupa, lupa);
  67. --components_num;
  68. }
  69. }
  70. }
  71. }
  72. return mst_weight;
  73. }
  74.  
  75.  
  76. private:
  77. vector<int> cheapest;
  78. vector<Edge> edges;
  79. vector<int> parent;
  80. vector<int> rank;
  81. int components_num;
  82. int size;
  83. int mst_weight = 0;
  84. };
  85.  
  86. int main() {
  87. int n, m;
  88. cin >> n >> m;
  89. CGraph graph(n);
  90. for (int i = 0; i < m; ++i) {
  91. Edge temp;
  92. cin >> temp.from >> temp.to >> temp.weight;
  93. --temp.from;
  94. --temp.to;
  95.  
  96. graph.add(temp);
  97. }
  98. cout << graph.count_mst_weight();
  99. system("pause");
  100.  
  101. return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement