Dijkstra 优先队列优化
#include <iostream> #include <queue> #include <vector> using namespace std; const int N=405; struct rec { int v,w; }; vector<rec> edge[N*N]; int n,st,ed; __int64 dis[N*N]; bool vis[N*N]; struct cmp { bool operator()(int a,int b) { return dis[a]>dis[b]; } }; void Dijkstra() { priority_queue<int,vector<int>,cmp> Q; // memset(dis,-1,sizeof(dis)); memset(vis,0,sizeof(vis)); int i,u,v; Q.push(st); dis[st]=0; while(!Q.empty()) { u=Q.top(); Q.pop(); vis[u]=0; if(u==ed) break; for(i=0;i<edge[u].size();i++) { v=edge[u][i].v; if(dis[v]==-1 || dis[v]>dis[u]+edge[u][i].w) { dis[v]=dis[u]+edge[u][i].w; if(!vis[v]) { vis[v]=1; Q.push(v); } } } } }
struct edge {int to,cost;}; typedef pair<int,int> P; //first是最短距离,second是顶点的编号 int V;//顶点个数 vector<edge> G[MAXV]; int d[MAXV]; void dijkstra(int s) { priority_queue<P,vector<P>,greater<P> > que; memset(d,INF,sizeof d); d[s] = 0; que.push(P(0,s)); //把起点推入队列 while(!que.empty()) { P p = que.top(); que.pop(); int v = p.second; //顶点的编号 if (d[v] < p.first) continue; for(int i = 0; i < G[v].size(); i++) { edge e = G[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.push(P(d[e.to],e.to)); } } } }