Pagini recente » Cod sursa (job #2318074) | Istoria paginii runda/agm-lagheta/clasament | Cod sursa (job #286565) | Cod sursa (job #813390) | Cod sursa (job #1690359)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
#define mult 9000000000
vector<pair<int,pair<int,int> > > muchii;
vector<pair<int,int> > liste[50001], heap;
int n, m, x, y, z, viz[50001];
long long dist[50001];
void solve()
{
int nod, distanta;
int pas = 0;
for( int i=2; i<=n; i++ )
dist[i]=mult;
dist[1] = 0;
heap.push_back( make_pair(0,1));
make_heap( heap.begin(), heap.end());
while ( !heap.empty() && pas <= n*m )
{
pas++;
pop_heap( heap.begin(), heap.end() );
nod = heap.back().second;
distanta = -(heap.back().first);
heap.pop_back();
viz[nod] = 0;
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( viz[it->first] == 0 )
{
viz[it->first] = 1;
heap.push_back(make_pair(-dist[it->first],it->first));
push_heap(heap.begin(), heap.end());
}
}
}
}
}
int ciclu()
{
for( vector<pair<int, pair<int,int> > >::iterator it=muchii.begin(); it!=muchii.end(); it++ )
if( dist[it->second.second] > it->first + dist[it->second.first])
return 1;
return 0;
}
int main()
{
in >> n >> m;
for( int i=1; i<=m; i++ )
{
in >> x >> y >> z;
muchii.push_back(make_pair(z,make_pair(x,y)));
liste[x].push_back(make_pair(y,z));
}
solve();
if( ciclu() )
{
out << "Ciclu negativ!";
}
else
{
for( int i=2; i<=n; i++ )
out << dist[i] << " ";
}
return 0;
}