#include using namespace std; using ll = long long; using P = pair; #define rep(i, n) for (int i = 0; i < (int)(n); i++) const ll inf = 1LL << 60; struct Edge { int to; ll w; Edge(int to, ll w) : to(to), w(w) {} }; struct Query { int a, b; ll w; Query(int a, int b, ll w) : a(a), b(b), w(w) {} }; using Graph = vector>; template bool chmin(T &a, T b) { if (a > b) { a = b; return true; } else return false; } template void print(vector v) { rep(i, v.size()) { cout << v[i] << " "; } cout << endl; return; } vector dijkstra(Graph G, int s, set

&S) { int N = G.size(); vector dist(N, inf); vector mindist(N, inf); vector seen(N, false); priority_queue, vector>, greater>> Q; Q.push({0, s * (N + 1)}); while (!Q.empty()) { ll u = Q.top().second; ll d = Q.top().first; int v, p; p = u % (N + 1); v = u / (N + 1); Q.pop(); if (seen[v]) continue; seen[v] = true; dist[v] = d; S.insert({v, p - 1}); S.insert({p - 1, v}); for (auto e : G[v]) { if (seen[e.to]) continue; ll newdist = dist[v] + e.w; if (newdist >= mindist[e.to]) continue; mindist[e.to] = newdist; Q.push({mindist[e.to], e.to * (N + 1) + v + 1}); } } return dist; } int main() { int T; cin >> T; int N, M; cin >> N >> M; vector E; Graph G(N); rep(i, M) { int u, v; ll w; cin >> u >> v >> w; u--; v--; E.push_back(Query(u, v, w)); G[u].push_back(Edge(v, w)); if (T == 0) G[v].push_back(Edge(u, w)); } ll ans = inf; if (T == 0) { ll temp = inf; rep(s, N) { set

S; vector D = dijkstra(G, s, S); for (auto q : E) { if (S.count({q.a, q.b})) continue; chmin(temp, D[q.a] + D[q.b] + q.w); } chmin(ans, temp); } } else { rep(s, N) { set

S; ll temp = inf; vector D = dijkstra(G, s, S); for (auto q : E) { if (q.b != s) continue; chmin(temp, D[q.a] + q.w); } chmin(ans, temp); } } if (ans != inf) cout << ans << endl; else cout << -1 << endl; return 0; }