Cod sursa(job #2374928)

Utilizator razvanlgu31Razvan Lungu razvanlgu31 Data 7 martie 2019 21:18:45
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>

#define NMAX 50010
#define INF (1<<30)

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

struct Nod {
    int y, cost;
    Nod() {
        y = 0;
        cost = 0;
    }
    Nod(int y, int cost) {
        this->y = y;
        this->cost = cost;
    }
    inline bool operator<(const Nod& x) const {
        return x.cost < cost;
    }
};
priority_queue <Nod> q;
vector <Nod> v[NMAX];
int x, y , cost, n, m, d[NMAX], nod, viz[NMAX];

void dijkstra() {
    q.push(Nod(1, 0));
    while(!q.empty()) {
        nod = q.top().y;
        q.pop();
        if(viz[nod] == 0) {
            viz[nod] = 1;
            for(vector <Nod> :: iterator it=v[nod].begin();it!=v[nod].end();it++)
					if(d[it->y]>d[nod]+it->cost) {
						d[it->y]=d[nod]+it->cost;
						q.push(Nod(it->y,d[it->y]));
					}
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 0; i < n; ++i) {
        fin >> x >> y >> cost;
        v[x].push_back(Nod(y, cost));
    }
    for (int i = 2; i <= n; ++i) {
        d[i] = INF;
    }
    dijkstra();
    for (int i = 2; i <= n; ++i) {
        if (d[i] == INF)
            fout << "0 ";
        else {
            fout << d[i] << " ";
        }
    }




    return 0;
}