Cod sursa(job #2836390)

Utilizator cezar.balutaCezar Baluta cezar.baluta Data 20 ianuarie 2022 11:54:24
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>

using namespace std;


const int N = 5e4 + 5;
int dp[N];


struct pereche{

    int cost,y;

};

struct comparare { ;

    bool operator()(pereche a, pereche b){

        return dp[a.y] > dp[b.y];

    }

};

vector<pereche>v[N];
bitset<N>inq;
priority_queue <pereche,vector<pereche>,comparare>q;





void init(int n){

    for(int i=1;i<n;i++){

        dp[i] = 2147483647;

    }

}



void bfs(){

    inq[1] = true;

    pereche x;

    x.y=1;

    x.cost=0;

    dp[1] = 0;

    q.push(x);

    while(!q.empty()){

        x = q.top();

        q.pop();

        inq[x.y] = false;

        for(auto y:v[x.y]){

            if(dp[y.y]>dp[x.y] + y.cost){

                dp[y.y]=dp[x.y] + y.cost;

                if(!inq[y.y]){

                    inq[y.y] = true;

                    q.push(y);

                }

            }

        }

    }

}



int main() {

    ios_base::sync_with_stdio(false);
    ifstream in("dijkstra.in");
    ofstream out("dijkstra.out");
    int n,m,x,y,cost;
    in>>n>>m;
    while(m--){
        in>>x>>y>>cost;
        pereche w;
        w.y=y;
        w.cost=cost;
        v[x].push_back(w);
        w.y=x;
       // v[y].push_back(w);
    }
    init(n+1);
    bfs();
    int nr = 2147483647;
    for(int i=2;i<=n;i++){
        if(dp[i] == nr){
            out<<0<<" ";
            continue;
        }
        out<<dp[i]<<" ";
    }

    return 0;

}