圖論-Dijkstra最短路

9102700發表於2024-05-24

驗板子的題:單源最短路


匆忙整理的板子,依稀記得大二下那次 vp 寫的巨抽象的最短路

點選檢視程式碼
int head[N], cnt = 0;
struct Edge{
    int from, to, nxt;
    ll val;
}e[N << 1];
void add(int u, int v, int w){
    e[++cnt].from = u;
    e[cnt].to = v;
    e[cnt].val = w;
    e[cnt].nxt = head[u];
    head[u] = cnt;
}

ll dis[N];
bool vis[N];

void dij(int s){
    for(int i = 1; i <= n; i++) dis[i] = inf, vis[i] = false;
    priority_queue<PII, vector<PII>, greater<PII> > heap;
    dis[s] = 0;
    heap.push({0LL, s});
    while(!heap.empty()){
        auto[x, u] = heap.top();
        heap.pop();
        if(vis[u]) continue;
        vis[u] = true;
        for(int i = head[u]; i != 0; i = e[i].nxt){
            int v = e[i].to;
            if(dis[v] > dis[u] + e[i].val){
                dis[v] = dis[u] + e[i].val;
                heap.push({dis[v], v});
            }
        }
    }
}

相關文章