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