Pagini recente » Cod sursa (job #289062) | Cod sursa (job #810171) | Cod sursa (job #2796745) | Cod sursa (job #1479739) | Cod sursa (job #1539570)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#define inf (1<<30)
using namespace std;
ifstream f("bellmanford.in");
ofstream go("bellmanford.out");
struct perechi{
int nod,cost;
}aux;
int x,y,c,n,m;
vector< vector<perechi> > g;
vector<bool> inq;
vector<int> used,dist;
queue<int> q;
bool bellman(int x)
{
q.push(x);
dist[x]=0;
used[x]=1;
inq[x]=true;
while (!q.empty())
{
x=q.front();
q.pop();
inq[x]=false;
for(int i=0; i<g[x].size(); i++)
{
int y=g[x][i].nod;
int c=g[x][i].cost;
if (dist[y]>dist[x]+c)
{
dist[y]=dist[x]+c;
if (!inq[y])
{
q.push(y);
inq[y]=true;
}
used[y]++;
if (used[y]>=n) return false;
}
}
}
return true;
}
int main()
{
f>>n>>m;
g.resize(n+1);
for(int i=0; i<=n; i++){
used.push_back(0);
inq.push_back(false);
dist.push_back(inf);
}
for(int i=1; i<=m; i++)
{
f>>x>>y>>c;
aux.nod=y;
aux.cost=c;
g[x].push_back(aux);
}
if (bellman(1)) for(int i=2; i<=n; i++) go<<dist[i]<<" ";
else go<<"Ciclu negativ!";
//go<<"test";
f.close();
go.close();
return 0;
}