Cod sursa(job #2472436)

Utilizator andreighinea1Ghinea Andrei-Robert andreighinea1 Data 12 octombrie 2019 13:09:35
Problema Algoritmul lui Dijkstra Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define Nmax 50002
#define inf 0x3f3f3f3f

using namespace std;

FILE *f=fopen("dijkstra.in","rt");
ofstream o("dijkstra.out");

int n,m,i,x,y,c,d[Nmax];
bool used[Nmax];

struct cmp{
    inline bool operator() (const int &a,const int &b){
        return d[a]>d[b];
    }
};

priority_queue<int,deque<int>,cmp> q;

struct node{
    int x,c;
} t;

vector<node> g[Nmax];

void read(){
    fscanf(f,"%d%d",&n,&m);
    for(i=1;i<=m;++i){
        fscanf(f,"%d%d%d",&x,&y,&c);
        t.x=y;
        t.c=c;
        g[x].push_back(t);
    }
}

void dijsktra(){
    int x,v,c,l;
    for(i=2;i<=n;++i)
        d[i]=inf;
    d[1]=0;

    q.push(1);
    while(!q.empty()){
        while(q.top() <= n && used[q.top()])
            q.pop();
        if(q.empty())
            return;
        x=q.top();
        q.pop();

        used[x]=true;
        l=g[x].size();
        for(int i=0;i<l;++i){
            v=g[x][i].x;
            c=g[x][i].c+d[x];
            if(c<d[v]){
                d[v]=c;
                q.push(v);
            }
        }
    }
}

void afis(){
    for(i=2;i<=n;++i){
        if(d[i]==inf)
            o << 0 << " ";
        else
            o << d[i] << " ";
    }
}

int main()
{
    read();
    dijsktra();
    afis();
    return 0;
}