Pagini recente » Cod sursa (job #1875710) | Borderou de evaluare (job #1567240) | Cod sursa (job #1739294) | Cod sursa (job #2449609) | Cod sursa (job #2119692)
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#include <climits>
#include <cstring>
#define MAXN 50001
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair <int, int> > v[MAXN];
bitset <MAXN> in_queue(false);
queue <int> q;
int dist[MAXN], count_in_queue[MAXN], n, m;
void init()
{
memset(dist, INT_MAX, sizeof(dist));
memset(count_in_queue, 0, sizeof(count_in_queue));
}
void read()
{
int x, y, c;
fin >> n >> m;
for (int i = 0; i < m; ++i) {
fin >> x >> y >> c;
v[x].push_back(make_pair(y, c));
}
}
int main()
{
int negativ = 0, aux;
init();
read();
dist[1] = 0;
q.push(1);
in_queue[1] = true;
while (q.empty() == false && negativ == 0) {
aux = q.front();
q.pop();
in_queue[aux] = false;
vector <pair <int, int> >::iterator it;
for (it = v[aux].begin(); it != v[aux].end(); ++it) {
if (dist[aux] < INT_MAX && dist[it->first] > dist[aux] + it->second) {
dist[it->first] = dist[aux] + it->second;
if (in_queue[it->first] == false) {
if (count_in_queue[it->first] > n) {
cout << it->first;
negativ = 1;
break;
}
else {
in_queue[it->first] = true;
count_in_queue[it->first]++;
q.push(it->first);
}
}
}
}
}
if (negativ == 1)
fout << "Ciclu negativ!";
else {
for (int i = 2; i <= n; ++i)
fout << dist[i] << ' ';
}
return 0;
}