Pagini recente » Cod sursa (job #876428) | Cod sursa (job #1435051) | Cod sursa (job #2177636) | Cod sursa (job #871641) | Cod sursa (job #2424834)
#include<iostream>
#include<fstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define max 10001
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair<int, int> > graph[50050];
queue<int> coada;
int N, M, x, y, c, freq[50001], cost[50001];
int bellmanford()
{
for (int i = 2; i <= N; i++)
cost[i] = max;
cost[1] = 0;
coada.push(1);
while (!coada.empty())
{
int var = coada.front();
freq[var]++;
if (freq[var] >= M)
{
fout << "Ciclu negativ!"<<endl;
return 0;
}
coada.pop();
for (unsigned int i = 0; i < graph[var].size(); i++)
{
pair<int, int> x = graph[var][i];
if (cost[x.first] > cost[var] + x.second)
{
cost[x.first] = cost[var] + x.second;
coada.push(x.first);
}
}
}
return 1;
}
int main()
{
fin >> N >> M;
for (int i = 0; i <M; i++)
{
fin >> x >> y >> c;
graph[x].push_back(make_pair(y, c));
}
if(bellmanford()==1)
for (int i = 2; i <= N; i++)
fout << cost[i] << " ";
return 0;
}