#include #include #include #include using namespace std; #define int long long struct Edge { int to, idx, weight; }; tuple, vector> find_cycle2(int N, int M, vector>& G) { vector vis(N, 0), used(M, 0), par_v(N, -1), par_e(N, -1), potential(N, 0); for (int s = 0; s < N; ++s) { if (vis[s]) continue; vector> stack = {{s, -1, -1, 0}}; while (!stack.empty()) { auto [v, p, e, pot] = stack.back(); stack.pop_back(); if (e != -1 && used[e]) continue; if (vis[v] && pot != potential[v]) { par_v[v] = p; if (e != -1) par_e[v] = e; return {v, p, e, par_v, par_e}; } vis[v] = 1; potential[v] = pot; if (e != -1) { par_e[v] = e; used[e] = 1; } par_v[v] = p; for (const auto& [a, ne, w] : G[v]) { if (used[ne]) continue; stack.emplace_back(a, v, ne, pot + w); } } } return {-1, -1, -1, par_v, par_e}; } pair, vector> cycle_detection2(int N, int M, vector>& G) { auto [v, p, e, par_v, par_e] = find_cycle2(N, M, G); if (p == -1) { return {{}, {}}; } else { vector cycle_v = {p}; vector cycle_e = {e}; while (v != p) { e = par_e[p]; p = par_v[p]; cycle_v.push_back(p); cycle_e.push_back(e); } reverse(cycle_v.begin(), cycle_v.end()); reverse(cycle_e.begin(), cycle_e.end()); return {cycle_v, cycle_e}; } } int32_t main() { int n, m; cin >> n >> m; vector> g(n); vector> E; for (int i = 0; i < m; ++i) { int a, b, w; cin >> a >> b >> w; --a; --b; g[a].push_back({b, i, w}); g[b].push_back({a, i, -w}); E.emplace_back(a, b, w); } auto [cycle_v, cycle_e] = cycle_detection2(n, m, g); if (cycle_v.empty()) { cout << -1 << endl; } else { cout << cycle_v.size() << endl; int ans = 0, c = 0; for (int i : cycle_e) { if (get<0>(E[i]) == c) { ans += get<2>(E[i]); c = get<1>(E[i]); } else { ans -= get<2>(E[i]); c = get<0>(E[i]); } } if (ans > 0) { cout << cycle_v[0] + 1 << endl; for (int i : cycle_e) cout << i + 1 << " "; } else { cout << cycle_v[0] + 1 << endl; for (auto it = cycle_e.rbegin(); it != cycle_e.rend(); ++it) cout << *it + 1 << " "; } cout << endl; } return 0; }