Pagini recente » Cod sursa (job #734749) | Cod sursa (job #129700) | Cod sursa (job #1565863) | Cod sursa (job #1783928) | Cod sursa (job #2800843)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int NMAX = 5e4;
const int INF = 1e9;
queue <pair<int,int>> q;
vector <pair<int,int>> edges[NMAX + 1];
int dist[NMAX + 1];
int inQueue[NMAX + 1];
int cnt[NMAX + 1];
int BellmanFord( int node, int n ) {
q.push( {0,node} );
while ( !q.empty() ) {
int node = q.front().second;
int d = q.front().first;
q.pop();
inQueue[node] = false;
dist[node] = d;
for ( auto i : edges[node] ) {
if ( dist[i.second] > dist[node] + i.first ) {
dist[i.second] = dist[node] + i.first;
if ( !inQueue[i.second] ) {
q.push( {d + i.first,i.second} );
cnt[i.second] ++;
inQueue[i.second] = 1;
cout << i.second << endl;
if ( cnt[i.second] == n ) {
return 0;
}
}
}
}
}
return 1;
}
int main() {
ifstream fin( "bellmanford.in" );
ofstream fout( "bellmanford.out" );
int n, i, m, a, b, c;
fin >> n >> m;
for ( i = 0; i < m; i ++ ) {
fin >> a >> b >> c;
edges[a].push_back( {c,b} );
}
for ( i = 1; i <= n; i ++ )
dist[i] = INF;
if ( !BellmanFord( 1, n ) ) {
fout << "Ciclu negativ!";
} else {
for ( i = 2; i <= n; i ++ ) {
fout << dist[i] << ' ';
}
}
return 0;
}