1. 程式人生 > >Dijkstra 優先隊列優化

Dijkstra 優先隊列優化

void typedef ostream vector class tor pan size ==

技術分享
#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); } } } } }
1 技術分享
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));
            }
        }
    }
}
2

Dijkstra 優先隊列優化