Pagini recente » Cod sursa (job #2187284) | Cod sursa (job #429217) | Cod sursa (job #740442) | Cod sursa (job #2511913) | Cod sursa (job #2981985)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
const int SIZE = 50005;
const int INF = 0x3f3f3f3f;
int n, m;
vector < pair <int, int> > adj[SIZE];
void Read()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, z;
f >> x >> y >> z;
adj[x].push_back(make_pair(y, z));
}
}
void BellmanFord(int startNode)
{
queue <int> q;
vector <int> dist(SIZE, INF);
vector <int> cntInQueue(SIZE, 0);
vector <bool> inQueue(SIZE, false);
q.push(startNode);
dist[startNode] = 0;
cntInQueue[startNode] = 1;
inQueue[startNode] = true;
while (q.empty() == false)
{
int node = q.front();
inQueue[node] = false;
q.pop();
for (unsigned int i = 0; i < adj[node].size(); i++)
{
int neighbour = adj[node][i].first;
int cost = adj[node][i].second;
if (dist[node] + cost < dist[neighbour])
{
dist[neighbour] = dist[node] + cost;
if (inQueue[neighbour] == false)
{
inQueue[neighbour] = true;
q.push(neighbour);
cntInQueue[neighbour]++;
if (cntInQueue[neighbour] >= n)
{
cout << "Ciclu negativ!";
return;
}
}
}
}
}
for (int i = 2; i <= n; i++)
{
cout << dist[i] << " ";
}
}
int main()
{
Read();
BellmanFord(1);
return 0;
}