Pagini recente » Cod sursa (job #1395358) | Cod sursa (job #18602) | Cod sursa (job #1192312) | Cod sursa (job #225684) | Cod sursa (job #3246911)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int inf = 1e9; // 10^9
vector<pair<int, int> > v[50005];
int cost[50005];
int inCoada[50005];
class cmp{
public:
bool operator() (int x, int y) {
return cost[x] > cost[y];
}
};
priority_queue<int, vector<int>, cmp> pq;
int n, m, x, y, c;
void dijkstra(int nod) {
for(int i = 1; i <= n; i ++) {
cost[i] = inf;
}
cost[nod] = 0; // costul de la nodul de la care am inceput pana la nodul curent
pq.push(nod);
while(!pq.empty()) {
nod = pq.top();
for(auto elem : v[nod]) {
if(cost[nod] + elem.second < cost[elem.first]) {
cost[elem.first] = cost[nod] + elem.second;
if(inCoada[elem.first] == 0) {
pq.push(elem.first);
inCoada[elem.first] = 1;
}
}
}
inCoada[nod] = 0;
pq.pop();
}
}
int main() {
fin >> n >> m;
for(int i = 1; i <= m; i ++) {
fin >> x >> y >> c; // muchie intre x si y cu costul c
v[x].push_back({y, c});
}
dijkstra(1);
for(int i = 2; i <= n; i ++) {
fout << cost[i] << ' ';
}
return 0;
}