Pagini recente » Cod sursa (job #1041198) | Cod sursa (job #645541) | Cod sursa (job #2115384) | Cod sursa (job #2360062) | Cod sursa (job #2568463)
#include <bits/stdc++.h>
using namespace std;
const int dim1 = 50010;
const int dim2 = 250010;
const int oo = (int) (1e9);
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
struct muchie
{
int x, y, c;
};
int n, m, dist[dim1];
bool ok;
muchie muchii[dim2];
void read()
{
in>>n>>m;
int x, y, c;
for(int i = 1;i <= m;i++)
{
in>>x>>y>>c;
muchii[i].x = x;
dist[x] = oo;
muchii[i].y = y;
dist[y] = oo;
muchii[i].c = c;
}
}
bool bellmanford()
{
dist[1] = 0;
for(int i = 1;i < n;i++)
{
for(int j = 1;j <= m;j++)
{
if(dist[muchii[j].y] > dist[muchii[j].x] + muchii[j].c)
dist[muchii[j].y] = dist[muchii[j].x] + muchii[j].c;
}
}
for(int i = 1;i <= m;i++)
{
if(dist[muchii[i].y] > dist[muchii[i].x] + muchii[i].c)
return false;
}
return true;
}
void print()
{
if(!ok)
out<<"Ciclu negativ!"<<'\n';
else
for(int i = 2;i <= n;i++)
out<<dist[i]<<' ';
}
int main()
{
read();
ok = bellmanford();
print();
return 0;
}