Pagini recente » Cod sursa (job #2909029) | Cod sursa (job #1932469) | Cod sursa (job #1392139) | Cod sursa (job #1437835) | Cod sursa (job #2982682)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int SIZE = 50001;
const int INF = 1e9;
int n, x, y, z, m;
vector<pair<int,int>> gr[SIZE];
queue<int> qu;
vector<int> dist(SIZE, INF);
int inq[SIZE];
bool ok = 1;
void bllmn(int stnd)
{
dist[stnd] = 0;
qu.push(stnd);
inq[stnd] = 1;
while(!qu.empty())
{
int nod = qu.front();
qu.pop();
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(vec);
inq[vec]++;
}
if (inq[vec] >= n)
{
ok = 0;
fout<<"Ciclu negativ!";
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]<<" ";
}
}
}