Pagini recente » Cod sursa (job #3267756) | Cod sursa (job #3167327) | Cod sursa (job #2654834) | Cod sursa (job #260694) | Cod sursa (job #2871178)
#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)
{
priority_queue <int, vector <pair <int ,int> >, Compare> PQ;
vector <int> cntInQueue(SIZE, 0);
vector <bool> onQueue(SIZE, false);
dist[start] = 0;
PQ.push(make_pair(start, 0));
onQueue[start] = true;
while (PQ.empty() == false)
{
int node = PQ.top().first;
cntInQueue[node]++;
PQ.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[node] + cost < dist[neighbour])
{
dist[neighbour] = cost + dist[node];
if (onQueue[neighbour] == false)
{
PQ.push(make_pair(neighbour, dist[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] << " ";
}
}
}