Dijkstra + 邻接表存图 + 优先队列优化

测试板子:https://www.luogu.org/problemnew/show/P3371

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
const int maxn = 1e6+10;
int dis[maxn];
int n,m,s;
typedef pair<int,int> P;
vector<P> E[maxn]; //邻接表寸土

void Djiskra(){
    memset(dis,INF,sizeof(dis));
    dis[s] = 0;
    priority_queue<P> que;  //优先队列优化
    que.push(P(0,s));  //这里的第一个数代表 后面的数到起点的距离
    while(!que.empty()){
        P p = que.top(); que.pop();
        int v = p.second;  //获取距离最短的点
        for(int i = 0;i < E[v].size();i++){  //邻接表遍历
            P e = E[v][i];
            if(dis[e.first] > dis[v] + e.second){
                dis[e.first] = dis[v] + e.second;
                que.push(P(-dis[e.first],e.first));  //这里由于优先队列默认由大到小排列,所以我存负数就可以由小到大
            }
        }
    }

    for(int i = 1;i <= n;i++)
        if(dis[i] == INF)
            cout << "2147483647" << " ";
        else
            cout << dis[i] << " ";
    cout << endl;
}

int main(){
    while(cin >> n >> m >> s){
        int x,y,z;
        for(int i = 0;i < m;i++){
            cin >> x >> y >> z;
            E[x].push_back(P(y,z));
        }
       Djiskra();
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值