Pagini recente » Cod sursa (job #10480) | Cod sursa (job #2617800) | Cod sursa (job #2868688) | Cod sursa (job #1649920) | Cod sursa (job #2941272)
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int maxn = 50005;
vector <pair <int, int> > v[maxn];
bitset <maxn> incoada;
int dist[maxn];
int fr[maxn];
int main()
{
int n, m;
in >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, cost;
in >> x >> y >> cost;
v[x].push_back(make_pair(y, cost));
}
for(int i = 2; i <= n; i++)
dist[i] = (1 << 30);
queue <int> q;
q.push(1);
while(!q.empty())
{
int nod = q.front();
q.pop();
incoada[nod] = 0;
fr[nod]++;
if(fr[nod] == n + 1) /// am gasit un ciclu negativ
{
out << "Ciclu negativ!" << "\n";
return 0;
}
for(auto it : v[nod])
{
if(dist[it.first] > dist[nod] + it.second)
{
dist[it.first] = dist[nod] + it.second;
if(!incoada[it.first])
{
q.push(it.first);
incoada[it.first] = 1;
}
}
}
}
for(int i = 2; i <= n; i++)
out << dist[i] << " ";
out << "\n";
return 0;
}