#include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; const ll INF = 1e+15; typedef pair P; typedef pair Pii; struct edge{ int to; ll cost; }; int n, m; vector G[2000]; ll d[2000]; bool used[2000]; set prevv[2000]; ll ans = INF; void dijkstra(int s){ priority_queue, greater

> que; d[s] = 0; que.push(P(0, s)); while(!que.empty()){ P p = que.top();que.pop(); int v = p.second; used[v] = true; if(d[v] < p.first) continue; for(edge e : G[v]){ if(d[v] + e.cost < d[e.to]){ d[e.to] = d[v] + e.cost; que.push(P(d[e.to], e.to)); prevv[e.to].clear(); prevv[e.to].insert(v); }else if(d[v] + e.cost < d[e.to]){ prevv[e.to].insert(v); } if(used[e.to]){ if(prevv[v].size() == 1){ if(prevv[v].count(e.to) == 0)chmin(ans, d[v] + e.cost - d[e.to]); }else{ chmin(ans, d[v] + e.cost - d[e.to]); } } } } } void solve(){ for(int i = 0; i < n; i++) d[i] = INF; for(int i = 0; i < n; i++){ if(d[i] == INF) dijkstra(i); } if(ans == INF){ cout << -1 << endl; }else{ cout << ans << endl; } } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int t; cin >> t >> n >> m; for(int i = 0; i < m; i++){ int u, v; ll w; cin >> u >> v >> w; u--; v--; G[u].push_back((edge){v, w}); if(t == 0) G[v].push_back((edge){u, w}); } solve(); }