Pagini recente » Cod sursa (job #3263590) | Cod sursa (job #824178) | Cod sursa (job #2912744) | Cod sursa (job #3205673) | Cod sursa (job #3198991)
#include <fstream>
#include <queue>
#include <vector>
#include <stdlib.h>
#define NMax 50005
#define pp pair<int,int>
#define inf 1e9
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n,m;
vector<pp> v[NMax];
int nr[NMax];
int cmin[NMax];
bool FoundNegativeCircuit;
void read()
{
in>>n>>m;
int x,y,c;
for(int i=1;i<=m;i++)
{
in>>x>>y>>c;
v[x].push_back({y,c});
}
}
queue<int>q;
void bellmanford(int start)
{
for(int i=1;i<=n;i++)
{
cmin[i] = inf;
}
cmin[start] = 0;
nr[start] = 1;
int x = start;
q.push(x);
while(!q.empty())
{
x = q.front();
q.pop();
if(nr[x] > n)
{
out<<"Ciclu negativ!\n";
exit(0);
}
for(auto i : v[x])
{
if(cmin[x] + i.second < cmin[i.first])
{
cmin[i.first] = cmin[x] + i.second;
nr[i.first] = nr[x] + 1;
q.push(i.first);
}
}
}
for(int i = 1;i<=n;i++)
{
if(i!=start)
{
out<<cmin[i]<<" ";
}
}
}
int main()
{
read();
bellmanford(1);
return 0;
}