Pagini recente » Clasament plictiseala | Cod sursa (job #872849) | Cod sursa (job #1145844) | Cod sursa (job #1692836) | Cod sursa (job #1242291)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#define DIM 50010
#define INF 0x3f3f3f3f
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<pair<int, int> > G[DIM];
queue<int> q;
bitset<DIM> inQueue;
int D[DIM], Nr[DIM];
int n, m, x, y, cost;
int main()
{
fin >> n >> m;
for (int i = 1;i <= m; i++)
{
fin >> x >> y >> cost;
G[x].push_back({y, cost});
}
q.push(1);
inQueue[1] = 1;
D[1] = 0;
for (int i = 2; i <=n; i++)
D[i] = INF;
while ( !q.empty() )
{
x = q.front(); // nod
q.pop();
inQueue[x] = 0;
for (const auto& p : G[x])
{
y = p.first; cost = p.second;
if (D[y] > D[x] + cost)
{
D[y] = D[x] + cost;
if ( !inQueue[y] )
{
Nr[y]++;
if (Nr[y] == n)
{
fout<<"Ciclu negativ!";
return 0;
}
q.push(y);
inQueue[y] = 1;
}
}
}
}
for (int i = 2; i <= n; i++)
fout << D[i] << " ";
return 0;
}