Pagini recente » Cod sursa (job #1685075) | Cod sursa (job #1415573) | Cod sursa (job #3166521) | Cod sursa (job #1413815) | Cod sursa (job #2981982)
#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);
q.push(startNode);
dist[startNode] = 0;
cntInQueue[startNode] = 1;
while (q.empty() == false)
{
int node = q.front();
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;
q.push(neighbour);
cntInQueue[neighbour]++;
if (cntInQueue[neighbour] >= n)
{
g << "Ciclu negativ!";
return;
}
}
}
}
for (int i = 2; i <= n; i++)
{
g << dist[i] << " ";
}
}
int main()
{
Read();
BellmanFord(1);
return 0;
}