#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; ll dist[2000]; constexpr ll inf = 1002003004005006007; 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); } ll ans = inf; rep(s, n) { for(auto [t, wt]: to[s]) { rep(i, n) dist[i] = inf; priority_queue, greater

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