Cod sursa(job #2472817)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 12 octombrie 2019 23:03:11
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
#define inf 1000000000
using namespace std;

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

struct state {
    int node, cost;
    bool operator<(const state &other) const {
        return cost > other.cost;
    }
};

int n, m;
vector <pair <int, int> > graf[50010];
priority_queue<state > q;
int dist[50010];
bool visited[50010];

void citire() {
    f >> n >> m;
    for(int i = 0; i < m; i++) {
        int a, b, c;
        f >> a >> b >> c;
        graf[a].push_back({b, c});
    }
}

void dijkstra() {
    for(int i = 1; i<= n; i++)
        dist[i] = -1;
    q.push({1, 0});
    while(!q.empty()) {
        int curr = q.top().node;
        int cost = q.top().cost;
        q.pop();
        if(dist[curr] != -1)
            continue;
        dist[curr] = cost;
        for(int i = 0; i < graf[curr].size(); i++) {
            int next = graf[curr][i].first;
            int c = graf[curr][i].second;
            q.push({next, c+cost});
        }
    }
}

int main() {
    citire();
    dijkstra();
    for(int i = 2; i <= n; i++) {
        if(dist[i] == -1)
            dist[i] = 0;
        g << dist[i] << ' ';
    }
}