#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; vector>> vec(2020); int u[2020], v[2020]; long long w[2020]; long long mi[2020]; int main() { bool t; cin >> t; int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { cin >> u[i] >> v[i] >> w[i]; if (!t) { vec[v[i]].emplace_back(make_pair(u[i], w[i])); } vec[u[i]].emplace_back(make_pair(v[i], w[i])); } long long ans = 10000000000000007; for (int i = 0; i < m; i++) { priority_queue,vector>,greater>> que; for (int j = 1; j <= n; j++) { mi[j] = 10000000000000007; } que.push(make_pair(0, v[i])); mi[v[i]] = 0; while (!que.empty()) { long long x = que.top().first; int y = que.top().second; que.pop(); for (int j = 0; j < vec[y].size(); j++) { if (y == v[i] && vec[y][j].first == u[i]) { continue; } if (y == u[i] && vec[y][j].first == v[i]) { continue; } if (mi[vec[y][j].first] > x + vec[y][j].second) { mi[vec[y][j].first] = x + vec[y][j].second; que.push(make_pair(x + vec[y][j].second, vec[y][j].first)); } } } if (ans > w[i] + mi[u[i]]) { ans = w[i] + mi[u[i]]; } } if (ans == 10000000000000007) { cout << -1 << endl; return 0; } cout << ans << endl; }