Pagini recente » Istoria paginii runda/pgleague | Cod sursa (job #1018008) | Cod sursa (job #353697) | Istoria paginii runda/oji-10-2/clasament | Cod sursa (job #2423801)
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
#define inf 100000000;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int N, M;
vector< pair <int,int> >graf[50005];
queue<int>myheap;
int cost[50005],freq[50005],viz[50005];
int bellmanford()
{
for (int i = 1; i <= N; i++)
{
cost[i] = inf;
viz[i] = 0;
}
cost[1] = 0;
myheap.push(1);
while (!myheap.empty())
{
int x = myheap.front();
myheap.pop();
freq[x]++;
if (freq[x] > M) return 0;
viz[x] = 1;
int l = graf[x].size();
for (int i = 0; i < l; i++)
{
int y, c;
y = graf[x][i].first;
c = graf[x][i].second;
if (cost[y] > c + cost[x])
{
cost[y] = c + cost[x];
if (viz[y] == 0)
{
myheap.push(y);
viz[y] = 1;
}
}
}
}
return 1;
}
int main()
{
int x, y, c;
fin >> N >> M;
for (int i = 0; i < M; i++)
{
fin >> x >> y >> c;
graf[x].push_back(make_pair(y,c));
}
if(bellmanford()==1)
for (int i = 2; i <= N; i++)
fout << cost[i] << " ";
else fout << "Ciclu negativ!";
system("pause");
}