Pagini recente » Cod sursa (job #2983850) | Cod sursa (job #463788) | Cod sursa (job #1819850) | Cod sursa (job #2838607) | Cod sursa (job #2302935)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
queue<int >q;
vector<pair<int,int> >graph[50005];
int n, m, from, to, cost, distante[50005], nr_coada[50005], ok=0;
bool in_coada[50005];
int rezolvare()
{
ok=0;
q.push(1);
in_coada[1]=true;
nr_coada[1]++;
while (!q.empty() && ok==0)
{
int nod_actual=q.front();
q.pop();
in_coada[nod_actual]=false;
for (auto &v:graph[nod_actual])
{
if (distante[nod_actual]+v.second<distante[v.first])
{
distante[v.first]=distante[nod_actual]+v.second;
if (!in_coada[v.first])
{
in_coada[v.first]=1;
nr_coada[v.first]++;
q.push(v.first);
if (nr_coada[v.first]>n)
{
return 0;
}
}
}
}
}
return 1;
}
int main() {
f >> n >> m;
for (int i=1; i<=m; i++)
{
f >> from >> to >> cost;
graph[from].push_back(make_pair(to,cost));
}
for (int i=2; i<=n; i++)
distante[i]=(1<<28);
if (rezolvare()==1)
{
for (int i=2; i<=n; i++)
{
g << distante[i] <<' ';
}
}
else
{
g << "Ciclu negativ!";
}
return 0;
}