#include using namespace std; typedef long long ll; template ostream& operator<< (ostream& os, const vector & v) { os << "[ "; for (const T & elem : v) { os < elem << " "; } os << " ]"; return os; } bool dfs(pair v, ll main_color, vector>> & pred, vector & visited_atleast_once, const vector>> & graph) { ll curr_v = v.first; ll curr_floor = v.second; visited_atleast_once[curr_v] = true; bool ret = false; for (const pair & neig : graph[curr_v]) { ll neig_vertex = neig.first; ll color = neig.second; if (curr_floor == 0) { if (pred[neig_vertex][0] == pair{curr_v, curr_floor}) continue; // protoze soused je predchudce if (color == main_color && pred[neig_vertex][0] == pair{-1, -1}) { pred[neig_vertex][0] = pair{curr_v, curr_floor}; ret |= dfs({neig_vertex, 0}, main_color, pred, visited_atleast_once, graph); pred[neig_vertex][0] = pair{-1, -1}; } else if (color != main_color) { // prechod do druheho patra if (pred[neig_vertex][0] != pair{-1, -1}) { return true; } pred[neig_vertex][1] = pair{curr_v, curr_floor}; ret |= dfs({neig_vertex, 1}, main_color, pred, visited_atleast_once, graph); pred[neig_vertex][1] = pair{-1, -1}; } } else { // curr_floor == 1 if (color != main_color) continue; // protoze muzu pouzivat jen main hrany if (pred[neig_vertex][1] == pair{curr_v, curr_floor}) continue; // protoze soused je predchudce if (pred[neig_vertex][0] != pair{-1, -1}) { return true; } if (pred[neig_vertex][1] == pair{-1, -1}) { pred[neig_vertex][1] = pair{curr_v, curr_floor}; ret |= dfs({neig_vertex, 1}, main_color, pred, visited_atleast_once, graph); pred[neig_vertex][1] = pair{-1, -1}; } // pred[neig_vertex][1] = pair{-1, -1} ###########################################################################################X } } return ret; } void test_case() { ll n, m; cin >> n >> m; vector>> graph(n); for (ll i = 0; i < m; ++i) { ll u, v, c; cin >> u >> v >> c; graph[u].push_back({v, c}); graph[v].push_back({u, c}); } // RED - 0 // BLUE - 1 vector>> pred(n, vector>(2, {-1, -1})); // pred[v][copy] vector visited_atleast_once(n, false); bool has_red_cycle_with_one_blue = false; for (ll i = 0; i < n; ++i) { if (!visited_atleast_once[i]) { visited_atleast_once[i] = true; pred[i][0] = pair{i, 0}; has_red_cycle_with_one_blue |= dfs({i, 0}, 0, pred, visited_atleast_once, graph); } } pred = vector>>(n, vector>(2, {-1, -1})); visited_atleast_once = vector(n, false); bool has_blue_cycle_with_one_red = false; for (ll i = 0; i < n; ++i) { if (!visited_atleast_once[i]) { visited_atleast_once[i] = true; pred[i][0] = pair{i, 0}; has_blue_cycle_with_one_red |= dfs({i, 0}, 1, pred, visited_atleast_once, graph); } } if (has_red_cycle_with_one_blue || has_blue_cycle_with_one_red) cout << "NO" << endl; else cout << "YES" << endl; } int main() { cin.tie(0); cout.tie(0); cin.exceptions(ios::failbit); ios::sync_with_stdio(false); ll t = 1; // cin >> t; // potential comment while (t--) { test_case(); } return 0; }