Pagini recente » Cod sursa (job #561230) | Cod sursa (job #1820052) | Cod sursa (job #2751779) | Cod sursa (job #1086321) | Cod sursa (job #2491636)
#include <bits/stdc++.h>
#define N 50005
#define pb push_back
#define fi first
#define se second
#define pii pair<int, int>
#define VI vector<int>
using namespace std;
const int INF = 0x3f3f3f3f;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int nodes; // number of nodes (read it)
int S = 1; // the starting node
vector<pii> g[N]; // fi = next node, se = distance
VI dist;
// Computes the distance from S to all the other nodes, no negative cycles
void dijkstra(){
dist = VI(nodes + 1, INF); // starting at 1
dist[S] = 0;
queue<pair<int, int&>> que;
que.push({S, dist[S]});
bool inQ[nodes + 1];
inQ[S] = true;
while(!que.empty()){
pii p = que.front(); que.pop();
inQ[p.fi] = false;
if(p.se != dist[p.fi]) continue;
for(pii e : g[p.fi])
if(p.se + e.se < dist[e.fi]){
dist[e.fi] = p.se + e.se;
if(!inQ[e.fi])
que.push({e.fi, dist[e.fi]}),
inQ[e.fi] = true;
}
}
}
int main(){
int m;
fin >> nodes >> m;
while(m --){
int x, y, d;
fin >> x >> y >> d;
g[x].pb({y, d});
}
dijkstra();
for(int i = 2; i <= nodes; i ++)
if(dist[i] == INF) fout << "0 ";
else fout << dist[i] << ' ';
}