Cod sursa(job #2846168)

Utilizator handicapatucavasi eduard handicapatu Data 8 februarie 2022 21:01:47
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
///grafuri orientate si ponderate
///determina distanta minima de la un nod selectat la toate celelalte noduri
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define INF 2000000000

using namespace std;

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

struct Queue{
    int node , cost;
    Queue(int a , int b){
        this -> node = a;
        this -> cost = b;
    }
    bool operator <(Queue const N) const{
        return this -> cost > N.cost;
    }
};

priority_queue < Queue > Q;
vector < pair < int , int > > V[50001];
int n , m , a , b , c;
int dist[50001];
bool inqueue[50001];

void dijkstra(int x){
    dist[x] = 0;
    inqueue[x] = true;
    Queue w = Queue(x , dist[x]);
    Q.push(w);
    while(!Q.empty()){
        Queue now = Q.top();
        Q.pop();
        inqueue[now.node] = false;
        for(int i = 0 ; i < V[now.node].size() ; ++i){
            if(dist[now.node] + V[now.node][i].second < dist[V[now.node][i].first]){
                dist[V[now.node][i].first] = dist[now.node] + V[now.node][i].second;
                if(inqueue[V[now.node][i].first] == false){
                    inqueue[V[now.node][i].first] = true;
                    Queue w = Queue(V[now.node][i].first , dist[V[now.node][i].first]);
                    Q.push(w);
                }
            }
        }
    }
}

int main()
{
    f >> n >> m;
    for(int i = 1 ; i <= n ; ++i)
        dist[i] = INF;
    for(int i = 1 ; i <= m ; ++i){
        f >> a >> b >> c;
        V[a].push_back(make_pair(b , c));
    }
    dijkstra(1);
    for(int i = 2 ; i <= n ; ++i){
        if(dist[i] != INF)
            g << dist[i] << " ";
        else
            g << 0 << " ";
    }
    return 0;
}