Pagini recente » Cod sursa (job #741946) | Cod sursa (job #2859631) | Cod sursa (job #1666869) | Cod sursa (job #193018) | Cod sursa (job #2982056)
#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;
struct Compare
{
inline bool operator() (pair <int, int> x, pair <int, int> y)
{
return x.second > y.second;
}
};
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)
{
priority_queue < pair <int, int>, vector < pair <int, int> >, Compare> pq;
vector <int> dist(SIZE, INF);
vector <int> cntInQueue(SIZE, 0);
dist[startNode] = 0;
pq.push(make_pair(startNode, dist[startNode]));
cntInQueue[startNode] = 1;
while (pq.empty() == false)
{
int node = pq.top().first;
int distanceToNode = pq.top().second;
pq.pop();
if (dist[node] < distanceToNode) continue;
for (unsigned int i = 0; i < adj[node].size(); i++)
{
int neighbour = adj[node][i].first;
int cost = adj[node][i].second;
if (distanceToNode + cost < dist[neighbour])
{
dist[neighbour] = distanceToNode + cost;
pq.push(make_pair(neighbour, dist[neighbour]));
cntInQueue[neighbour]++;
if (cntInQueue[neighbour] >= n - 1)
{
g << "Ciclu negativ!";
return;
}
}
}
}
for (int i = 2; i <= n; i++)
{
g << dist[i] << " ";
}
}
int main()
{
Read();
BellmanFord(1);
return 0;
}