Cod sursa(job #3300644)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 18 iunie 2025 12:39:07
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;

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

typedef pair<int,int> pi;

const int inf=1e8;
const int nmax=5e4+5;

priority_queue <pi,vector<pi>,greater<pi>> q;
vector <pi> g[nmax];
int n, m, d[nmax];
bool sel[nmax];

void dijkstra (int node)
{
    for (int i=1; i<=n; i++)
    {
        d[i]=inf;
        sel[i]=false;
    }
    d[node]=0;
    q.push({0,node});
    while (!q.empty())
    {
        int k=q.top().second;
        q.pop();
        if (sel[k])
            continue;
        sel[k]=true;
        for (auto i:g[k])
        {
            if (d[k]+i.first<d[i.second])
            {
                d[i.second]=d[k]+i.first;
                q.push({d[i.second],i.second});
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i=1; i<=m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        g[x].push_back({c,y});
    }
    dijkstra(1);
    for (int i=2; i<=n; i++)
    {
        if (d[i]==inf)
            fout << 0 << " ";
        else
            fout << d[i] << " ";
    }
}