Cod sursa(job #2828239)

Utilizator cezar.balutaCezar Baluta cezar.baluta Data 6 ianuarie 2022 23:59:28
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>

using namespace std;

struct pereche{
    int y,cost;
};

const int N = 5e4 + 5;
vector<pereche>v[N];
bitset<N>inq;
queue<pereche>q;
int dp[N];

void init(int n){
    for(int i=1;i<n;i++){
        dp[i] = 1<<30;
    }
}

void bfs(){
    inq[1] = true;
    pereche x;
    x.y=1;
    x.cost=0;
    dp[1] = 0;
    q.push(x);
    while(!q.empty()){
        x = q.front();
        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() {
    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 = 1<<30;
    for(int i=2;i<=n;i++){
        if(dp[i] == nr){
            out<<0<<" ";
            continue;
        }
        out<<dp[i]<<" ";
    }
    return 0;
}