/* -*- coding: utf-8 -*- * * 2277.cc: No.2277 Honest or Dishonest ? - yukicoder */ #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 100000; const int MAX_QN = 100000; const int MOD = 998244353; /* typedef */ typedef long long ll; typedef vector vi; typedef queue qi; typedef pair pii; typedef vector vpii; typedef vector vb; typedef vector vvi; typedef stack si; struct UFT { vector links, ranks, sizes; UFT() {} void init(int n) { links.resize(n); for (int i = 0; i < n; i++) links[i] = i; ranks.assign(n, 1); sizes.assign(n, 1); } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; /* global variables */ vpii nbrs[MAX_N]; int gids[MAX_N], ds[MAX_N]; UFT uft; /* subroutines */ void scc_visit(const vpii *nbrs, int v, vvi& scc, si& S, vb &inS, vi& low, vi& num, int& time) { low[v] = num[v] = ++time; S.push(v); inS[v] = true; for (const auto [w, c]: nbrs[v]) { if (num[w] == 0) { scc_visit(nbrs, w, scc, S, inS, low, num, time); low[v] = min(low[v], low[w]); } else if (inS[w]) low[v] = min(low[v], num[w]); } if (low[v] == num[v]) { scc.push_back(vi()); for (;;) { int w = S.top(); S.pop(); inS[w] = false; scc.back().push_back(w); if (v == w) break; } } } void calc_scc(const int n, const vpii nbrs[], vvi& scc) { vi num(n), low(n); si S; vb inS(n); int time = 0; for (int u = 0; u < n; u++) if (num[u] == 0) scc_visit(nbrs, u, scc, S, inS, low, num, time); } /* main */ int main() { int n, qn; scanf("%d%d", &n, &qn); for (int i = 0; i < qn; i++) { int ai, bi, ci; scanf("%d%d%d", &ai, &bi, &ci); ai--, bi--; nbrs[bi].push_back({ai, ci}); } vvi scc; calc_scc(n, nbrs, scc); int m = scc.size(); for (int i = 0; i < m; i++) for (auto u: scc[i]) gids[u] = i; fill(ds, ds + n, -1); for (int st = 0; st < n; st++) if (ds[st] < 0) { ds[st] = 0; qi q; q.push(st); while (! q.empty()) { int u = q.front(); q.pop(); int gu = gids[u]; for (auto [v, c]: nbrs[u]) if (gids[v] == gu) { if (ds[v] < 0) { ds[v] = ds[u] ^ c; q.push(v); } else if (ds[v] != (ds[u] ^ c)) { puts("0"); return 0; } } } } uft.init(m); for (int u = 0; u < n; u++) for (auto [v, c]: nbrs[u]) { int gu = gids[u], gv = gids[v]; if (gu != gv) uft.merge(gu, gv); } int ans = 1; for (int u = 0; u < n; u++) if (u == uft.root(u)) ans = (ll)ans * 2 % MOD; printf("%d\n", ans); return 0; }