#include #include #include #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; using P = pair; constexpr int INF = 1001001001; constexpr int mod = 1000000007; // constexpr int mod = 998244353; template inline bool chmax(T& x, T y){ if(x < y){ x = y; return true; } return false; } template inline bool chmin(T& x, T y){ if(x > y){ x = y; return true; } return false; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int T, N, M; cin >> T >> N >> M; using edge = tuple; vector> graph(N); vector u(M), v(M), w(M); for(int i = 0; i < M; ++i){ cin >> u[i] >> v[i] >> w[i]; --u[i], --v[i]; graph[u[i]].emplace_back(v[i], w[i], i); if(T == 0) graph[v[i]].emplace_back(u[i], w[i], i); } constexpr ll inf = 1e+17; ll ans = inf; for(int ban = 0; ban < M; ++ban){ vector dist(N, inf); dist[v[ban]] = 0; using Data = pair; priority_queue, greater> que; que.emplace(0, v[ban]); while(!que.empty()){ auto [d, from] = que.top(); que.pop(); if(d > dist[from]) continue; for(auto [to, cost, id] : graph[from]){ if(id != ban && chmin(dist[to], dist[from] + cost)){ que.emplace(dist[to], to); } } } chmin(ans, dist[u[ban]] + w[ban]); } if(ans == inf) ans = -1; cout << ans << endl; return 0; }