Pagini recente » Cod sursa (job #2520891) | Cod sursa (job #818190) | Cod sursa (job #2984266) | Cod sursa (job #1573511) | Cod sursa (job #640035)
Cod sursa(job #640035)
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 50002
#define oo (1<<30)
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
vector<pair<int,int> > V[NMAX];
vector<pair<int,int> >::iterator it,sf;
queue<int> Q;
int D[NMAX],App[NMAX],N,M;
int main()
{
int x,y,c;
in>>N>>M;
while(M--)
{
in>>x>>y>>c;
V[x].push_back(make_pair(y,c));
}
fill(D+2,D+N+1,oo);
for(Q.push(1);!Q.empty();Q.pop())
{
x = Q.front();
App[x]++;
if(App[x]>N)
{
out<<"Ciclu negativ!\n";
return 0;
}
for(it=V[x].begin(),sf=V[x].end();it<sf;++it)
{
y = it->first;
c = it->second;
if(D[y]>D[x]+c)
{
D[y] = D[x]+c;
Q.push(y);
}
}
}
for(x=2;x<=N;x++)
out<<(D[x]==oo?0:D[x])<<' ';
return 0;
}