Cod sursa(job #2468359)

Utilizator andreighinea1Ghinea Andrei-Robert andreighinea1 Data 5 octombrie 2019 14:22:48
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <queue>
#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;
    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);
        init(y,x,c);
    }
}

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

    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);
            }
        }
    }
}

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

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