Pagini recente » Cod sursa (job #1335745) | Cod sursa (job #1202960) | Cod sursa (job #2044360) | Cod sursa (job #3239558) | Cod sursa (job #1921869)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define DM 50005
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, a, b, c, viz[DM], dist[DM];
const int INF = (1 << 30);
bool inq[DM];
vector <pair<int, int> > g[DM];
queue <int> q;
void bellman_ford()
{
for(int i = 2; i <= n; i++)
dist[i] = INF;
inq[1] = 1;
q.push(1);
while(!q.empty())
{
int nod = q.front();
q.pop();
inq[nod] = 0;
for(auto it : g[nod])
if(dist[it.first] > dist[nod] + it.second)
{
dist[it.first] = dist[nod] + it.second;
viz[it.first]++;
if(!inq[nod])
{
if(viz[it.first] > n)
{
fout << "Ciclu negativ!";
return;
}
inq[it.first] = 1;
q.push(it.first);
}
}
}
for(int i = 2; i <= n; i++)
fout << dist[i] << ' ';
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
fin >> a >> b >> c;
g[a].push_back(make_pair(b,c));
}
bellman_ford();
return 0;
}