#include #pragma GCC optimize("Ofast") #define _GLIBCXX_DEBUG using namespace std; using std::cout; using std::cin; using std::endl; using ll=long long; using ld=long double; ll ILL=1167167167167167167; const int INF=2100000000; const ll mod=1e9+7; #define rep(i,a) for (ll i=0;i using _pq = priority_queue, greater>; template ll LB(vector &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();} template ll UB(vector &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();} template bool chmin(T &a,const T &b){if(a>b){a=b;return 1;}else return 0;} template bool chmax(T &a,const T &b){if(a void So(vector &v) {sort(v.begin(),v.end());} template void Sore(vector &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});} void yneos(bool a){if(a) cout<<"YES\n"; else cout<<"NO\n";} using len_type=ll; struct edge{ int to; len_type length; }; len_type dijkstra_movement(edge e,int from,len_type t){ return t+e.length+1; } vector dijkstra(vector> &G,int start,len_type inf){ int M=G.size(); assert(M>start&&start>=0); vector seen(M,inf); seen[start]=0; priority_queue,vector>,greater>> pq; pq.push({0,start}); while(!pq.empty()){ len_type time; int ver; tie(time,ver)=pq.top(); pq.pop(); if(seen[ver]>t; rep(i,t) solve(); } void solve(){ int N,M; cin>>N>>M; vector> G(N*N*2); map m; rep(i,M){ int h,w,c; cin>>h>>w>>c; h--,w--; m[h*N+w]=c; } vector dx={0,0,1,-1},dy={1,-1,0,0}; rep(i,N) rep(j,N){ int A=i*N+j; rep(k,4){ int s=dx[k]+i,t=dy[k]+j; if(min(s,t)==-1||max(s,t)==N) continue; int B=s*N+t; G[A].push_back({B,m[B]}); G[A+N*N].push_back({B+N*N,m[B]}); G[A].push_back({B+N*N,0}); } } auto seen=dijkstra(G,0,ILL); cout<