Cod sursa(job #3304412)

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

using namespace std;

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

const int nmax=1005,inf=INT_MAX;

typedef pair<int,pair<int,int> > piii;

vector <piii> gr[nmax];
priority_queue <piii,vector<piii>,greater<piii> > q;

int t[nmax],d[nmax];
bool sel[nmax];

int x,y,c,n,mini,k,p,m;

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

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

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

        if ( q.empty() )
            break;

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

        d[k]=c;
        sel[k]=true;
        q.pop();

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

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

    while ( f >> x >> y >> c )
        gr[x].pb({c,{x,y}});

    dijkstra(p);

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