Pagini recente » Cod sursa (job #2889492) | Cod sursa (job #2645959) | Cod sursa (job #1305321) | Cod sursa (job #2363274) | Cod sursa (job #2403562)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
#define to first
#define cost second
const int nmax = 5e4 + 5, inf = 1e9;
vector <pair <int, int> > v[nmax];
vector <int> d(nmax, inf);
bool ciclu_negativ = false;
int n, m, viz[nmax], x, y, c;
void bfs ()
{
queue <int> q;
int node;
q.push(1);
d[1] = 0;
while (!q.empty())
{
node = q.front();
q.pop();
if (viz[node] == n)
{
ciclu_negativ = true;
return;
}
viz[node]++;
for (int i=0; i<v[node].size(); ++i)
if (d[v[node][i].to] > d[node] + v[node][i].cost)
{
d[v[node][i].to] = d[node] + v[node][i].cost;
q.push(v[node][i].to);
}
}
}
int main()
{
fin >> n >> m;
while (m--)
{
fin >> x >> y >> c;
v[x].push_back(make_pair(y, c));
}
bfs();
if (ciclu_negativ)
{
fout << "Ciclu negativ!";
}
else
{
for (int i=2; i<=n; ++i)
fout << d[i] << ' ';
}
return 0;
}