#include using namespace std; #define rep(i,n) for(int i = 0; i < (n); ++i) #define rrep(i,n) for(int i = (n)-1; i >= 0; --i) #define chmax(a, b) a = max(a, b) #define chmin(a, b) a = min(a, b) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; int main() { ios::sync_with_stdio(false); cin.tie(0); int T, n, m; cin >> T >> n >> m; vector> to(n); rep(_, m) { int u, v, w; cin >> u >> v >> w; --u, --v; to[u].emplace_back(v, w); if (T == 0) to[v].emplace_back(u, w); } constexpr ll inf = 1002003004005006007; ll ans = inf; rep(s, n) { VI first_move(n); VL dist(n, inf); priority_queue, greater

> q; auto push = [&](int v, ll c) { if (c < dist[v]) { first_move[v] = false; dist[v] = c; q.emplace(c, v); } }; for(auto [v, w]: to[s]) { push(v, w); first_move[v] = true; } while(!q.empty()) { auto [c, u] = q.top(); q.pop(); if (c != dist[u]) continue; for(auto [v, w]: to[u]) { if (first_move[u] && v == s) continue; push(v, c + w); } } chmin(ans, dist[s]); } if (ans == inf) ans = -1; cout << ans << endl; }