Pagini recente » Cod sursa (job #1875898) | Cod sursa (job #1512830) | Cod sursa (job #355200) | Cod sursa (job #2196749) | Cod sursa (job #1337717)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
#define DIM 50010
#define INF 0x3f3f3f3f
ifstream is("bellmanford.in");
ofstream os("bellmanford.out");
vector <vector<pair<int, int>>> g;
vector <int> d;
bitset <DIM> inQueue;
queue <int> q;
int n, m;
int cnt[DIM];
bool work;
void Read();
void Solve();
void Write();
int main()
{
Read();
Solve();
if(!work)
Write();
is.close();
os.close();
return 0;
}
void Read()
{
is >> n >> m;
int x, y, z;
g = vector<vector<pair<int, int>>>(n+1);
d = vector<int>(n+1, INF);
for(int i = 1; i <= m; ++i)
{
is >> x >> y >> z;
g[x].push_back({y, z});
}
}
void Solve()
{
q.push(1);
d[1] = 0;
inQueue[1] = 1;
int x;
while(!q.empty())
{
x = q.front();
inQueue[x] = 0;
q.pop();
for(const auto & y : g[x])
{
if(d[y.first] > d[x] + y.second)
{
d[y.first] = d[x] + y.second;
if(!inQueue[y.first])
{
cnt[y.first]++;
if(cnt[y.first] == n)
{
os << "Ciclu negativ!";
work = true;
return;
}
q.push(y.first);
inQueue[y.first] = 1;
}
}
}
}
}
void Write()
{
for(int i = 2; i <= n; ++i)
{
os << d[i] << ' ';
}
return ;
}