Pagini recente » Statistici Teste G (veruxy) | Cod sursa (job #2202806) | Monitorul de evaluare | Cod sursa (job #1514744) | Cod sursa (job #2423740)
#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],neg;
int bellmanford()
{
for (int i = 2; i <= N; i++)
cost[i] = inf;
cost[1] = 0;
myheap.push(1);
while (!myheap.empty())
{
int x = myheap.front();
myheap.pop();
freq[x]++;
if (freq[x]>M)
{
return 0;
}
else
{
int l = graf[x].size();
for (int i = 0; i < l; i++)
{
pair<int, int>vecin = graf[x][i];
if (cost[vecin.second] > cost[x] + vecin.first)
cost[vecin.second] = cost[x] + vecin.first;
myheap.push(vecin.second);
}
}
}
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(c, y));
}
if(bellmanford()==1)
for (int i = 2; i <= N; i++)
fout << cost[i] << " ";
else fout << "Ciclu negativ!";
system("pause");
}