#include using namespace std; #define rep2(i, m, n) for (int i = (m); i < (n); ++i) #define rep(i, n) rep2(i, 0, n) using ll = long long; template inline bool chmin(T &a, const T b) { if (a > b) { a = b; return true; } return false; } template istream &operator>>(istream &is, array &v) { for (auto &e : v) is >> e; return is; } template istream &operator>>(istream &is, vector &v) { for (auto &e : v) is >> e; return is; } struct fast_ios { fast_ios(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_; const ll INFll = (1ll<<60) - 1; template struct edge { int v; T w; edge(int v, T w) : v(v), w(w) {} }; template using Graph = vector>>; template vector dijkstra(const Graph &G, int s) { int n = G.size(); const auto INF_T = numeric_limits::max() / 2 - 1; vector dist(n, INF_T); using PTi = pair; priority_queue, function> pq( [] (auto x, auto y) { return x.first > y.first; } ); dist[s] = 0; pq.emplace(dist[s], s); while (!pq.empty()) { auto [d, u] = pq.top(); pq.pop(); if (dist[u] < d) continue; for (auto &[v, w] : G[u]) if (chmin(dist[v], d + w)) pq.emplace(dist[v], v); } return dist; } int main() { int T, n, m; cin >> T >> n >> m; vector> E(m); cin >> E; for (auto &[u, v, w] : E) --u, --v; ll ans = INFll; rep(i, m) { Graph G(n); int s = -1, t = -1, wst = -1; rep(j, m) { auto [u, v, w] = E[j]; if (j == i) { s = v, t = u, wst = w; continue; } G[u].emplace_back(v, w); if (T == 0) G[v].emplace_back(u, w); } auto dist = dijkstra(G, s); chmin(ans, dist[t] + wst); } if (ans == INFll) ans = -1; cout << ans << '\n'; }