Cod sursa(job #2418731)

Utilizator malina99oanea ana malina malina99 Data 5 mai 2019 23:53:02
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int inf = 1 << 30;
const int nmax = 50001;

struct node {
    int noUrm;
    int cost;
    node *next;
};

node *graph[nmax];
int distanta[nmax];
int vizitat[nmax];
int n, m;

void add( int n1, int n2, int cost ) {
    node * nod = new node;
    nod->cost = cost;
    nod->next = graph[n1];//adaug la inceput
    nod->noUrm = n2;
    graph[n1] = nod;

}

void read() {
    f >> n >> m;
    for( int i = 0; i < m; i++) {
        int n1, n2, cost;
        f >> n1 >> n2 >> cost;
        add( n1, n2, cost);
    }
}

void dijkstra() {
    for( int i = 2; i <= n; i++)
        distanta[i] = inf;

    for( int i = 1; i <= n; i++ ) {
        int distantaMinim = inf, nodMinim;

        for( int j = 1; j <= n; j++) 
            if( distantaMinim >= distanta[j] && !vizitat[j] )   
                distantaMinim = distanta[j], nodMinim = j;

        vizitat[nodMinim] = 1;

        node * start = graph[ nodMinim ];
        while( start ) {
            if( distanta[ start->noUrm ] > start->cost + distanta[nodMinim] )
                distanta[ start->noUrm ] = start->cost + distanta[nodMinim];
            start = start->next;
        }
    }
}

int main() {
    read();
    dijkstra();

    for( int i = 2; i <= n; i++ )
        if( distanta[i] == inf ) g << 0 << " ";
        else g << distanta[i] << " ";
    return 0;
}