matistjati

Untitled

Jul 9th, 2026
9
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 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.  
  12. pair<int, vi> hungarian(const vector<vi> &a) {
  13. if (a.empty()) return {0, {}};
  14. int n = sz(a) + 1, m = sz(a[0]) + 1;
  15. vi u(n), v(m), p(m), ans(n - 1);
  16. rep(i,1,n) {
  17. p[0] = i;
  18. int j0 = 0; // add "dummy" worker 0
  19. vi dist(m, INT_MAX), pre(m, -1);
  20. vector<bool> done(m + 1);
  21. do { // dijkstra
  22. done[j0] = true;
  23. int i0 = p[j0], j1, delta = INT_MAX;
  24. rep(j,1,m) if (!done[j]) {
  25. auto cur = a[i0 - 1][j - 1] - u[i0] - v[j];
  26. if (cur < dist[j]) dist[j] = cur, pre[j] = j0;
  27. if (dist[j] < delta) delta = dist[j], j1 = j;
  28. }
  29. rep(j,0,m) {
  30. if (done[j]) u[p[j]] += delta, v[j] -= delta;
  31. else dist[j] -= delta;
  32. }
  33. j0 = j1;
  34. } while (p[j0]);
  35. while (j0) { // update alternating path
  36. int j1 = pre[j0];
  37. p[j0] = p[j1], j0 = j1;
  38. }
  39. }
  40. rep(j,1,m) if (p[j]) ans[p[j] - 1] = j - 1;
  41. return {-v[0], ans}; // min cost
  42. }
  43.  
  44.  
  45. int main() {
  46. cin.tie(0)->sync_with_stdio(0);
  47. cin.exceptions(cin.failbit);
  48.  
  49. int n, m, k;
  50. cin >> m >> n >> k;
  51. bool swapped = 0;
  52. if (n < m) swap(n, m), swapped = 1;
  53. vector<vector<int>> cost(m, vector<int>(n, 0));
  54. rep(_, 0, k) {
  55. int i, j, p;
  56. cin >> i >> j >> p;
  57. i--; j--;
  58. if (!swapped) swap(i, j);
  59. cost[i][j] = -p;
  60. }
  61. auto [c, matching] = hungarian(cost);
  62. vector<pii> ans;
  63. rep(i, 0, sz(matching)) {
  64. pii p = pii(i, matching[i]);
  65. if (!swapped) swap(p.first, p.second);
  66. ans.emplace_back(p);
  67. }
  68. cout << -c << "\n";
  69. cout << sz(ans) << "\n";
  70. for (pii& e : ans) cout << e.first + 1 << " " << e.second + 1 << "\n";
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment