Cod sursa(job #2472404)

Utilizator andreighinea1Ghinea Andrei-Robert andreighinea1 Data 12 octombrie 2019 12:27:30
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define Nmax 50001
#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];

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];

/*struct node{
    int x,c;
    node *next;
} *g[Nmax];

void init(int x, int y, int c){
    node *t=new node();
    t->c=c;
    t->x=y;
    t->next=g[x];
    g[x]=t;
}*/

void read(){
    fscanf(f,"%d%d",&n,&m);
    for(i=1;i<=m;++i){
        fscanf(f,"%d%d%d",&x,&y,&c);
        //init(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()){
        x=q.top();
        q.pop();
        /*for(node *p=g[x];p;p=p->next){
            v=p->x;
            c=(p->c)+d[x];
            if(c<d[v]){
                d[v]=c;
                q.push(v);
            }
        }*/
        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;
}