Pagini recente » Cod sursa (job #2614768) | Cod sursa (job #1003260) | Cod sursa (job #2982570)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int SIZE = 50001;
const int INF = 1e9;
struct compare
{
bool operator()(pair<int,int> l, pair<int, int> r)
{
return l.second > r.second;
}
};
priority_queue<pair<int,int>, vector<pair<int,int>>, compare> qu;
vector<pair<int, int>> gr[SIZE];
vector<int> dist(SIZE, INF);
int n, m, x, y, z;
bool ok = 1, schimbari;
void bllmn(int stnd)
{
dist[stnd] = 0;
qu.push(make_pair(stnd, dist[stnd]));
for (int i = 1; i <= n; i++)
{
schimbari = 0;
qu.push(make_pair(stnd, dist[stnd]));
while (!qu.empty())
{
int nod = qu.top().first;
int distanta = qu.top().second;
qu.pop();
if (!(distanta > dist[nod]))
{
for (auto j: gr[nod])
{
int vec = j.first;
int cost = j.second;
if (dist[nod] + cost < dist[vec])
{
dist[vec] = dist[nod] + cost;
qu.push(make_pair(vec, dist[vec]));
schimbari = 1;
}
if ((dist[nod] + cost < dist[vec]) && i > n)
{
int ok = 0;
fout<<"Ciclu negativ!";
return;
}
}
}
}
if (schimbari == 0)
return;
}
}
int main()
{
fin>>n>>m;
for (int i = 1; i <= m; i++)
{
fin>>x>>y>>z;
gr[x].push_back(make_pair(y, z));
}
bllmn(1);
if (ok)
{
for (int i = 2; i <= n; i++)
{
fout<<dist[i]<<" ";
}
}
}