Pagini recente » Cod sursa (job #1878648) | Cod sursa (job #226780) | Monitorul de evaluare | Cod sursa (job #2078177) | Cod sursa (job #2260439)
#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 ;
bool 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() ;
//printf ("%d\n", mat[first.nod][0].folosit ) ;
for (muchie& elem : mat[first.nod] ) {
if (dist[first.nod] + elem.cost < dist[elem.nod] ) {
elem.folosit++;
//printf ("%d ", elem.folosit ) ;
if (elem.folosit == n ) {
ok = 1 ;
return -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;
}