Pagini recente » Cod sursa (job #2435002) | Cod sursa (job #2410640) | Cod sursa (job #247464) | album2 | Cod sursa (job #2462669)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 50005, MAXM = 250005;
struct conexiune{
int x, y, c;
} graf[MAXM];
int dist[MAXN], copie[MAXN];
int main()
{
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
fin >> n >> m;
for(int i = 1; i <= m; ++i)
fin >> graf[i].x >> graf[i].y >> graf[i].c;
int iter = n - 1;
for(int i = 2; i <= n; ++i) dist[i] = 1e9;
while(iter){
for(int i = 1; i <= m; ++i)
dist[graf[i].y] = min(dist[graf[i].y], dist[graf[i].x] + graf[i].c);
iter--;
}
for(int i = 1; i <= n; ++i) copie[i] = dist[i];
for(int i = 1; i <= m; ++i) copie[graf[i].y] = min(copie[graf[i].y], copie[graf[i].x] + graf[i].c);
bool ok = 0;
for(int i = 1; i <= n; ++i) if(dist[i] == copie[i]) ok = 1;
if(ok){
for(int i = 2; i <= n; ++i)
fout << dist[i] << " ";
}
else fout << "Ciclu negativ!";
return 0;
}