#include <bits/stdc++.h>
using namespace std;
int n, m, a, b;
vector<pair<int, int> > ke[400009];
int d[400009][11];
bool marked[400009][11];
struct info {
int d;
int u;
int w;
info(int _d, int _u, int _w) : d(_d), u(_u), w(_w) {}
bool operator()(const info x) {
if (d < x.d) return true;
}
};
struct infoComparator {
bool operator()(const info& t1, const info& t2) {
return t1.d > t2.d;
}
};
main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v, w;
cin >> u >> v >> w;
// cout << u << " " << v << " " << w << endl;
ke[u].push_back({v + n, w});
ke[v].push_back({u + n, w});
ke[v + n].push_back({u, w});
ke[u + n].push_back({v, w});
d[u][w] = d[v][w] = d[v + n][w] = d[u + n][w] = INT_MAX;
}
priority_queue<info, vector<info>, infoComparator> pq;
pq.push({0, 1, 0});
int ans = INT_MAX;
while (pq.size()) {
auto top = pq.top();
pq.pop();
int u = top.u, w = top.w;
if (marked[u][w]) continue;
if (u == n) {
ans = top.d;
break;
}
marked[u][w] = true;
for (auto& [v, _w] : ke[u]) { // c(u,v) = w
if (marked[v][_w]) continue;
if (u <= n) {
if (d[v][_w] >= top.d) {
d[v][_w] = top.d;
pq.push({top.d, v, _w});
}
} else {
int cost = top.d + w * _w;
if (cost < d[v][_w]) {
d[v][_w] = cost;
pq.push({cost, v, _w});
}
}
}
}
cout << (ans < INT_MAX ? ans : -1) << endl;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbiwgbSwgYSwgYjsKdmVjdG9yPHBhaXI8aW50LCBpbnQ+ID4ga2VbNDAwMDA5XTsKaW50IGRbNDAwMDA5XVsxMV07CmJvb2wgbWFya2VkWzQwMDAwOV1bMTFdOwoKc3RydWN0IGluZm8gewogICAgaW50IGQ7CiAgICBpbnQgdTsKICAgIGludCB3OwogICAgaW5mbyhpbnQgX2QsIGludCBfdSwgaW50IF93KSA6IGQoX2QpL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gICAgaW50IHUgPSB0b3AudSwgdyA9IHRvcC53OwoKICAgICAgICBpZiAobWFya2VkW3VdW3ddKSBjb250aW51ZTsKCiAgICAgICAgaWYgKHUgPT0gbikgewogICAgICAgICAgICBhbnMgPSB0b3AuZDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQoKICAgICAgICBtYXJrZWRbdV1bd10gPSB0cnVlOwoKICAgICAgICBmb3IgKGF1dG8mIFt2LCBfd10gOiBrZVt1XSkgeyAgLy8gYyh1LHYpID0gdwogICAgICAgICAgICBpZiAobWFya2VkW3ZdW193XSkgY29udGludWU7CgogICAgICAgICAgICBpZiAodSA8PSBuKSB7CiAgICAgICAgICAgICAgICBpZiAoZFt2XVtfd10gPj0gdG9wLmQpIHsKICAgICAgICAgICAgICAgICAgICBkW3ZdW193XSA9IHRvcC5kOwogICAgICAgICAgICAgICAgICAgIHBxLnB1c2goe3RvcC5kLCB2LCBfd30pOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgaW50IGNvc3QgPSB0b3AuZCArIHcgKiBfdzsKICAgICAgICAgICAgICAgIGlmIChjb3N0IDwgZFt2XVtfd10pIHsKICAgICAgICAgICAgICAgICAgICBkW3ZdW193XSA9IGNvc3Q7CiAgICAgICAgICAgICAgICAgICAgcHEucHVzaCh7Y29zdCwgdiwgX3d9KTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgIH0KICAgIH0KCiAgICBjb3V0IDw8IChhbnMgPCBJTlRfTUFYID8gYW5zIDogLTEpIDw8IGVuZGw7Cn0=