Cod sursa(job #3266948)

Utilizator Edi17roAnghel Eduard Edi17ro Data 10 ianuarie 2025 19:35:22
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>
#define INF 1e9
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
const int NMAX = 50000;
int n, m;

struct Point {
    int node, cost;

    bool operator < (const Point& a) const { ///revert what you want
        return cost > a.cost;
    }
};

vector<pair<int, int> > g[NMAX + 1];
int cost[NMAX + 1];

void dij(int start)
{
    for(int i = 1; i <= n; ++i)
        cost[i] = INF;
    //priority_queue <Point> q;
    priority_queue <pair<int, int>, vector<pair<int, int> > , greater < pair<int, int> > > q;
    cost[start] = 0;
    q.push({1, 0});

    while(!q.empty())
    {
        int v = q.top().first;
        int c = q.top().second;
        q.pop();

        if(cost[v] != c)
            continue;

        for(int i = 0; i < g[v].size(); ++i){
            if(cost[v] + g[v][i].second < cost[g[v][i].first]){
                q.push({g[v][i].first, g[v][i].second + c});
                cost[g[v][i].first] = g[v][i].second + c;
            }
        }
    }

}

int main()
{
    in >> n >> m;
    int u, v;
    int c;
    for(int i = 1; i <= m; ++i)
    {
        in >> u >> v >> c;
        g[u].push_back({v, c});
    }

    dij(1);

    for(int i = 2; i <= n; ++i)
    {
        if(cost[i] == INF)
            out << 0 << ' ';
        else
        out << cost[i] << ' ';
    }
    return 0;
}