Pagini recente » Cod sursa (job #348141) | Cod sursa (job #706411) | Cod sursa (job #1708714) | Cod sursa (job #2082976) | Cod sursa (job #2883943)
#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);
struct Compare
{
bool operator() (pair <int, int> a, pair <int, int> b)
{
return a.second > b.second;
}
};
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();
Q.pop();
inQueue[node] = false;
cntInQueue[node]++;
if (cntInQueue[node] >= n)
{
return false;
}
for (int i = 0; i < G[node].size(); i++)
{
int neighbour = G[node][i].first;
int cost = G[node][i].second;
if (dist[node] + cost < dist[neighbour])
{
dist[neighbour] = dist[node] + cost;
if (inQueue[neighbour] == false)
{
Q.push(neighbour);
inQueue[neighbour] = true;
}
}
}
}
return true;
}
int main()
{
Read();
if (BellmanFord(1) == false)
{
g << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; i++)
{
g << dist[i] << " ";
}
}
}