Pagini recente » Profil Mercioiu | Cod sursa (job #395945) | Cod sursa (job #3194840) | Monitorul de evaluare | Cod sursa (job #2162893)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int Inf = 0x3f3f3f3f;
using PII = pair<int, int>;
using VI = vector<int>;
vector<vector<PII>> G;
vector<int> d;
vector<int> nr;
vector<bool> v;
int N, M;
void Read();
int BellmanFord(int x, VI& d);
void Write();
int main()
{
Read();
BellmanFord(1, d);
Write();
return 0;
}
void Read()
{
fin >> N >> M;
G = vector<vector<PII>>(N + 1);
d.resize(N + 1, Inf);
v.resize(N + 1, false);
nr.resize(N + 1);
while(M--)
{
int x, y, cost;
fin >> x >> y >> cost;
G[x].push_back({y, cost});
}
fin.close();
}
int BellmanFord(int x, VI& d)
{
d[x] = 0;
v[x] = true;
queue<int> Q;
Q.push(x);
while(!Q.empty())
{
int newx = Q.front();
v[newx] = false;
for(auto y : G[newx])
if(d[newx] + y.second < d[y.first])
{
d[y.first] = d[newx] + y.second;
if(!v[y.first])
{
if(nr[y.first] > N)
{
fout << "Ciclu negativ!\n";
return 0;
}
Q.push(y.first);
v[y.first] = true;
++nr[y.first];
}
}
Q.pop();
}
}
void Write()
{
for(int i = 2; i <= N; ++i)
fout << d[i] << " ";
fout.close();
}