Pagini recente » Cod sursa (job #2555357) | Cod sursa (job #2385865) | Cod sursa (job #2620384) | Cod sursa (job #848059) | Cod sursa (job #2574419)
#include <bits/stdc++.h>
using namespace std;
const int dim1 = 50001;
const int dim2 = 250001;
const int oo = (int) (1e9);
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n, m, dist[dim1], nr[dim1];
bool incoada[dim1];
vector<pair<int ,int> > muchii[dim1];
bool cmp(int a, int b)
{
return dist[a] < dist[b];
}
queue<int> q;
void read()
{
in>>n>>m;
for(int i = 1;i <= n;i++)
dist[i] = oo;
int x, y, c;
for(int i = 1;i <= m;i++)
{
in>>x>>y>>c;
muchii[x].push_back({y, c});
}
}
void bellman()
{
dist[1] = 0;
bool negativ = false;
q.push(1);
incoada[1] = true;
nr[1]++;
while(!q.empty() && !negativ)
{
int curent = q.front();
incoada[curent] = false;
q.pop();
for(vector<pair<int, int> >::iterator it = muchii[curent].begin(); it != muchii[curent].end();it++)
{
if(dist[it->first] > dist[curent] + it->second)
{
dist[it->first] = dist[curent] + it->second;
if(!incoada[it->first])
{
if(nr[it->first] > n)
negativ = true;
else
{
q.push(it->first);
incoada[it->first] = true;
nr[it->first]++;
}
}
}
}
}
if(negativ)
out<<"Ciclu negativ!";
else
for(int i = 2;i <= n;i++)
out<<dist[i]<<' ';
}
int main()
{
read();
bellman();
return 0;
}