Pagini recente » Cod sursa (job #2578581) | Cod sursa (job #681112) | Cod sursa (job #3149276) | Cod sursa (job #1746104) | Cod sursa (job #2717146)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
typedef long long ll;
const ll lim = 50000;
const ll INF = 20000000000LL;
int n, m;
vector<pair<int, int>> l[lim+5];
ll dist[lim+5];
bitset<lim+5> inq;
int cnt[lim+5];
bool Bellman(int sursa)
{
for(int i=1; i<=n; i++)
dist[i] = INF;
dist[sursa] = 0;
queue<int> q;
q.push(sursa);
cnt[sursa]++;
inq[sursa] = 1;
while(!q.empty())
{
int nod = q.front();
q.pop();
inq[nod] = 0;
for(auto& edge : l[nod])
if(dist[nod] + edge.second < dist[edge.first])
{
dist[edge.first] = dist[nod] + edge.second;
if(inq[edge.first]==0)
{
if(cnt[edge.first] > n) return false;
inq[edge.first]=1;
q.push(edge.first);
cnt[edge.first]++;
}
}
}
return true;
}
int main()
{
in>>n>>m;
for(int i=1; i<=m; i++)
{
int x, y, c;
in>>x>>y>>c;
l[x].push_back(make_pair(y, c));
}
if(!Bellman(1))
out<<"Ciclu negativ!";
else
for(int i=2; i<=n; i++) out<<dist[i]<<' ';
return 0;
}