Pagini recente » Cod sursa (job #2274606) | Cod sursa (job #1019279) | Cod sursa (job #1744633) | Cod sursa (job #2157977) | Cod sursa (job #2434977)
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50005
#define mmax 250005
#define oo 2000000005
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
struct edges
{
long a;
long b;
long c;
}V[nmax];
long n, m, F[nmax + 5], i, j;
vector < long > D(nmax + 5, oo);
vector < long > P[nmax + 5];
priority_queue < pair < long, long > > Q;
void Bell()
{
pair < long, long > a;
long long cnt = 0;
while (!Q.empty() && cnt <= 1ll * n * m)
{
cnt++;
a = Q.top();
Q.pop();
long node = a.second;
F[node] = 0;
for (i = 0; i < P[node].size(); i++)
{
long pos = P[node][i];
if (D[V[pos].a] + V[pos].c < D[V[pos].b])
{
D[V[pos].b] = D[V[pos].a] + V[pos].c;
if (!F[V[pos].b])
{
F[V[pos].b] = 1;
Q.push({D[V[pos].b], V[pos].b});
}
}
}
}
}
bool Negativ()
{
for (long i = 1; i <= m; i++)
if (D[V[i].a] + V[i].c < D[V[i].b])
return true;
return false;
}
int main()
{
cin >> n >> m;
for (i = 1; i <= m; i++)
{
cin >> V[i].a >> V[i].b >> V[i].c;
P[V[i].a].push_back(i);
}
D[1] = 0;
Q.push({0, 1});
Bell();
if (Negativ()) return cout << "Ciclu negativ!\n", 0;
for (int i = 2; i <= n; i++) cout << D[i] << " ";
return 0;
}