Cod sursa(job #3162070)

Utilizator Raul_AArdelean Raul Raul_A Data 28 octombrie 2023 12:09:09
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
using namespace std;

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

#define cin in
#define cout out

const int MAX=50000;
ll cost[MAX+5]; 

struct cmp{
    
    bool operator ()(int x,int y) 
    { 
        return (cost[x] > cost[y]);
    }
};

int n,m,x,y,z;
vector< pii> v[MAX+5];///din x -> y cost z
priority_queue<int,vector<int>,cmp> Q;

void dijkstra(int start) 
{
    Q.emplace(start);
    cost[start]=0;
    
    while(!Q.empty())
    {
        int nod=Q.top();
        Q.pop();
        
        for(auto x: v[nod])
        {
            //cout<<x.val+cost[nod]<<' '<<cost[x.nod]<<'\n';
            if(cost[x.first]==LLONG_MAX and cost[nod]+x.second<cost[x.first])
            {
                cost[x.first]=cost[nod]+x.second;
                Q.push(x.first);
            }
        }
    }
}

int main()
{
    cin>>n>>m;
    
    while(m--) 
    {
        cin>>x>>y>>z;
        v[x].push_back({y,z});
    }
    
    for(int i=1;i<=n;i++)
        cost[i]=LLONG_MAX;
    
    dijkstra(1);
    
    for(int i=2;i<=n;i++,cout<<' ')
        if(cost[i]==LLONG_MAX)
            cout<<0;
        else
            cout<<cost[i];
    return 0;
}