#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 t, n, m; vector G[2000]; ll d[2000]; set prevv[2000]; ll ans = INF; void dijkstra(int s){ priority_queue, greater

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