Pagini recente » Cod sursa (job #1212075) | Cod sursa (job #1619727) | Cod sursa (job #2696254) | Cod sursa (job #2821637) | Cod sursa (job #1690559)
#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<int> q;
q.push(1);
t[1]++;
in_q[1] = true;
while( !q.empty())
{
nod = q.front();
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] > dist[nod] + it->second )
{
dist[it->first] = it->second + dist[nod];
if( !in_q[it->first] )
{
q.push( it->first);
t[it->first]++;
in_q[it->first] = true;
if( t[it->first] > n )
{
neg = true;
out << "Ciclu negativ!";
return 0;
}
}
}
}
if( neg)
{
out << "Circuit negativ!";
return 0;
}
for( int i=2; i<=n; i++ )
out << dist[i] << " ";
}