Pagini recente » Cod sursa (job #123800) | Cod sursa (job #1880545) | Cod sursa (job #430053) | Cod sursa (job #1575052) | Cod sursa (job #2260431)
#include <iostream>
#include <stdio.h>
#include <queue>
#include <vector>
#define NMAX 50001
#define INFINIT 1000000000
struct muchie {
int nod ;
int cost ;
int folosit ;
};
struct nd {
int nod ;
};
using namespace std;
queue <nd> q ;
vector <muchie> mat [ NMAX + 1 ] ;
int dist [ NMAX + 1 ] ;
int ok ;
void bellmanford (int s, int n ) {
q.push({1}) ;
dist[1] = 0 ;
for (int i = 2 ; i <= n ; i++ )
dist[i] = INFINIT ;
while (!q.empty()) {
nd first = q.front() ;
q.pop() ;
for (muchie &elem : mat[first.nod] ) {
if (dist[first.nod] + elem.cost < dist[elem.nod] ) {
elem.folosit++;
if (elem.folosit == n )
ok = 1 ;
dist[elem.nod] = dist[first.nod] + elem.cost ;
q.push({elem.nod}) ;
}
}
}
}
int main() {
FILE *fin, *fout ;
fin = fopen ("bellmanford.in", "r" ) ;
fout = fopen ("bellmanford.out", "w" ) ;
int n, a, b, c, m, i ;
fscanf (fin, "%d%d", &n, &m ) ;
for (i = 0 ; i < m ; i++ ) {
fscanf (fin, "%d%d%d", &a, &b, &c ) ;
mat[a].push_back({b, c}) ;
}
ok = 0 ;
bellmanford(1, n) ;
if (ok == 1 )
fprintf (fout, "Ciclu negativ!" ) ;
else
for (i = 2 ; i <= n ; i++ )
fprintf (fout, "%d ", dist[i] ) ;
return 0;
}