#include typedef long long LL; const int N = 2e3 + 7; const LL INF = 0x3f3f3f3f3f3f3f3f; int n, m, pre[N]; LL dis[N]; std::vector> g[N]; void dijkstra(int r) { std::priority_queue, std::vector>, std::greater<>> q; memset(pre, 0, sizeof pre); memset(dis, 0x3f, sizeof dis); dis[r] = 0, q.push({0, r}); while(!q.empty()) { auto [d, u] = q.top(); q.pop(); if(d != dis[u]) continue; for(auto &&[v, w]: g[u]) if(dis[v] > d + w) { dis[v] = d + w; pre[v] = u; q.push({dis[v], v}); } } } void undir() { scanf("%d%d", &n, &m); for(int i = 1, x, y, z; i <= m; ++i) { scanf("%d%d%d", &x, &y, &z); g[x].emplace_back(y, z); g[y].emplace_back(x, z); } LL ans = INF; for(int r = 1; r <= n; ++r) { dijkstra(r); for(int u = 1; u <= n; ++u) for(auto &&[v, w]: g[u]) if(pre[u] != v && pre[v] != u) ans = std::min(ans, dis[u] + dis[v] + w); } printf("%lld\n", ans == INF ? -1 : ans); } void dir() { scanf("%d%d", &n, &m); for(int i = 1, x, y, z; i <= m; ++i) { scanf("%d%d%d", &x, &y, &z); g[x].emplace_back(y, z); } LL ans = INF; for(int r = 1; r <= n; ++r) { dijkstra(r); for(int u = 1; u <= n; ++u) for(auto &&[v, w]: g[u]) if(v == r) ans = std::min(ans, dis[u] + w); } printf("%lld\n", ans == INF ? -1 : ans); } int main() { int cas; scanf("%d", &cas); if(cas == 0) undir(); else dir(); return 0; }