Pagini recente » Cod sursa (job #1175793) | Cod sursa (job #2716176) | Cod sursa (job #1502537) | Cod sursa (job #2562563) | Cod sursa (job #1337964)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream is("bellmanford.in");
ofstream os("bellmanford.out");
#define INF 0x3f3f3f3f
vector < vector < pair < int, int > > > v;
queue <int> Q;
bool oke[50001], cic_neg;
int nd[50001], cnt[50001], d[50001];
int n, m;
int x, y, z;
int nod, cost;
int main()
{
is >> n >> m;
v.resize(n+1);
for ( int i = 1; i <= m; ++i )
{
is >> x >> y >> z;
v[x].push_back(make_pair(y, z));
}
for ( int i = 2; i <= n; ++i )
d[i] = INF;
Q.push(1);
while ( !Q.empty() && !cic_neg )
{
x = Q.front();
Q.pop();
oke[x] = false;
for ( int i = 0; i < v[x].size(); ++i )
{
nod = v[x][i].first;
cost = v[x][i].second;
if ( d[nod] > d[x] + cost )
{
d[nod] = d[x] + cost;
if ( !oke[nod] )
{
if ( cnt[nod] > n )
cic_neg = true;
else
{
cnt[nod]++;
Q.push(nod);
oke[nod] = true;
}
}
}
}
}
if ( cic_neg )
os << "Ciclu negativ!";
else
for ( int i = 2; i <= n; ++i )
os << d[i] << ' ';
is.close();
os.close();
return 0;
}