Cod sursa(job #2501541)

Utilizator coculescugabiCoculescu Gabriel coculescugabi Data 29 noiembrie 2019 20:30:23
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <ctime>

using namespace std;

ifstream fin("in/test1.in");
ofstream fout("out/test1.out");

const int NMax = 50005;
const int oo = (1 << 30); // max int

int N, M;
int D[NMax]; // distance
bool Inqueue[NMax]; // inqueue[i] = true if node is visited

vector < pair < int, int > > G[NMax];

struct compdist {
    bool operator()(int x, int y) {
        return D[x] > D[y];
    }
};

priority_queue < int, vector < int >, compdist> Queue;
// push nodes ascending regarding the cost

void Read() {
    fin >> N >> M;
    for(int i = 1; i <= M; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y,c));
    }
}

void Dijkstra(int s) {
    for(int i = 1; i <= N; i++) {
        D[i] = oo;
        Inqueue[i] = false;
    }
    D[s] = 0;
    Queue.push(s);
    Inqueue[s] = true;
    while(!Queue.empty()) {
        int nodCurrent = Queue.top(); // take node with smallest cost
        for(unsigned int i = 0; i < G[nodCurrent].size(); i++) {
            int Neighbour = G[nodCurrent][i].first;
            int Cost = G[nodCurrent][i].second;
            if(D[nodCurrent] + Cost < D[Neighbour]) {
                D[Neighbour] = D[nodCurrent] + Cost;
                if(Inqueue[Neighbour] == false) {
                    Queue.push(Neighbour);
                    Inqueue[Neighbour] = true;
                }
            }
        }
        Inqueue[nodCurrent] = false;
        Queue.pop();
    }
}

void Write() {
    for(int i = 2; i <= N; i++) {
        if(D[i] != oo)
            fout << D[i] << " ";
        else
            fout << "0 "; // if there is no path to the node
    }
}

int main()
{
    Read();
    double start = clock();
    Dijkstra(1);
    double end = clock();
    double rez = (end - start) / CLOCKS_PER_SEC;
    cout << rez;
    Write();
    return 0;
}