Cod sursa(job #3243018)

Utilizator cristian46290Petre Cristian cristian46290 Data 15 septembrie 2024 11:53:00
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <fstream>
#include <math.h>
#include <algorithm>
#include <vector>
#include <queue>


using namespace std;

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


const int nMax = 50005;
const int oo = (1 << 30);
int n, m, x, y;
int distanta[nMax];
bool ok[nMax];

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

priority_queue < int, vector < int >, cmp> coada;
vector < pair < int, int> > muchii[nMax];

void dijkstra(int nodS)
{
    for (int i = 1;i <= n;i++)distanta[i] = oo;
    distanta[nodS] = 0;
    coada.push(nodS);
    ok[nodS] = true;
    while(!coada.empty()){
        int Nod = coada.top();
        coada.pop();
        ok[Nod] = false;
        for (unsigned int i = 0;i < muchii[Nod].size();i++){
            int vecin = muchii[Nod][i].first;
            if (distanta[Nod] + muchii[Nod][i].second < distanta[vecin]){
                distanta[vecin] = distanta[Nod] + muchii[Nod][i].second;
                if (ok[vecin] == false)coada.push(vecin);
            }
        }
    }
}

int main()
{
    f >> n >> m;
    for (int i = 1;i <= n;i++){
        int cost;
        f >> x >> y >> cost;
        muchii[x].push_back(make_pair(y,cost));
    }
    dijkstra(1);
    for (int i = 2;i <= n;i++){
        if (distanta[i] != oo)g << distanta[i] << " ";
        else g << 0 << " ";
    }
}