Cod sursa(job #2797078)

Utilizator LucaMihaiLM10Luca Ilie LucaMihaiLM10 Data 9 noiembrie 2021 11:09:40
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <stdio.h>
#include <queue>
#include <vector>

#define MAX_N 50000

using namespace std;

struct muchie {
    int nod, cost;
    bool operator < (const muchie &aux) const {
        return cost > aux.cost;
    }
};

int dist[MAX_N], viz[MAX_N];
vector <muchie> muchii[MAX_N];
priority_queue <muchie> pq;

int main() {
    FILE *fin, *fout;
    int n, m, x, y, next, c, i;
    struct muchie crt;

    fin = fopen( "dijkstra.in", "r" );
    fscanf( fin, "%d%d", &n, &m );
    for ( i = 0; i < m; i++ ) {
        fscanf( fin, "%d%d%d", &x, &y, &c );
        x--;
        y--;
        muchii[x].push_back( { y, c } );
    }
    fclose( fin );

    for ( i = 0; i < n; i++ )
        dist[i] = -1;

    pq.push( { 0, 0 } );
    while ( !pq.empty() ) {
        crt = pq.top();
        pq.pop();
        if ( viz[crt.nod] == 0 ) {
            viz[crt.nod] = 1;
            dist[crt.nod] = crt.cost;
            for ( i = 0; i < muchii[crt.nod].size(); i++ ) {
                next = muchii[crt.nod][i].nod;
                if ( dist[next] == -1 || dist[crt.nod] + muchii[crt.nod][i].cost < dist[next] ) {
                    dist[next] = dist[crt.nod] + muchii[crt.nod][i].cost;
                    pq.push( { next, dist[crt.nod] + muchii[crt.nod][i].cost } );
                }
            }
        }
    }

    fout = fopen( "dijkstra.out", "w" );
    for ( i = 1; i < n; i++ )
        fprintf( fout, "%d ", dist[i] == -1 ? 0 : dist[i] );
    fclose( fout );

    return 0;
}