Pagini recente » Cod sursa (job #1919735) | Cod sursa (job #1122426) | Cod sursa (job #242299) | Cod sursa (job #2660913) | Cod sursa (job #2819399)
#include <iostream>
#include <algorithm>
#include <functional>
#include <queue>
#include <vector>
#include <fstream>
#include <cstring>
using namespace std;
#define PAIR pair<int,int>
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int inf = 1e9;
int n,m;
int d[50001];
vector<vector<PAIR> > g(50001);
priority_queue<PAIR, vector<PAIR>,greater<PAIR>> pq;
int v[50001];
void djk(){
for(int i=1;i<=n;i++)
d[i] = inf;
d[1] = 0;
pq.push({0,1});
while(!pq.empty()){
PAIR p = pq.top();
int dist,nod;
dist = p.first;
nod = p.second;
pq.pop();
if(dist > d[nod])
continue;
for(auto next: g[nod]){
if(d[next.first] > dist + next.second){
d[next.first] = dist + next.second;
pq.push({d[next.first],next.first});
v[next.first] ++ ;
if(v[next.first] > n) {
out << "Ciclu negativ!\n";
exit(0);
}
}
}
}
}
int main()
{
in >> n >> m;
for(int i=1;i<=m;i++){
int a,b,c;
in >> a >> b >> c;
g[a].push_back(make_pair(b,c));
}
djk();
for(int i=2;i<=n;i++){
if(d[i] == inf)
out << 0;
else
out << d[i];
out <<" ";
}
return 0;
}