#include #include #include #include using namespace std; int T, N, M; int U[2000], V[2000]; long long W[2000]; long long dijkstra(int src, int dst, int id) { vector>> G(N); for (int i = 0; i < M; ++i) if (i != id) { G[U[i]].push_back(make_pair(V[i], W[i])); if (T == 0) { G[V[i]].push_back(make_pair(U[i], W[i])); } } vector d(N, (long long)1e18); priority_queue> pq; pq.push(make_pair(0, src)); d[src] = 0; while (!pq.empty()) { auto p = pq.top(); auto cost = -p.first; auto u = p.second; pq.pop(); if (d[u] < cost) continue; for (auto e:G[u]) { int v = e.first; long long nd = d[u] + e.second; if (d[v] > nd) { d[v] = nd; pq.push(make_pair(-nd, v)); } } } return d[dst]; } main() { cin >> T >> N >> M; for (int i = 0; i < M; ++i) { cin >> U[i] >> V[i] >> W[i]; --U[i];--V[i]; } long long INF = 1e18; long long ans = INF; for (int i = 0; i < M; ++i) { ans = min(ans, dijkstra(V[i], U[i], i) + W[i]); } cout << (ans == INF ? -1 : ans )<< endl; }