Cod sursa(job #3304414)

Utilizator Luca_georgescuLuca Georgescu Luca_georgescu Data 23 iulie 2025 11:54:14
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>
#define fs first
#define sc second

using namespace std;

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

int n,m;
int sel[250005],t[250005],d[250005];

typedef pair <int,int> pi;

vector <pi> gr[250005];
priority_queue <pi, vector <pi>, greater <pi> > q;

const int inf=INT_MAX;

void init()
{
    for (int i=1; i<=n; i++ )
    {
        sel[i]=false;
        d[i]=inf;
        t[i]=0;
    }
}

void dijkstra (int p)
{
    init();
    sel[p]=true;
    d[p]=0;

    for (auto i:gr[p] )
    {
        q.push(i);
        d[i.sc]=i.fs;
    }

    while ( !q.empty() )
    {
        while ( !q.empty() && sel[q.top().sc] )
            q.pop();

        if ( q.empty() )
            break;

        int k=q.top().sc;
        int c=q.top().fs;

        q.pop();

        sel[k]=true;
        d[k]=c;

        for (auto i:gr[k] )
        {
            if ( !sel[i.sc] && c+i.fs<d[i.sc] )
            {
                q.push({c+i.fs,i.sc});
                t[i.sc]=k;
            }
        }
    }
}

int main()
{
    f >> n >> m;

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

    dijkstra(1);

    for (int i=2; i<=n; i++ )
       if ( d[i]!=inf )
            g << d[i] << " ";
        else g << 0 << " ";

    return 0;
}