首页 > 代码库 > Dijkstra + heap

Dijkstra + heap

用优先队列实现,和朴素Dijkstra差不多,核心思想没有改变。

模板:

struct node    
{
    int pos, dist;
    friend bool operator < (node a, node b)  // 定义优先级
    {
        return a.dist > b.dist;   // 小的先出
    }
};
int Dijkstra(int n,int start,int end)  // n个点,定义起点和终点
{
    bool visited[maxn];
    int pos;
    node tmp;
    tmp.pos = start;
    tmp.dist = 0;
    priority_queue<node> q;
    for(int i = 1; i <= n; i++)
    {
        visited[i] = 0;
        dist[i] = INF;
    }
    dist[start]= 0;
    q.push(tmp);   // 将起点插入队列
    while(!q.empty())
    {
        tmp = q.top();
        q.pop();
        pos = tmp.pos;
        if(tmp.dist == INF)  // 没有边直接返回
            return INF;
        if(visited[pos])
            continue;
        visited[pos] = 1;  
        for(int i = 1; i <= n; i++)
            if(!visited[i] && tmp.dist + map[pos][i] < dist[i])
            {
                dist[i] = tmp.dist + map[pos][i];
                node t; t.pos = i; t.dist = dist[i];
                q.push(t);       // 将更新后的边插入队列
            }
    }
    return dist[end];
}