dijkstra 模板

dijkstra解决无负权边的图的最短路,有向无向都可以,密集图无需优先队列优化,直接利用d数组遍历找最小值即可。

const int INF = 0x3fffffff;

struct Edge{
    int to, cost;
    Edge(int nto, int ncost) : to(nto),cost(ncost){}
    Edge(){};
    bool operator < (const Edge& rhs) const{
        return cost > rhs.cost;
    }
};

vector<vector<Edge> > G;
priority_queue<Edge> pq;
int d[30010], n;
//d保存着每个点到源点的最短距离。

int dijkstra(int head, int tail){
    while(!pq.empty())
        pq.pop();
    fill(d+1, d+n+1, INF);
    pq.push(Edge(head, 0));
    d[head] = 0;

    Edge t;
    while(!pq.empty()){
        t = pq.top();  pq.pop();
        if(t.to == tail)
            break;
        if(d[t.to] < t.cost)//判断t是否已经有近的路或者已经访问过
            continue;
        for(int i = 0; i < G[t.to].size(); ++i){
            Edge e = G[t.to][i];
            if(d[e.to] > t.cost + e.cost) {//只将需要更新的节点加入队列
                d[e.to] = t.cost + e.cost;
                pq.push(Edge(e.to, d[e.to]));
            }
        }
    }
    return t.cost;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值