Advertisement
pb_jiang

CF1594D

Mar 23rd, 2025
363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. // Problem: D. The Number of Imposters
  2. // Contest: Codeforces - Codeforces Round 747 (Div. 2)
  3. // URL: https://codeforces.com/problemset/problem/1594/D
  4. // Memory Limit: 256 MB
  5. // Time Limit: 3000 ms
  6. //
  7. // Powered by CP Editor (https://cpeditor.org)
  8.  
  9. #include <assert.h>
  10. #include <bits/stdc++.h>
  11. using namespace std;
  12. #ifndef __DEBUG__
  13. #define dbg(...) 42
  14. #endif
  15. template <class T> using mpq = priority_queue<T, vector<T>, greater<T>>;
  16.  
  17. using ll = long long;
  18. using a2l = array<ll, 2>;
  19. using pll = pair<ll, ll>;
  20. using vl = vector<ll>;
  21.  
  22. void solve()
  23. {
  24.     ll n, m;
  25.     cin >> n >> m;
  26.     vl fa(n + 1), cf(n + 1), sc1(n + 1, 1), sc2(n + 1);
  27.     function<ll(ll)> ufind = [&](ll x) {
  28.         if (fa[x] == 0)
  29.             return x;
  30.         ll old = fa[x];
  31.         fa[x] = ufind(fa[x]);
  32.         cf[x] = (cf[x] + cf[old]) % 2;
  33.         return fa[x];
  34.     };
  35.     auto ujoin = [&](ll x, ll y, ll parity) -> bool {
  36.         auto px = ufind(x), py = ufind(y);
  37.         if (px == py)
  38.             return (cf[x] + parity) % 2 == cf[y];
  39.         ll nc = (parity + cf[y] - cf[x] + 2) % 2;
  40.         cf[py] = nc, fa[py] = px;
  41.         if (nc)
  42.             sc1[px] += sc2[py], sc2[px] += sc1[py];
  43.         else
  44.             sc1[px] += sc1[py], sc2[px] += sc2[py];
  45.         return true;
  46.     };
  47.     bool valid = true;
  48.     for (ll i = 0, a, b; i < m; ++i) {
  49.         string op;
  50.         cin >> a >> b >> op;
  51.         if (op[0] == 'i') {
  52.             valid = valid && ujoin(a, b, 1);
  53.         } else {
  54.             assert(op[0] == 'c');
  55.             valid = valid && ujoin(a, b, 0);
  56.         }
  57.     }
  58.     if (!valid) {
  59.         cout << -1 << '\n';
  60.         return;
  61.     }
  62.  
  63.     ll v = 0;
  64.     for (ll i = 1; i <= n; ++i)
  65.         if (ufind(i) == i)
  66.             v += max(sc1[i], sc2[i]);
  67.     cout << v << '\n';
  68. }
  69.  
  70. int main(int argc, char **argv)
  71. {
  72.     ll t;
  73.     cin >> t;
  74.     while (t--)
  75.         solve();
  76.     return 0;
  77. };
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement