#include <bits/stdc++.h> using namespace std; typedef long long ll; using P = pair<ll, int>; const ll INF = 10000000000000; int main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); int t; cin >> t; int n, m; cin >> n >> m; vector<vector<P>> adj(n); for (int z = 0; z < m; ++z) { int u, v; ll w; cin >> u >> v >> w; u--; v--; adj[u].push_back(P(w, v)); if (t == 0) adj[v].push_back(P(w, u)); } ll ans = INF; for (int x = 0; x < n; ++x) { vector<ll> dist(n, INF); vector<int> prev(n, -1); dist[x] = 0; priority_queue<P, vector<P>, greater<P>> q; q.push(P(0ll, x)); while (!q.empty()) { P z = q.top(); q.pop(); ll c0 = z.first; int i = z.second; for (P y : adj[i]) { ll c1 = y.first; int j = y.second; if (t == 0 and prev[i] == j) continue; if (dist[j] > c0 + c1) { prev[j] = i; dist[j] = c0 + c1; q.push(P(c0 + c1, j)); } else if (t == 0 or j == x) { ans = min(ans, c0 + dist[j] + c1); } } } } cout << (ans < INF ? ans : -1) << endl; return 0; }