Pagini recente » Cod sursa (job #2519988) | Cod sursa (job #2859742) | Cod sursa (job #3174155) | Cod sursa (job #229535) | Cod sursa (job #1342503)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
struct muchie
{
int y, c;
};
const int N = 50001;
const int INF = 2147483647;
int n, m;
int d[N], IT[N];
bool ok[N], CN;
vector<muchie> a[N];
queue<int> q;
void bellmanford(int x)
{
CN = 0;
for(int i = 1; i <= n; i++)
d[i] = INF;
d[x] = 0;
q.push(x);
ok[x] = 1;
while(!q.empty())
{
x = q.front();
q.pop();
ok[x] = 0;
for(size_t i = 0; i < a[x].size(); i++)
{
int y = a[x][i].y;
int c = a[x][i].c;
if(d[x] + c < d[y])
{
d[y] = d[x] + c;
if(ok[y] == 0)
{
q.push(y);
ok[y] = 1;
if(++IT[y] > n)
{
out << "Ciclu negativ!\n";
CN = 1;
return;
}
}
}
}
}
}
void citire()
{
in >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, c;
in >> x >> y >> c;
a[x].push_back((muchie){y, c});
}
}
void afisare()
{
for(int i = 2; i <= n; i++)
out << d[i] << ' ' ;
}
int main()
{
citire();
bellmanford(1);
if(!CN)
afisare();
return 0;
}