Pagini recente » Cod sursa (job #1603062) | Cod sursa (job #120728) | Cod sursa (job #461379) | Cod sursa (job #2617042) | Cod sursa (job #2368148)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int maxn = 50005;
const int maxm = 250005;
const int inf = 2000000000;
int n, m, last;
int d[maxn];
bool ok[maxn];
struct muchie{
long a, b, c;
} e[maxm];
vector<int>A[maxn];
struct str{
int nod;
bool operator <(const str &other)const
{
return d[nod]>d[other.nod];
}
};
priority_queue<str>H;
void BellmanFord()
{
int nod, poz;
long long pas=0;
while(!H.empty() && pas<=1LL*n*m)
{
pas++;
//pop_heap(Heap.begin(),Heap.end());
//per=Heap.back();
// Heap.pop_back();
nod=H.top().nod;
H.pop();
ok[nod]=0;
for(auto it:A[nod])
{
if(d[e[it].a] + e[it].c < d[e[it].b])
{
d[e[it].b] = d[e[it].a] + e[it].c;
if(!ok[e[it].b])
{
ok[e[it].b]=1;
//Heap.push_back({-d[e[poz].b], e[poz].b});
H.push({e[it].b});
//push_heap(Heap.begin(),Heap.end());
}
}
}
}
}
int main()
{
long a,b,c;
fin>>n>>m;
for(long i=1; i<=m; i++)
{
fin>>e[i].a>>e[i].b>>e[i].c;
A[e[i].a].push_back(i);
}
for(long i=2; i<=n; i++)
d[i]=inf;
H.push({1});
BellmanFord();
for(int i=1; i<=m; i++)
{
if(d[e[i].a] + e[i].c < d[e[i].b])
{
fout<<"Ciclu negativ!\n";
return 0;
}
}
for(int i=2; i<=n; i++)
fout<<d[i]<<' ';
return 0;
}