Pagini recente » Cod sursa (job #499714) | Cod sursa (job #2675214) | Cod sursa (job #2649366) | Cod sursa (job #2883407) | Cod sursa (job #2606437)
#include <bits/stdc++.h>
#define newline '\n'
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
///***********************
#define neighbour first
#define cost second
const int OO = 0x3f3f3f3f;
const int NMAX = 5e4 + 3;
int n, m;
array<vector<pair<int, int>>, NMAX> lst;
array<int, NMAX> dis, nrVis;
array<bool, NMAX> inQ;
void read()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, z;
fin >> x >> y >> z;
lst[x].push_back(make_pair(y, z));
}
}
bool bellmanFord(int start)
{
fill(dis.begin(), dis.end(), OO);
dis[start] = 0;
inQ[start] = true;
queue<int> q;
q.push(start);
while (!q.empty())
{
int cnode = q.front();
q.pop();
nrVis[cnode]++;
if (nrVis[cnode] >= n)
return false;
inQ[cnode] = false;
for (auto it : lst[cnode])
{
if (dis[cnode] + it.cost < dis[it.neighbour])
{
dis[it.neighbour] = dis[cnode] + it.cost;
if (!inQ[it.neighbour])
{
q.push(it.neighbour);
inQ[it.neighbour] = true;
}
}
}
}
return true;
}
void display(bool hasCy)
{
if (hasCy)
fout << "Ciclu negativ!" << newline;
else
for (int i = 2; i <= n; i++)
fout << dis[i] << ' ';
}
int main()
{
read();
display(!bellmanFord(1));
fout.close();
return 0;
}