Cod sursa(job #2866817)

Utilizator mateisebastian4Matei Sebastian mateisebastian4 Data 9 martie 2022 23:39:26
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int N=2415115;
int dp[N],n,x,y,m;


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

struct pereche
{

    int y,cost;

};


struct comparare
{
    bool operator()(pereche A,pereche B){
    return A.y>B.y;
    }
};

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

void bfs()
{
    inq[1]=1;
    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()
{int x,y,cost;
    pereche w;
    fin>>n>>m;
    while(fin>>x>>y>>cost)
    {
        w.y=y;
        w.cost=cost;
        v[x].push_back(w);
    }
    init(n+1);
    bfs();
    for(int i=2;i<=n;i++)
        if(dp[i]==N)
        {
        fout<<"0"<<" ";
        continue;
        }
    else fout<<dp[i]<<" ";
}