Cod sursa(job #3255478)

Utilizator razviii237Uzum Razvan razviii237 Data 10 noiembrie 2024 18:16:09
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int maxn = 50005, maxm = 250005, inf = 1 << 30;

int d[maxn];

class cmp {
public:
    bool operator() (int a, int b) {
        return d[a] > d[b]; // in ordine crescatoare dupa distanta
    }
};

int n, m;
priority_queue<int, vector<int>, cmp> pq;
vector<pair<int, int>> g[maxn];
int viz[maxn];

void dijkstra() {
    pq.push(1);
    viz[1] = 1;
    while(!pq.empty()) {
        int nod = pq.top();
        viz[nod] = 0;
        pq.pop();
        for(auto muchie : g[nod]) {
            if(d[nod] + muchie.second < d[muchie.first]) {
                d[muchie.first] = d[nod] + muchie.second;
                if(viz[muchie.first] == 0) {
                    viz[muchie.first] = 1;
                    pq.push(muchie.first);
                }
            }
        }
    }
}

int main()
{
    int x, y, z;
    fin >> n >> m;
    for(int i = 1; i <= m; i ++) {
        fin >> x >> y >> z;
        g[x].push_back({y, z});
    }
    for(int i = 2; i <= n; i ++) {
        d[i] = inf;
    }
    dijkstra();
    for(int i = 2; i <= n; i ++) {
        if(d[i] == inf)
            fout << 0 << ' ';
        else
            fout << d[i] << ' ';
    }

    fin.close();
    fout.close();
    return 0;
}