Pagini recente » Cod sursa (job #895814) | Cod sursa (job #377220) | Cod sursa (job #82483) | Cod sursa (job #2535269) | Cod sursa (job #2695918)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 50005;
const int INF = 2e9;
int dist[NMAX];
priority_queue<pair<int,int>> pq;
vector<pair<int,int>> graph[NMAX];
void dijkstra() {
pair<int,int> a, b;
a = make_pair(0, 1);
pq.push(a);
int node, cost;
int next_node;
int next_cost;
while(!pq.empty()) {
node = pq.top().second;
cost = pq.top().first;
pq.pop();
if(cost > dist[node])
continue;
for(int i = 0; i < graph[node].size(); i++) {
next_node = graph[node][i].second;
next_cost = graph[node][i].first;
if(dist[node] + next_cost < dist[next_node]) {
dist[next_node] = dist[node] + next_cost;
next_cost = dist[next_node];
pq.push(make_pair(next_cost, next_node));
}
}
}
}
int main() {
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m;
fin >> n >> m;
dist[1] = 0;
for(int i = 2; i <= n; i++) {
dist[i] = INF;
}
for(int i = 1; i <= m; i++) {
int x,y,cost;
fin >> x >> y >> cost;
graph[x].emplace_back(cost, y);
}
dijkstra();
for(int i = 2; i <= n; i++) {
if(dist[i] == INF) {
fout << 0 << " ";
}
else {
fout << dist[i] << " ";
}
}
fin.close();
fout.close();
return 0;
}