Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <stack>
  5. #include <cstring>
  6. #include <queue>
  7.  
  8. #define ll long long
  9. #define MAX(a,b) (a)>(b)?(a):(b)
  10. #define MIN(a,b) (a)>(b)?(b):(a)
  11. #define pll pair<ll, ll>
  12.  
  13. using namespace std;
  14.  
  15. typedef struct route {
  16. int u, v;
  17. ll cost;
  18.  
  19. route(int a, int b, ll c): u(a), v(b), cost(c){}
  20.  
  21. bool operator < (const route& a) const {
  22. return this->cost > a.cost;
  23. }
  24.  
  25. };
  26.  
  27. int N, M;
  28. char univ[1234];
  29. priority_queue<route, vector<route>, less<route>> G;
  30. int parent[1234], _rank[1234];
  31. bool vi[1234];
  32.  
  33. void init() {
  34. for (int i = 0; i <= N; i++) {
  35. parent[i] = i;
  36. _rank[i] = 0;
  37. }
  38. }
  39.  
  40. int find(int x) {
  41. if (parent[x] == x)
  42. return x;
  43. else {
  44. return parent[x] = find(parent[x]);
  45. }
  46. }
  47.  
  48. void unite(int a, int b) {
  49. a = find(a);
  50. b = find(b);
  51.  
  52. if (a == b) return;
  53.  
  54. if (_rank[a] < _rank[b]) {
  55. parent[b] = a;
  56. }
  57. else {
  58. parent[a] = b;
  59.  
  60. if (_rank[a] == _rank[b]) {
  61. _rank[a]++;
  62. }
  63. }
  64. }
  65.  
  66. int main(void)
  67. {
  68. cin >> N >> M;
  69.  
  70. ll ans = 0;
  71. init();
  72.  
  73. for (int i = 1; i <= N; i++)
  74. scanf(" %c ", &univ[i]);
  75.  
  76. for (int i = 0; i < M; i++) {
  77. int u, v, c;
  78. cin >> u >> v >> c;
  79. if (univ[u] != univ[v]) {
  80. G.push(route(u, v, c));
  81. }
  82. }
  83.  
  84. while (!G.empty()) {
  85. int u = G.top().u, v = G.top().v, c = G.top().cost;
  86. G.pop();
  87.  
  88. if (find(u) != find(v)) {
  89. unite(u, v);
  90. vi[u] = true;
  91. vi[v] = true;
  92. ans += c;
  93. }
  94. }
  95.  
  96. for (int i = 1; i <= N; i++) {
  97. if (vi[i] == false) {
  98. printf("-1\n");
  99. return 0;
  100. }
  101. }
  102.  
  103. printf("%lld\n", ans);
  104.  
  105.  
  106. return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement