cin >> n >> m; for (int i = 1; i <= m; ++i) { int x, y, z; cin >> x >> y >> z; if (!z) f[0].a[x][y] = 1; else g[0].a[x][y] = 1; } for (int i = 1; i <= 60; ++i) { f[i] = f[i - 1] * g[i - 1]; g[i] = g[i - 1] * f[i - 1]; } ll ans = 0; Matrix s; s.setone(); for (int i = 60; ~i; --i) { if ((s * f[i]).empty()) continue; s = s * f[i], swap(f, g), ans |= 1ll << i; } if (ans > 1e18) returncout << -1 << "\n", 0; cout << ans << "\n"; return0; }