Pagini recente » Cod sursa (job #797605) | Cod sursa (job #2580748) | Cod sursa (job #1590248) | Cod sursa (job #276617) | Cod sursa (job #2978544)
#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];
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;
adj[x].push_back(make_pair(y, z));
}
}
bool BellmanFord(int startNode)
{
priority_queue < pair <int, int>, vector < pair <int, int> >, Compare> pq;
vector <int> cntInQueue(SIZE, 0);
dist[startNode] = 0;
pq.push(make_pair(startNode, dist[startNode]));
while (pq.empty() == false)
{
int node = pq.top().first;
int distanceToNode = pq.top().second;
cntInQueue[node]++;
pq.pop();
if (cntInQueue[node] >= n) return false;
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]));
}
}
}
return true;
}
int main()
{
Read();
if (BellmanFord(1) == false)
{
g << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; i++)
{
g << dist[i] << " ";
}
}
return 0;
}