Pagini recente » Cod sursa (job #1098393) | Rating Lita Andrei Rares (LitaAndrei) | Cod sursa (job #2348671) | Cod sursa (job #28953) | Cod sursa (job #1690541)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
#define mult 1000000000
vector<pair<int,int> > liste[50001];
vector<pair<int,pair<int,int> > > muc;
int n, m, x, y, z, t[50001], dist[50001], nod, distanta;
bool in_q[50001];
int main()
{
in >> n >> m;
bool neg = false;
for( int i=1; i<=m; i++ )
{
in >> x >> y >> z;
liste[x].push_back( make_pair(y,z));
}
for( int i=1; i<=n; i++ )
dist[i] = mult;
dist[1] = 0;
queue<pair<int,int> > q;
q.push(make_pair(1,0));
while( !q.empty() && neg == false )
{
nod = q.front().first;
distanta = q.front().second;
in_q[nod] = false;
q.pop();
for( vector<pair<int,int> >::iterator it = liste[nod].begin(); it!=liste[nod].end(); it++ )
if( dist[it->first] > distanta + it->second )
{
dist[it->first] = distanta + it->second;
if( !in_q[it->first] )
{
q.push( make_pair( it->first, dist[it->first ]));
t[it->first]++;
in_q[it->first] = true;
if( t[it->first] > n -1)
neg = true;
}
}
}
if( neg)
{
out << "Circuit negativ!";
return 0;
}
for( int i=2; i<=n; i++ )
out << dist[i] << " ";
}