Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <assert.h>
- #include <bits/stdc++.h>
- using namespace std;
- #ifndef __DEBUG__
- #define dbg(...) 42
- #endif
- template <class T> using mpq = priority_queue<T, vector<T>, greater<T>>;
- using ll = long long;
- using pii = pair<int, int>;
- using pll = pair<ll, ll>;
- using vl = vector<ll>;
- using vi = vector<int>;
- using a3l = array<ll, 3>;
- void solve()
- {
- int n, m;
- cin >> n >> m;
- vl fa(n + 1), offset(n + 1);
- function<pll(ll)> find = [&](ll x) {
- if (fa[x] == 0)
- return pll{x, 0};
- auto [p, dist] = find(fa[x]);
- fa[x] = p, offset[x] += dist;
- return pll{fa[x], offset[x]};
- };
- auto insert = [&](ll x, ll y, ll dist) {
- auto [px, dx] = find(x);
- auto [py, dy] = find(y);
- if (px == py)
- return;
- fa[py] = px;
- // offset[py] += dx;
- // offset[py] = offset[px] - dx - dist + dy;
- // offset[py] = -offset[px] + dx + dist - dy;
- // offset[py] = dist - dx + dy;
- offset[py] = dist + dx - dy;
- };
- auto query = [&](ll x, ll y, ll d) {
- auto [px, dx] = find(x);
- auto [py, dy] = find(y);
- if (px != py)
- return true;
- // return dx == dy + d;
- // return dx + d == dy;
- return dy - dx == d;
- };
- vector<a3l> conds(m);
- for (auto &c : conds) {
- cin >> c[0] >> c[1] >> c[2];
- if (c[0] > c[1]) {
- swap(c[0], c[1]);
- c[2] = -c[2];
- }
- }
- for (const auto &c : conds) {
- auto [a, b, d] = c;
- if (!query(a, b, d)) {
- cout << "NO" << endl;
- return;
- }
- insert(a, b, d);
- auto [fa, da] = find(a);
- auto [fb, db] = find(b);
- // assert(db - da == d);
- // assert(da - db == d);
- assert(db - da == d);
- }
- cout << "YES" << endl;
- }
- int main(int argc, char **argv)
- {
- int t;
- cin >> t;
- while (t--) {
- solve();
- }
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement