Cod sursa(job #3148801)

Utilizator baragan30Baragan Andrei baragan30 Data 4 septembrie 2023 13:54:12
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;
const int NMAX = 50001;
int n,m;
int cost[NMAX];
///       neighbour, cost
vector < pair<int, int> > v[NMAX];
bool marca[NMAX];

struct compara
{
    bool operator()(int x, int y)
    {
        return cost[x] > cost[y];
    }
};
priority_queue<int, vector<int>, compara> q;






void citire()
{
    ifstream in("dijkstra.in");
    in>> n>> m;
    for (int i = 1; i <= m ; i ++)
    {
        int x,y,c;
        in >> x >> y >> c;
        v[x].push_back(make_pair(y,c));

    }
}

void Dijkstra(int startNode)
{
    q.push(startNode);
    while(!q.empty())
    {
        int nod = q.top();
        q.pop();
        for (auto item : v[nod])
        {
            int neigh = item.first;
            int c = item.second;
            if(cost[neigh] == 0 || cost[neigh] < cost[nod] + c)
            {
                cost[neigh] = cost[nod] + c;
                if(!marca[neigh]){
                    marca[neigh] = true;
                    q.push(neigh);
                }
            }
        }
    }

}
void afisare()
{
    ofstream out("dijkstra.out");
    for (int i = 2; i <= n; i ++)
    {
        out<< cost[i]<<" ";
    }

}

int main()
{
    citire();
    Dijkstra(1);
    afisare();
    return 0;
}