Pagini recente » Cod sursa (job #3205860) | Cod sursa (job #3280573) | Cod sursa (job #2748527) | Cod sursa (job #2423426) | Cod sursa (job #2424010)
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;
#define max_size 9999999
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<pair<int, int>> graph[5000001];
queue<int> q;
int cost[5000001];
int freq[5000001];
int N, M, x, y, c;
int bellmanford()
{
for (int i = 2; i <= N; i++)
cost[i] = max_size;
cost[1] = 0;
q.push(1);
while (!q.empty())
{
int aux = q.front();
freq[aux]++;
if (freq[aux] >= M)
{
fout << "Ciclu negativ!";
return 0;
}
q.pop();
for (unsigned int i = 0; i < graph[aux].size(); i++)
{
pair<int, int>x = graph[aux][i];
if (cost[x.first] > cost[aux] + x.second);
q.push(x.first);
}
}
return 1;
}
int main()
{
fin >> N >> M;
for (int i = 1; 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;
}