Pagini recente » Cod sursa (job #1167247) | Cod sursa (job #1341047) | Cod sursa (job #1255913) | Cod sursa (job #1861958) | Cod sursa (job #3321466)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 50005
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<pair<int,int>> G[NMAX];
int path[NMAX], n,m;
void dijkstra (int source) {
priority_queue<pair<int,int>> pq;
for (int i = 1; i <= n; i++) {
path[i]=-1;
}
path[source]=0;
for (auto it:G[source]) {
pq.push({-it.second,it.first});
}
while (!pq.empty()) {
int node=pq.top().second;
int distance=-pq.top().first;
pq.pop();
if (path[node]!=-1) {
continue;
}
path[node]=distance;
for (const auto& it: G[node]) {
if (path[it.first]==-1) {
pq.push({-(it.second+distance),it.first});
}
}
}
}
int main() {
int x,y,w;
fin >> n >> m;
for (int i = 1; i <= m; i++) {
fin >> x >> y >> w;
G[x].push_back({y,w});
}
dijkstra(1);
for (int i = 2; i <= n; ++i) {
fout << max(path[i], 0) << ' ';
}
return 0;
}