Pagini recente » Cod sursa (job #2916796) | Cod sursa (job #1621582) | Cod sursa (job #766511) | Cod sursa (job #948070) | Cod sursa (job #2453697)
#include <fstream>
#include <queue>
#define inf 1000000000
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
queue<int> q;
long n, m, cost[50010], times[50010];
struct muchie{
long a, b, c;
} muchii[250010];
int main() {
f >> n >> m;
for(int i = 1; i <= m; i++)
f >> muchii[i].a >> muchii[i].b >> muchii[i].c;
cost[1] = 0;
for(int i = 2; i <= n; i++)
cost[i] = inf;
q.push(1);
while(!q.empty()) {
int a = q.front();
q.pop();
times[a]++;
if(times[a] > n) {
g << "Ciclu negativ!";
return 0;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(cost[muchii[j].a] + muchii[j].c < cost[muchii[j].b]) {
cost[muchii[j].b] = cost[muchii[j].a] + muchii[j].c;
q.push(muchii[j].b);
}
}
for(int i = 2; i <= n; i++)
g << cost[i] << ' ';
}