Pagini recente » Cod sursa (job #2905239) | Cod sursa (job #2598990) | Cod sursa (job #1462894) | Cod sursa (job #2940159) | Cod sursa (job #2873387)
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define DIM 50000
#define INF (1LL << 30)
typedef pair<int, int> PII;
int n, m;
bool sel[DIM + 1]; //ce elemente am in coada;
int cost[DIM + 1]; //costul pana la fiecare element;
vector <PII> G[DIM + 1];
queue <int> Q;
static inline void BellmanFord(int st) {
for(int i = 1; i <= n; i++)
cost[i] = INF;
Q.push(st);
cost[st] = 0;
sel[st] = 1;
while(!Q.empty()) {
int nod = Q.front();
int c = cost[nod];
sel[nod] = 0; //scot nodul din coada;
Q.pop();
for(auto e : G[nod])
if(c + e.second < cost[e.first]) { //daca am un drum mai mic;
cost[e.first] = c + e.second;
sel[e.first] = 1;
Q.push(e.first);
}
}
}
int main() {
fin.tie(0);
fout.tie(0);
fin >> n >> m;
for(int i = 1; i <= m; i++) {
int x, y, c;
fin >> x >> y >> c;
G[x].push_back({y, c});
}
BellmanFord(1);
for(int i = 2; i <= n; i++)
fout << cost[i] << " ";
return 0;
}