Dijkstra算法(模板+练习)

Dijkstra模板(矩阵)

int cost[maxn][maxn];
int d[maxn];
bool used[maxn];
int V;//顶点数量。

//求起点到各个顶点的最短距离 

void dijkstra(int s)
{
    fill(d,d+V,inf) ;
    fill(used,used,false);
    d[s] = 0;
    while(true)
    {
        int v = -1;
        for(int i=0;iif(!used[i] && (v == -1 || d[i] < d[v]))
                v = i;
        }
        if(v == -1)
            break;
        used[v] = true;

        for(int i=0;imin(d[i],d[v]+cost[v][i]);       
    }

}

Dijkstra算法模板(邻接表+堆优化)

struct edge{
    int to,cost;
}; 
typedef pair<int,int> P;//first是最短距离,second是顶点编号 
int V;
vector G[maxn];
int d[maxn];

void dijkstra(int s)
{
    //通过指定greater

参数,堆按照first从小到大的顺序取值 priority_queuevector

, greater

> q; fill(d,d+V,inf) ; d[s] = 0; q.push(P(0,s)); while(!q.empty()) { P p = q.top(); q.pop(); int v = p.second; if(d[v] < p.first) continue; for(int i=0;iif(d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; q.push(P(d[e.to],e.to)); } } } }

练习:https://www.luogu.org/problemnew/show/P3371

#include
#define inf 2147483647
using namespace std;
struct edge{
    int to,cost;
    edge(int a,int b):to(a),cost(b){};
};
typedef pair<int,int> P; 
int main()
{
    int n,m,s;
    cin>>n>>m>>s;
    vector G[n+1];
    int d[n+1];
    fill(d,d+n+1,inf);
    for(int i=0;iint a,b,c;
        cin>>a>>b>>c;
        G[a].push_back(edge(b,c));
    }
    priority_queuevector

,greater

> q; d[s] = 0; q.push(P(0,s)); while(!q.empty()) { P p = q.top(); q.pop(); int v = p.second; if(d[v] < p.first) continue; for(int i=0;i//遍历v的所有边。 { edge e = G[v][i]; if(d[e.to] > d[v] + e.cost){ d[e.to] = d[v] + e.cost; q.push(P(d[e.to],e.to)); } } } int first = 0; for(int i=1;i<=n;i++) { if(first) cout<<" "; cout<1; } cout<return 0; }

你可能感兴趣的:(Dijkstra算法)