Dijkstra单源最短路径算法; 优先队列+静态数组邻接表; STL优先队列还是没想明白排序原则;

#include <iostream> #include <queue> using namespace std; const int MAXN =1000000; int u[MAXN]; int v[MAXN]; int w[MAXN]; int d[MAXN]; int first[MAXN]; int next[MAXN]; bool done[MAXN]; typedef pair<int,int> pii; priority_queue<pii,vector<pii>,greater<pii> > q; int n,m; void Dijkstra() { memset(done,0,sizeof(done)); for(int i=0;i<n;++i) { d[i]=MAXN; } d[0]=0; q.push(make_pair(d[0],0)); while(!q.empty()) { pii u=q.top(); q.pop(); int x=u.second; if(done[x]) { continue; } done[x]=true; for(int e=first[x];e!=-1;e=next[e]) { if(d[v[e]]>d[x]+w[e]) { d[v[e]]=d[x]+w[e]; q.push(make_pair(d[v[e]],v[e])); } } } } int main() { //输入边,构造出邻接表 memset(first,-1,sizeof(first)); cin>>n>>m; for(int i=0,j=0;i<m;++i) { int a,b,c; cin>>a>>b>>c; u[j]=a; v[j]=b; w[j]=c; next[j]=first[u[j]]; first[u[j]]=j; ++j; u[j]=b; v[j]=a; w[j]=c; next[j]=first[u[j]]; first[u[j]]=j; ++j; } Dijkstra(); for(int j=0;j<n;++j) { cout<<j<<","<<d[j]<<endl; } return 0; }

 

 

貌似像是SPFA.

你可能感兴趣的:(算法,include,IM,pair)