Pagini recente » Cod sursa (job #620692) | Cod sursa (job #2667435) | Cod sursa (job #1267117) | Cod sursa (job #1047993) | Cod sursa (job #1402720)
#include <fstream>
#include <queue>
#include <vector>
#define INF 123456789
using namespace std;
int main()
{
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
vector<pair<long, long> > *graf;
queue<long> Q;
bool *in_queue, stop=false;
long *times_in_queue, *dist;
long n, m, a, b, c;
in>>n>>m;
graf = new vector<pair<long, long> >[n+1];
in_queue = new bool[n+1];
times_in_queue = new long[n+1];
dist = new long[n+1];
for(long i=0; i<m; ++i)
{
in>>a>>b>>c;
graf[a].push_back(make_pair(b, c));
}
for(long i=1; i<=n; ++i)
{
times_in_queue[i]=0;
in_queue[i]=false;
dist[i]=INF;
}
in_queue[1]=true;
dist[1]=0;
Q.push(1);
times_in_queue[1]=1;
while(!Q.empty()&&!stop)
{
a=Q.front();
Q.pop();
for(vector<pair<long, long> >::iterator it=graf[a].begin(), ed=graf[a].end(); it!=ed; ++it)
{
if(dist[it->first]>dist[a]+it->second)
{
dist[it->first]=dist[a]+it->second;
++times_in_queue[it->first];
if(times_in_queue[it->first]>n) stop=true;
if(!in_queue[it->first])
{
in_queue[it->first]=true;
Q.push(it->first);
}
}
}
}
if(stop) out<<"Ciclu negativ!\n";
else
for(long i=2; i<=n; ++i) out<<dist[i]<<' ';
in.close(); out.close();
return 0;
}