Cod sursa(job #3366062)

Utilizator AlexandruCorneaCornea Alexandru Mihai AlexandruCornea Data 28 septembrie 2026 19:57:38
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;

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

int n,m,d[50001];
vector<pair<int,int>> v[50001];

void citire()
{
    fin>>n>>m;

    for(int i=1; i<=m; i++)
    {
        int x,y,c;
        fin>>x>>y>>c;
        v[x].push_back({y,c});
    }
}

void rezolvare()
{
    const int INF=1e9;

    for(int i=1; i<=n; i++)
        d[i]=INF;

    priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;

    d[1]=0;
    q.push({0,1});

    while(!q.empty())
    {
        int dx=q.top().first;
        int x=q.top().second;
        q.pop();

        if(dx!=d[x])
            continue;

        for(auto p:v[x])
        {
            int y=p.first;
            int c=p.second;

            if(d[y]>d[x]+c)
            {
                d[y]=d[x]+c;
                q.push({d[y],y});
            }
        }
    }
}

void afisare()
{
    for(int i=2; i<=n; i++)
    {
        if(d[i]==1000000000)
            fout<<0<<" ";
        else
            fout<<d[i]<<" ";
    }
}

int main()
{
    citire();
    rezolvare();
    afisare();

    return 0;
}