Cod sursa(job #2097295)

Utilizator alinp25Alin Pisica alinp25 Data 30 decembrie 2017 21:29:05
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <queue>
#include <iostream>

#define inf 0x3f3f3f3f

typedef std::pair<int, int> iPair;
int n;
std::vector<int> d(50001, inf);
std::vector<iPair> v[50001];
int node, next, cost;
std::priority_queue<iPair, std::vector<iPair>, std::greater<iPair> > pq;
int inqueue[50001];

void read() {
    std::ifstream fin("dijkstra.in");
    int x, y, w, m;
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        fin >> x >> y >> w;
        v[x].push_back(std::make_pair(y, w));
    }
    fin.close();
}

void printSol() {
    std::ofstream fout("dijkstra.out");
    for (int i = 2; i <= n; i++) {
        if (d[i] == inf) {
            fout << "0 ";
        } else {
            fout << d[i] << " ";
        }
    }
    fout.close();
}

void solve() {
    d[1] = 0;
	pq.push(std::make_pair(1, 0));
	inqueue[1] = 1;
    while (!pq.empty()) {
        node = pq.top().first;
		pq.pop();
		inqueue[node] = 0;
        for (int i = 0; i < v[node].size(); i++) {
            next = v[node][i].first;
            cost = v[node][i].second;
            if (d[next] > d[node] + cost) {
				d[next] = d[node] + cost;
				if (!inqueue[next]) {
					pq.push(std::make_pair(next, d[next]));
					inqueue[next] = 1;
				}
            }
        }
    }
}

int main(int argc, char* argv[])
{
    read();
    solve();
    printSol();
    return 0;
}