Pagini recente » Cod sursa (job #2695157) | Cod sursa (job #1774694) | Cod sursa (job #1714436) | Cod sursa (job #234129) | Cod sursa (job #2076939)
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <set>
#define STILL_IN_QUEUE 0
#define NOT_IN_QUEUE 1
#define INFINITY 2147483647
#define MAX_N 50001
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<pair<int, int>> graf[MAX_N];
int dist[MAX_N];
int n, m;
int source;
set<pair<int, int>> q;
int stillInQueue[MAX_N];
int main() {
fin>>n>>m;
source = 1;
for (int i = 0; i < m; i++) {
int a, b, c;
fin>>a>>b>>c;
graf[a].push_back(make_pair(c, b));
}
for (int i = 1; i <= n; i++) {
dist[i] = INFINITY;
if (i == source)
dist[i] = 0;
q.insert(make_pair(dist[i], i));
}
while (!q.empty()) {
pair<int, int> nod = *q.begin();
q.erase(q.begin());
stillInQueue[nod.second] = NOT_IN_QUEUE;
vector<pair<int, int>> neighbours = graf[nod.second];
vector<pair<int, int>>::iterator it;
for (it = neighbours.begin(); it != neighbours.end(); it++) {
pair<int, int> neighbour = *it;
if (nod.first != INFINITY) {
if (stillInQueue[neighbour.second] == STILL_IN_QUEUE) {
int alt = nod.first + neighbour.first;
if (alt < dist[neighbour.second]) {
q.erase(make_pair(dist[neighbour.second], neighbour.second));
dist[neighbour.second] = alt;
q.insert(make_pair(dist[neighbour.second], neighbour.second));
}
}
}
}
}
for (int i = 1; i <= n; i++) {
if (i != source) {
if (dist[i] == INFINITY)
fout<<"0 ";
else
fout<<dist[i]<<" ";
}
}
return 0;
}