Pagini recente » Cod sursa (job #1726392) | Cod sursa (job #1379079) | Cod sursa (job #2315052) | Cod sursa (job #2291176) | Cod sursa (job #2221876)
#include <fstream>
#include <vector>
#include <queue>
#define DIM 50005
#define inf 1000000005
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector < int > ls[DIM], lc[DIM];
int n, m, x, y, cost, i;
queue < int > Q;
int seen[DIM], cnt[DIM];
int main()
{
f >> n >> m;
while ( m -- )
{
f >> x >> y >> cost;
ls[x].push_back(y);
lc[x].push_back(cost);
}
for ( int i = 2 ; i <= n ; i ++ )
seen[i] = inf;
Q.push(1);
while (Q.empty()==0)
{
int old_n = Q.front();
Q.pop();
int l = ls[old_n].size();
for ( int i = 0 ; i < l ; i ++ )
{
int new_n = ls[old_n][i];
int new_c = lc[old_n][i];
if (seen[old_n]+new_c < seen[new_n])
{
seen[new_n] = seen[old_n]+new_c;
cnt[new_n]++;
Q.push(new_n);
}
if (cnt[new_n] >= n)
{
g << "Ciclu negativ!";
return 0;
}
}
}
for ( int i = 2 ; i <= n ; i ++ )
g << seen[i] << ' ';
return 0;
return 0;
}