Advertisement
prog3r

https://www.spoj.com/problems/PRIMIT/, ADD MINIMAL AMOUNT OF EDGES FOR EULER PATH

Mar 8th, 2025
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4.     ios::sync_with_stdio(0);
  5.     cin.tie(0);
  6.     int T;
  7.     cin >> T;
  8.     vector<int> component;
  9.     vector<pair<bool,bool>> comps;
  10.     component.reserve(1000);
  11.     comps.reserve(1000);
  12.     for (int tt = 0; tt < T; tt += 1) {
  13.         int m;
  14.         cin >> m;
  15.         vector<int> inDegree(1001), outDegree(1001);
  16.         vector<vector<int>> adj(1001);
  17.         for (int i = 0; i < m; ++i) {
  18.             int u, v;
  19.             cin >> u >> v;
  20.             outDegree[u]++;
  21.             inDegree[v]++;
  22.             adj[u].push_back(v);
  23.             adj[v].push_back(u);
  24.         }
  25.         auto in_og = inDegree, out_og = outDegree;
  26.         auto dfs = [&] (auto f, int u) -> void {
  27.             if (!inDegree[u] && !outDegree[u]) {
  28.                 return;
  29.             }
  30.             component.push_back(u);
  31.             inDegree[u] = 0;
  32.             outDegree[u] = 0;
  33.             for (const auto &v : adj[u]) {
  34.                 f(f, v);
  35.             }
  36.         };
  37.         int tot = 0;
  38.         comps.clear();
  39.         for (int i = 1; i <= 1000; i += 1) {
  40.             if (!inDegree[i] && !outDegree[i]) {
  41.                 continue;
  42.             }
  43.             component.clear();
  44.             dfs(dfs, i);
  45.             tot += 1;
  46.             bool need1 = false;
  47.             bool need2 = false;
  48.             for (const auto &x : component) {
  49.                 need1 |= in_og[x] > out_og[x];
  50.                 need2 |= in_og[x] < out_og[x];
  51.             }
  52.             comps.push_back({need1,need2});
  53.         }
  54.         int fix1 = 0;
  55.         int fix2 = 0;
  56.         for (int i = 0; i < comps.size(); i += 1) {
  57.             fix1 -= comps[i].first;
  58.             fix2 -= comps[i].second;
  59.         }
  60.         for (int i = 1; i <= 1000; i += 1) {
  61.             if (in_og[i] > out_og[i]) {
  62.                 fix1 += in_og[i] - out_og[i];
  63.             } else if (in_og[i] < out_og[i]) {
  64.                 fix2 += out_og[i] - in_og[i];
  65.             }
  66.         }
  67.         cout << m + 1 + tot - 1 + (fix1+fix2)/2 << "\n";
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement