Pagini recente » Cod sursa (job #1795504) | Cod sursa (job #2349132) | Cod sursa (job #2557674) | Borderou de evaluare (job #368889) | Cod sursa (job #2871182)
#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;
vector <pair <int, int> > G[SIZE];
vector <int> dist(SIZE, INF);
void Read()
{
f >> n >> m;
for (int i = 1; i <= n; i++)
{
int x, y, z;
f >> x >> y >> z;
G[x].push_back(make_pair(y, z));
}
}
struct Compare
{
bool operator() (pair <int, int> a, pair <int, int> b)
{
return a.second > b.second;
}
};
bool BellmanFord(int start)
{
queue <int> Q;
vector <int> cntInQueue(SIZE, 0);
vector <bool> onQueue(SIZE, false);
dist[start] = 0;
Q.push(start);
onQueue[start] = true;
while (Q.empty() == false)
{
int node = Q.front();
cntInQueue[node]++;
Q.pop();
onQueue[node] = false;
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 (onQueue[neighbour] == false)
{
Q.push(neighbour);
onQueue[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] << " ";
}
}
}