Pagini recente » Cod sursa (job #419712) | Cod sursa (job #2707731) | Cod sursa (job #867372) | Cod sursa (job #649512) | Cod sursa (job #2764846)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <algorithm>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
const int MAX_N = 50005;
const int INF = 0x3f3f3f3f;
vector < pair <int, int> > adj[MAX_N];
int main(void) {
int n, m;
f >> n >> m;
for (int i = 0; i < m; ++ i) {
int x, y, c;
f >> x >> y >> c;
adj[x].push_back(make_pair(y, c));
}
queue <int> Q;
bool in_queue[MAX_N];
vector <int> dist(MAX_N, INF), cnt_in_queue(MAX_N, 0);
bool negative_cycle = false;
dist[1] = 0, Q.push(1);
while (!Q.empty() && !negative_cycle)
{
int node = Q.front();
Q.pop();
in_queue[node] = false;
vector < pair <int, int> >::iterator it;
for (it = adj[node].begin(); it != adj[node].end(); ++ it) if (dist[node] < INF)
if (dist[it->first] > dist[node] + it->second) {
dist[it->first] = dist[node] + it->second;
if (!in_queue[it->first]) {
if (cnt_in_queue[it->first] > n)
negative_cycle = true;
else {
Q.push(it->first);
in_queue[it->first] = true;
cnt_in_queue[it->first] ++;
}
}
}
}
if (!negative_cycle) {
for (int i = 2; i <= n; ++ i)
g << dist[i] << " ";
}
else
g << "Ciclu negativ!\n";
return 0;
}