Cod sursa(job #2572002)

Utilizator andreighinea1Ghinea Andrei-Robert andreighinea1 Data 5 martie 2020 11:11:27
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50002
#define inf 0x3f3f3f3f

using namespace std;

ifstream f("dijkstra.in");
ofstream o("dijkstra.out");

int n,m,i,x,y,z,d[nmax];
bool used[nmax];
vector<pair<int,int> > g[nmax];

struct cmp{
    inline bool operator ()(int a,int b){
        return d[a]>d[b];
    }
};
priority_queue<int,vector<int>,cmp> q;

void dijkstra(int start){
    int x,l,i,c,v;

    for(i=1;i<=n;++i)
        d[i]=inf;
    d[start]=0;
    q.push(start);

    while(!q.empty()){
        x=q.top();
        q.pop();
        used[x]=false;

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

int main()
{
    f >> n >> m;
    for(i=1;i<=m;++i){
        f >> x >> y >> z;
        g[x].push_back(make_pair(y,z));
    }
    dijkstra(1);
    for(i=2;i<=n;++i)
        o << d[i] << " ";
    return 0;
}