#pragma GCC target ("avx2") // #pragma GCC optimization ("O3") #pragma GCC optimization ("unroll-loops") #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // #include using namespace std; using ll=long long; template using V = vector; template using P = pair; using vll = V; using vii = V; using vvll = V; using vvii = V< V >; using PII = P; using PLL = P; #define RevREP(i,n,a) for(ll i=n;i>a;i--) // (a,n] #define REP(i,a,n) for(ll i=a;i inline bool chmax(T& a, T b) {if (a < b) { a=b; return true; } return false; } template < class T > inline bool chmin(T& a, T b) {if (a > b) { a=b; return true; } return false; } #define DEBUG_VLL(vec) for(int sz=0;sz; int main() { cin.tie(0); ios::sync_with_stdio(false); int t, n, m; cin >> t >> n >> m; V< V > edges(n); rep(i, m) { int u, v, w; cin >> u >> v >> w; u--, v--; edges[u].eb(PII(v, w)); if (t == 0) edges[v].eb(PII(u, w)); } ll ans = HIGHINF; rep(i, n) { for (PII to: edges[i]) { auto [ton, tow] = to; vll dist(n, HIGHINF); priority_queue pq; pq.push(PLI(0, ton)); while (pq.size() > 0) { PLI q = pq.top(); pq.pop(); if (dist[q.second] < -q.first) continue; dist[q.second] = -q.first; for (PII e: edges[q.second]) { if (dist[e.first] < ll(-q.first) + e.second) continue; if ((q.second == i and e.first == ton) or (t == 0 and q.second == ton and e.first == i)) continue; pq.push(PLI(-(ll(-q.first) + e.second), e.first)); } } if (dist[i] < HIGHINF) chmin(ans, dist[i] + tow); } } if (ans == HIGHINF) ans = -1; cout << ans << '\n'; return 0; }