Advertisement
pb_jiang

CF1850H AC

Jul 23rd, 2023
950
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <assert.h>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. #ifndef __DEBUG__
  5. #define dbg(...) 42
  6. #endif
  7. template <class T> using mpq = priority_queue<T, vector<T>, greater<T>>;
  8.  
  9. using ll = long long;
  10. using pii = pair<int, int>;
  11. using pll = pair<ll, ll>;
  12. using vl = vector<ll>;
  13. using vi = vector<int>;
  14. using a3l = array<ll, 3>;
  15.  
  16. void solve()
  17. {
  18.     int n, m;
  19.     cin >> n >> m;
  20.  
  21.     vl fa(n + 1), offset(n + 1);
  22.     function<pll(ll)> find = [&](ll x) {
  23.         if (fa[x] == 0)
  24.             return pll{x, 0};
  25.         auto [p, dist] = find(fa[x]);
  26.         fa[x] = p, offset[x] += dist;
  27.         return pll{fa[x], offset[x]};
  28.     };
  29.     auto insert = [&](ll x, ll y, ll dist) {
  30.         auto [px, dx] = find(x);
  31.         auto [py, dy] = find(y);
  32.         if (px == py)
  33.             return;
  34.         fa[py] = px;
  35.  
  36.         // offset[py] += dx;
  37.         // offset[py] = offset[px] - dx - dist + dy;
  38.         // offset[py] = -offset[px] + dx + dist - dy;
  39.         // offset[py] = dist - dx + dy;
  40.         offset[py] = dist + dx - dy;
  41.     };
  42.     auto query = [&](ll x, ll y, ll d) {
  43.         auto [px, dx] = find(x);
  44.         auto [py, dy] = find(y);
  45.         if (px != py)
  46.             return true;
  47.         // return dx == dy + d;
  48.         // return dx + d == dy;
  49.         return dy - dx == d;
  50.     };
  51.  
  52.     vector<a3l> conds(m);
  53.     for (auto &c : conds) {
  54.         cin >> c[0] >> c[1] >> c[2];
  55.         if (c[0] > c[1]) {
  56.             swap(c[0], c[1]);
  57.             c[2] = -c[2];
  58.         }
  59.     }
  60.     for (const auto &c : conds) {
  61.         auto [a, b, d] = c;
  62.         if (!query(a, b, d)) {
  63.             cout << "NO" << endl;
  64.             return;
  65.         }
  66.         insert(a, b, d);
  67.         auto [fa, da] = find(a);
  68.         auto [fb, db] = find(b);
  69.         // assert(db - da == d);
  70.         // assert(da - db == d);
  71.         assert(db - da == d);
  72.     }
  73.  
  74.     cout << "YES" << endl;
  75. }
  76.  
  77. int main(int argc, char **argv)
  78. {
  79.     int t;
  80.     cin >> t;
  81.     while (t--) {
  82.         solve();
  83.     }
  84.     return 0;
  85. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement