Cod sursa(job #2814997)

Utilizator cegaxEmanuel Soto Ortega cegax Data 8 decembrie 2021 22:42:08
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
using namespace std;
#define all(c) (c).begin(), (c).end()
#define rall(A) A.rbegin(),A.rend()
#define pb push_back 
#define dbg(x) do {cerr << #x <<" = " << (x) << endl; } while (false)
typedef long long ll;
typedef pair<ll, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
//cout << setprecision(12) << fixed;

const int maxn = 5e4+5;
const ll INF = (ll) 1e18;

int n, m; 
vector<ll> d;
vii adj[maxn];

void dijkstra(int s) {
    d.assign(n, INF);
    d[s] = 0;

    priority_queue<ii, vector<ii>, greater<ii>> q;
    q.push({0, s});

    while (!q.empty()) {
        int v = q.top().second;
        ll d_v = q.top().first;
        q.pop();
        if (d_v != d[v])
            continue;

        for (auto edge : adj[v]) {
            int to = edge.first;
            ll len = edge.second;

            if (d[v] + len < d[to]) {
                d[to] = d[v] + len;
                q.push({d[to], to});
            }
        }
    }
}


int main() {
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

    ifstream in; ofstream out;
    in.open("dijkstra.in");
    out.open("dijkstra.out");

    in >> n >> m;

    for(int i = 0; i < m; i++) {
        int a, b, w; in >> a >> b >> w;
        a--; b--;
        adj[a].pb({b, w});
        adj[b].pb({a, w});
    }
    
    dijkstra(0);

    for(int i = 1; i < n; i++) {
        if(d[i] == INF) out << 0 << " ";
        else out << d[i] << " ";
    }
    
    return 0;
}