Pagini recente » Cod sursa (job #2347218) | Cod sursa (job #2554836)
#include <bits/stdc++.h>
#define INFINIT 1000000000
struct gogu {
int cost;
int nod;
};
std::vector< gogu >g[50001];
std::queue< int >q;
char inqueue[50001];
int d[50001], cl[50001];
int main() {
FILE *fin, *fout;
int n, m, i, a, b, c, ok = 1, x, y, dxy;
fin = fopen( "bellmanford.in", "r" );
fout = fopen( "bellmanford.out", "w" );
fscanf( fin, "%d%d", &n, &m );
for ( i = 0; i < m; i++ ) {
fscanf( fin, "%d%d%d", &a, &b, &c );
g[a].push_back( { c, b } );
}
for ( i = 2; i <= n; i++ )
d[i] = INFINIT;
d[1] = 0;
q.push( 1 );
while ( !q.empty() && ok ) {
x = q.front();
q.pop();
inqueue[x] = 0;
for ( i = 0; i < g[x].size(); i++ ) {
y = g[x][i].nod;
dxy = g[x][i].cost;
if ( d[x] + dxy < d[y] ) {
d[y] = d[x] + dxy;
cl[y]++;
if ( cl[y] == n )
ok = 0;
if ( inqueue[y] == 0 ) {
inqueue[y] = 1;
q.push( y );
}
}
}
}
if ( ok == 0 ) {
fprintf( fout, "Ciclu negativ!" );
} else {
for ( i = 2; i <= n; i++ )
fprintf( fout, "%d ", d[i] );
}
fclose( fin );
fclose( fout );
return 0;
}