Pagini recente » Cod sursa (job #2502404) | Cod sursa (job #2189515) | Cod sursa (job #114160) | Cod sursa (job #1450467) | Cod sursa (job #1850779)
#include <fstream>
#include <vector>
#include <queue>
#define INF 2000000000
#define nMax 50001
#define pb push_back
#define mkp make_pair
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
int viz[nMax], dp[nMax], frecv[nMax];
vector<pair<int, int> > G[nMax];
queue<int> Q;
void bellmanFord()
{
for(int i=2; i<=n; i++)
dp[i]=INF;
Q.push(1);
while(!Q.empty())
{
int node=Q.front();
Q.pop();
viz[node]=0;
for(vector<pair<int, int> >::iterator it=G[node].begin(); it!=G[node].end(); it++)
{
int fiu=it->first;
int cost=it->second;
if(dp[node]+cost<dp[fiu])
{
dp[fiu]=dp[node]+cost;
frecv[fiu]++;
if(frecv[fiu]>=n)
{
fout<<"Ciclu negativ!";
return;
}
if(viz[fiu]==0)
{
viz[fiu]=1;
Q.push(fiu);
}
}
}
}
for(int i=2; i<=n; i++)
fout<<dp[i]<<" ";
}
int main()
{
int a, b, c;
fin>>n>>m;
for(int i=1; i<=m; i++)
{
fin>>a>>b>>c;
G[a].pb(mkp(b, c));
}
bellmanFord();
}