matistjati

Untitled

Jul 9th, 2026
6
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define rep(i, a, b) for(int i = a; i < (b); ++i)
  5. #define all(x) begin(x), end(x)
  6. #define sz(x) (int)(x).size()
  7. typedef long long ll;
  8. typedef pair<int, int> pii;
  9. typedef vector<int> vi;
  10.  
  11. template <typename T> pair<T, vector<int>>
  12. weighted_matching(vector<vector<T>> &C) {
  13. int i = sz(C), m = sz(C[0]), c, j, s, r;
  14. vector<T> dist(m), potential(m);
  15. vi row_match(i), col_match(m, -1), cols(m), prev(m);
  16. T d, nd, cost = 0;
  17. for (; i--;) {
  18. rep(c, 0, m) dist[c] = C[i][c], cols[c] = c, prev[c] = i;
  19. for (s = 0;;) {
  20. for (j = s; j < m; j++) if (c = cols[j],
  21. nd = dist[c] - potential[c], j == s || d > nd)
  22. d = nd, swap(cols[s], cols[j]);
  23. if (!~(r = col_match[c = cols[s++]])) break;
  24. rep(j, 0, m) if (dist[j] > (nd = C[r][j] - C[r][c] +
  25. dist[c])) dist[j] = nd, prev[j] = r;
  26. }
  27. for (cost += dist[c]; s--;) j = cols[s],
  28. potential[j] = dist[j] - d;
  29. for (; r != i; swap(c, row_match[r]))
  30. r = col_match[c] = prev[c];
  31. }
  32. return {cost, row_match};
  33. }
  34.  
  35. int main() {
  36. cin.tie(0)->sync_with_stdio(0);
  37. cin.exceptions(cin.failbit);
  38.  
  39. int n, m, k;
  40. cin >> m >> n >> k;
  41. bool swapped = 0;
  42. if (n < m) swap(n, m), swapped = 1;
  43. vector<vector<int>> cost(m, vector<int>(n, 0));
  44. rep(_, 0, k) {
  45. int i, j, p;
  46. cin >> i >> j >> p;
  47. i--; j--;
  48. if (!swapped) swap(i, j);
  49. cost[i][j] = -p;
  50. }
  51. auto [c, matching] = weighted_matching(cost);
  52. vector<pii> ans;
  53. rep(i, 0, sz(matching)) {
  54. pii p = pii(i, matching[i]);
  55. if (!swapped) swap(p.first, p.second);
  56. ans.emplace_back(p);
  57. }
  58. cout << -c << "\n";
  59. cout << sz(ans) << "\n";
  60. for (pii& e : ans) cout << e.first + 1 << " " << e.second + 1 << "\n";
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment