Pagini recente » Cod sursa (job #2119963) | Cod sursa (job #2584067) | Cod sursa (job #1841276) | Cod sursa (job #872128) | Cod sursa (job #2589074)
#include <bits/stdc++.h>
#define N 50001
#define INF 0x3F3F3F3F
using namespace std;
bitset <N> enqueue;
vector <pair <int, int>> G[N];
array <int, N> dist, ct;
class cmp {
public:
bool operator () (const int &a, const int &b) {
return dist[a]>dist[b];
}
};
int main () {
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
ios::sync_with_stdio(false);
int n, m, i, j, c;
fin >> n >> m;
for (; m; m--) {
fin >> i >> j >> c;
G[i].push_back(make_pair(j, c));
}
dist.fill(INF);
priority_queue <int, vector <int>, cmp> Q;
Q.push(1);
enqueue[1]=ct[1]=1;
dist[1]=0;
while (!Q.empty()) {
auto save=Q.top();
Q.pop();
enqueue[save]=0;
for (auto it: G[save])
if (dist[it.first]>dist[save]+it.second) {
dist[it.first]=dist[save]+it.second;
Q.push(it.first);
enqueue[it.first]=1;
ct[it.first]++;
if (ct[it.first]==n) {
fout << "Ciclu negativ!";
return 0;
}
}
}
for (i=2; i<=n; i++)
fout << dist[i] << ' ';
return 0;
}