#include using namespace std; //* ATCODER #include using namespace atcoder; typedef modint998244353 mint; //*/ /* BOOST MULTIPRECISION #include using namespace boost::multiprecision; //*/ typedef long long ll; #define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++) #define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--) template bool chmin(T &a, const T &b) { if (a <= b) return false; a = b; return true; } template bool chmax(T &a, const T &b) { if (a >= b) return false; a = b; return true; } template T max(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]); return ret; } template T min(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]); return ret; } template T sum(vector &a){ T ret = 0; for (int i=0; i<(int)a.size(); i++) ret += a[i]; return ret; } ll floor_sqrt(ll n){ ll ub = 3e9 + 30; ll lb = 0; while(ub - lb > 1){ ll t = (ub + lb) / 2; if (t * t <= n){ lb = t; }else{ ub = t; } } return lb; } //defmodfact const int COMinitMAX = 992844; mint fact[COMinitMAX+1], factinv[COMinitMAX+1]; void modfact(){ fact[0] = 1; for (int i=1; i<=COMinitMAX; i++){ fact[i] = fact[i-1] * i; } factinv[COMinitMAX] = fact[COMinitMAX].inv(); for (int i=COMinitMAX-1; i>=0; i--){ factinv[i] = factinv[i+1] * (i+1); } } mint cmb(int a, int b){ if (a> n >> m; vector ikeru(n, vector>(0)); rep(i,0,m){ int u, v; ll w; cin >> u >> v >> w; u--; v--; ikeru[u].push_back(pair(v, w)); } int k; cin >> k; vector a(k), b(k), c(k); map,int> mp; vector bs(n, vector(0)); set> dame; rep(i,0,k){ cin >> a[i] >> b[i] >> c[i]; a[i]--; b[i]--; c[i]--; if (mp.find(pair(a[i], b[i])) == mp.end()){ mp[pair(a[i], b[i])] = (int)mp.size(); bs[b[i]].push_back(a[i]); } dame.insert(make_tuple(a[i], b[i], c[i])); } int l = mp.size(); vector d(n,1e18); vector dk(l,1e18); d[0] = 0; rep(i,0,n){ vector> ds; ds.push_back(pair(d[i], -1)); map> am; rep(j,0,(int)bs[i].size()){ ds.push_back(pair(dk[mp[pair(bs[i][j], i)]], bs[i][j])); } sort(ds.begin(), ds.end()); for(auto[j,w]:ikeru[i]){ rep(x,0,(int)ds.size()){ if (ds[x].second == -1 || dame.find(make_tuple(ds[x].second, i, j)) == dame.end()){ if(mp.find(pair(i, j))==mp.end()){ chmin(d[j], w+ds[x].first); }else{ chmin(dk[mp[pair(i, j)]], w+ds[x].first); } break; } } } } if (d[n-1] == 1e18){ cout << -1 << '\n'; }else{ cout << d[n-1] << '\n'; } }