Pagini recente » Cod sursa (job #473516) | Cod sursa (job #739546) | Cod sursa (job #1849846) | Cod sursa (job #625909) | Cod sursa (job #1292862)
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
using namespace std;
const int nmax = 50005;
const int inf = (1LL << 31) - 1;
int i, n, m, x, y, c, cnt[nmax], d[nmax];
vector<pii> v[nmax];
bitset<nmax> inq;
deque<int> q;
void bellman(int source)
{
for(i = 1; i <= n; i++)
d[i] = inf;
d[source] = 0;
q.push_back(source);
inq[source] = 1;
while(!q.empty())
{
x = q.front();
q.pop_front();
inq[x] = 0;
cnt[x]++;
if(cnt[x] == n)
{
printf("Ciclu negativ!\n");
return;
}
for(auto it : v[x])
if(d[x] + it.second < d[it.first])
{
d[it.first] = d[x] + it.second;
if(!inq[it.first])
{
q.push_back(it.first);
inq[it.first] = 1;
}
}
}
for(i = 1; i <= n; i++)
if(i != source)
printf("%d ", d[i]);
}
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
scanf("%d%d", &n, &m);
for(; m; m--)
{
scanf("%d%d%d", &x, &y, &c);
v[x].pb(mp(y, c));
}
bellman(1);
return 0;
}