Pagini recente » Cod sursa (job #2645681) | Cod sursa (job #2257975) | Cod sursa (job #2460794) | Cod sursa (job #3179601) | Cod sursa (job #2605172)
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
using namespace std;
int n;
int ap[50001];
int modif[50001];
int rasp[50001];
vector<pair<int,int> >muchii[250001];
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
void bellman_ford()
{
int inf=1000000000;
for(int i = 1; i <= n; ++i)
rasp[i] = inf;
queue<int>q;
q.push(1);
rasp[1] = 0;
ap[1] = 1;
while(!q.empty())
{
int nod = q.front();
q.pop();
ap[nod] = 0;
for(auto it : muchii[nod])
{
if(rasp[it.first] > rasp[nod] + it.second)
{
rasp[it.first] = rasp[nod] + it.second;
if(ap[it.first] == 0)
{
q.push(it.first);
ap[it.first] = 1;
}
modif[it.first]++;
if(modif[it.first] > n)
{
g <<"Ciclu negativ!";
return;
}
}
}
}
for(int i = 2; i <= n; ++i)
g << rasp[i] << " ";
}
int main()
{
int m;
f >> n >> m;
while(m--)
{
int x,y,cost;
f >> x >> y >> cost;
muchii[x].push_back({y,cost});
}
bellman_ford();
}