Cod sursa(job #2969933)

Utilizator sandry24Grosu Alexandru sandry24 Data 23 ianuarie 2023 21:44:50
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pb push_back
#define mp make_pair
#define f first
#define s second

int n, m;
vector<vector<pi>> adj(100001);
vector<int> parent(100001);
vector<ll> dist(100001, 1e18);
vector<bool> visited(100001);

void Dijkstra(ll x){
    dist[x] = 0;
    parent[x] = -1;
    priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>> q;
    q.push({0, x});
    while(!q.empty()){
        int a = q.top().s;
        q.pop();
        visited[a] = 1;
        for(auto u : adj[a]){
            int b = u.f, w = u.s;
            if(!visited[b] && dist[a] + w < dist[b]){
                dist[b] = dist[a] + w;
                q.push({dist[b], b});
                parent[b] = a;
            }
        }
    }
}
 
void solve(){
    cin >> n >> m;
    for(int i = 0; i < m; i++){
        int a, b, w;
        cin >> a >> b >> w;
        adj[a].pb({b, w});
    }
    Dijkstra(1);
    for(int i = 2; i <= n; i++)
        cout << (dist[i] == 1e18 ? 0 : dist[i]) << ' ';
}  
 
int main(){
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    ios::sync_with_stdio(0); cin.tie(0);
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
}