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 54 55 56
| #include<bits/stdc++.h> using namespace std; const int maxn = 1e5; const int INF = 0x3f3f3f3f; struct Node{ int from,to,cost; Node(int a,int b,int c):from(a),to(b),cost(c){} }; vector<Node>Edges; vector<int>G[maxn]; int Dis[maxn]; int N,M,S,T; typedef pair<int,int> Pair; priority_queue<Pair,vector<Pair>,greater<Pair> >Q; inline void AddEdge(int x,int y,int z){ Edges.push_back(Node(x,y,z)); G[x].push_back(Edges.size()-1); } inline void Init(){ Edges.clear(); memset(Dis,INF,sizeof(Dis)); for(int i=0;i<N;G[i++].clear()); int x,y,z; while(M--){ scanf("%d%d%d",&x,&y,&z); AddEdge(x,y,z); AddEdge(y,x,z); } scanf("%d%d",&S,&T); Dis[S]=0; Q.push(Pair(0,S)); } inline void Dijkstra(){ int Now,Val,L; while(!Q.empty()){ Now=Q.top().second; Val=Q.top().first; Q.pop(); if(Dis[Now]<Val){continue;} L=G[Now].size(); for(int i=0;i<L;++i){ if(Dis[Edges[G[Now][i]].to]>Dis[Now]+Edges[G[Now][i]].cost){ Dis[Edges[G[Now][i]].to]=Dis[Now]+Edges[G[Now][i]].cost; Q.push(Pair(Dis[Edges[G[Now][i]].to],Edges[G[Now][i]].to)); } } } Dis[T]==INF?printf("-1n"):printf("%dn",Dis[T]); } int main(){ while(~scanf("%d%d",&N,&M)){ Init(); Dijkstra(); } return 0; }
|