#include #include #include using namespace std; int main() { int t, n, m; cin >> t >> n >> m; vector > adj[n]; int weight[m]; for (int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; u--; v--; adj[u].emplace_back(v, i); if (t == 0) adj[v].emplace_back(u, i); weight[i] = w; } long long ans = 1LL<<60; for (int u = 0; u < n; u++) for (auto [v, i] : adj[u]) { vector dist(n, 1LL<<60); priority_queue > pq; dist[v] = 0; pq.push({0, v}); while (!pq.empty()) { long long d = -pq.top().first; int x = pq.top().second; pq.pop(); if (d > dist[x]) continue; for (auto [y, j] : adj[x]) { if (j == i) continue; if (dist[y] <= dist[x] + weight[j]) continue; dist[y] = dist[x] + weight[j]; pq.push({-dist[y], y}); } } ans = min(ans, dist[u] + weight[i]); } cout << (ans < 1LL<<60 ? ans : -1) << endl; }