Cod sursa(job #3162051)

Utilizator Raul_AArdelean Raul Raul_A Data 28 octombrie 2023 11:53:10
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;

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

#define cin in
#define cout out

struct date{
    int nod;
    ll val;
    
    bool operator < (const date &b) const
    { 
        return (val >= b.val);
    }
};

const int MAX=50000;

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

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

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;
}