【图论】单源点最短路模板(有向图)Dijkstra

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 500;
const int MAXM = 20000;
typedef pair<int, int> pii;
priority_queue<pii, vector<pii>, greater<pii> > que;
int dis[MAXN+10], Fa[MAXN+10];
bool vis[MAXN+10];
struct node{
    int v, w;
    node *next;
}Edges[MAXM*2+10], *ecnt=Edges, *adj[MAXN+10];
char ch;
void Read(int &u){
    while((ch = getchar()) , ch != EOF){
        if(ch >= '0' && ch <= '9'){
            u = ch - '0';
            while((ch = getchar()), ch >= '0' && ch <= '9')
                u = u * 10 + ch - '0';
            ungetc(ch, stdin);
            return;
        }
    }
}
void addedge(int u, int v, int w){
    ++ecnt;
    ecnt->v = v;
    ecnt->next = adj[u];
    ecnt->w = w;
    adj[u] = ecnt;
}
int main(){
    int n, m, u, v, w, s, t;
    Read(n); Read(m);
    for(int i=1;i<=m;i++){
        Read(u); Read(v); Read(w);
        addedge(v, u, w);
    }
    Read(s); Read(t);
    que.push(make_pair(0, t));
    memset(dis, 0x7f, sizeof dis);
    dis[t] = 0;
    pii tp;
    while(!que.empty()){
        tp = que.top(); que.pop();
        if(vis[tp.second]) continue;
        for(node *p=adj[tp.second];p;p=p->next){
            if(dis[p->v] > tp.first + p->w){
                dis[p->v] = tp.first + p->w;
                Fa[p->v] = tp.second;
                que.push(make_pair(dis[p->v], p->v));
            }else if(dis[p->v] == tp.first + p->w)
                Fa[p->v] = Fa[p->v] ? min(tp.second, Fa[p->v]) : tp.second;
        }
        vis[tp.second] = true;
    }
    printf("%d\n%d", dis[s], s);
    u = s;
    do{
        u = Fa[u];
        if(u > 0) printf(" %d", u);
    }while(u != t);

    return 0;
}

转载于:https://www.cnblogs.com/JeremyGJY/p/5921600.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值