单源最短路+正权图+稀疏图----->堆优化dijkstra
1 #include<iostream> 2 #include<vector> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 int n,m; 7 const int N=2e5; 8 int h[N],e[N],w[N],ne[N],idx; 9 bool st[N]; 10 int dis[N]; 11 typedef pair<int,int> PII; 12 void add(int a,int b,int c){ 13 e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++; 14 } 15 int dijkstra(){ 16 priority_queue<PII,vector<PII>,greater<PII>>heap; 17 memset(dis,0x3f,sizeof(dis)); 18 dis[1]=0; 19 heap.push({0,1});//必须是距离在前,不然就自己重写结构体 20 while(heap.size()){ 21 auto t=heap.top(); 22 heap.pop(); 23 int id=t.second; 24 int distance=t.first; 25 if(st[id]) continue; 26 st[id]=true; 27 for(int i=h[id];i!=-1;i=ne[i]){//松弛从id能到的每一个点 28 int j=e[i]; 29 if(dis[j]>dis[id]+w[i]){ 30 dis[j]=dis[id]+w[i]; 31 heap.push({dis[id]+w[i],j}); 32 } 33 } 34 } 35 if(dis[n]==0x3f3f3f3f) return -1; 36 return dis[n]; 37 } 38 int main(void){ 39 cin>>n>>m; 40 memset(h,-1,sizeof(h)); 41 for(int i=0;i<m;i++){ 42 int a,b,c; 43 cin>>a>>b>>c; 44 add(a,b,c); 45 } 46 cout<<dijkstra(); 47 return 0; 48 }