Cod sursa(job #3260676)

Utilizator alex.cojocaruAlex Cojocaru alex.cojocaru Data 3 decembrie 2024 11:51:51
Problema Algoritmul lui Dijkstra Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <map>
#include <queue>
#include <vector>

#define INF (1LL << 31)

using namespace std;

struct Edge {
    int to;
    long long weight;
    bool operator < (const Edge& b) {
        return this->weight > b.weight;
    }
};

map<int, vector<Edge>> graph;
priority_queue<Edge> q;
map<int, long long> dist;

void dijkstra(int s, int n) {
    queue<Edge> q;
    for(int i = 1; i <= n; i++)
        dist[i] = INF;
    q.push({s, 0LL});
    dist[0] = 0LL;
    while(!q.empty()) {
        Edge top = q.front();
        q.pop();
        if(dist[top.to] > top.weight) {
            dist[top.to] = top.weight;
            for(Edge next : graph[top.to])
                q.push({next.to, next.weight+dist[top.to]});
        }
    }
}

int main() {
    ifstream fin("dijkstra.in");
    ofstream fout("dijkstra.out");
    int n, m, to, from;
    long long weight;
    fin>>n>>m;
    for(int i = 0; i < m; i++) {
        fin>>from>>to;
        fin>>weight;
        graph[from].push_back({to, weight});
    }
    dijkstra(1, n);
    for(int i = 2; i <= n; i++) {
        if(dist[i] == INF)
            dist[i] = 0LL;
        fout<<dist[i]<<" ";
    }
    return 0;
}