1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include<bits/stdc++.h> using namespace std;
typedef pair<int,int> pii;
const int N=1.5e5+5;
int n,m; int x,y,z;
int idk; int hd[N],ne[N],to[N],ed[N];
void merge(int u,int v,int x){ ed[++idk]=x; to[idk]=v; ne[idk]=hd[u]; hd[u]=idk; }
int dij(int be,int en){ int dis[N]; bool fns[N]={false}; memset(dis,0x3f,sizeof(dis)); priority_queue<pii, vector<pii>, greater<pii> > pq; dis[be]=0; pq.push({0,be}); while(!pq.empty()){ auto tp=pq.top();pq.pop(); int ds=tp.first,dt=tp.second; if(fns[dt])continue; fns[dt]=true; if(dt==en)break; for(int i=hd[dt];i;i=ne[i]){ if(dis[to[i]]>dis[dt]+ed[i]){ dis[to[i]]=dis[dt]+ed[i]; pq.push({dis[to[i]],to[i]}); } } } if(dis[en]==0x3f3f3f3f)return -1; else return dis[en]; }
int main(){ cin>>n>>m; while(m--){ cin>>x>>y>>z; merge(x,y,z); } cout<<dij(1,n); return 0; }
|