Pagini recente » Cod sursa (job #2338412) | Cod sursa (job #976730) | Cod sursa (job #1921627) | Cod sursa (job #2321947) | Cod sursa (job #1277172)
#include <iostream>
#include <queue>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <fstream>
#define Nmax 50001
#define INF 0x3f3f3f3f
using namespace std;
void read_data(int &N, int &M, vector< pair<int,int> > G[])
{
ifstream f("bellmanford.in");
f>>N>>M;
int x,y,c;
for(int i = 1; i <= M ; ++i)
{
f>>x>>y>>c;
G[x].push_back( make_pair(y,c) );
}
f.close();
}
void bellmanford(int &N, vector< pair<int,int> > G[], int sol[], bool &ciclu)
{
queue<int> Q;
bitset<Nmax> in_q;
int cnt[Nmax];
fill(cnt+1, cnt + N + 1, 0);
in_q.reset();
Q.push(1);
sol[1] = 0;
in_q[1] = 1;
cnt[1] = 1;
while(!Q.empty())
{
int node = Q.front();
Q.pop();
in_q[node] = 0;
for(auto it = G[node].begin(); it != G[node].end(); ++it)
{
if(sol[node] + it->second < sol[it->first])
{
sol[it->first] = sol[node] + it->second;
++cnt[it->first];
if(cnt[it->first] > N+1)
{
ciclu = true;
return;
}
if(!in_q[it->first])
{
Q.push(it->first);
in_q[it->first] = 1;
}
}
}
}
}
int main()
{
vector< pair<int,int> > G[Nmax];
int N, M;
read_data(N, M, G);
int sol[Nmax];
bool ciclu = false;
fill(sol+1, sol+N+1, INF);
bellmanford(N, G, sol, ciclu);
ofstream g("bellmanford.out");
if(ciclu)
g<<"Ciclu negativ!";
else
for(int i=2;i<=N;++i)
g<<sol[i]<<" ";
g.close();
return 0;
}