Pagini recente » Cod sursa (job #2445327) | Cod sursa (job #993389) | Cod sursa (job #1882687) | Istoria paginii runda/simulareoji2020/clasament | Cod sursa (job #1899477)
#include <iostream>
#include <vector>
#include <set>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <queue>
#include <bitset>
using namespace std;
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define nmax 5005
#define inf 0x3f3f3f3f
vector<vector < pair<int,int> > >G(nmax);
bitset <nmax> mark;
int n,m,nr[nmax],d[nmax];
void read();
bool bellmanford();
void write();
int main()
{
read();
write();
return 0;
}
bool bellmanford(){
for(int i=2;i<=n;i++)
d[i] = inf;
d[1] = 0;
queue<int>Queue;
Queue.push(1);
while(!Queue.empty()){
int node = Queue.front();
Queue.pop();
nr[node]++;
if(nr[node] > n)
return false;
for(int i=0;i<G[node].size();++i){
long long sum = d[node] + G[node][i].s;
if(sum < d[G[node][i].f]){
d[G[node][i].f] = sum;
Queue.push(G[node][i].f);
}
}
}
return true;
}
void write(){
FILE * fout = fopen("bellmanford.out","w");
if(!bellmanford())
fprintf(fout,"Ciclu negativ!");
else
for(int i=2;i<=n;i++)
fprintf(fout,"%d ",d[i]);
}
void read(){
FILE * fin = fopen("bellmanford.in","r");
fscanf(fin,"%d %d", &n, &m);
for(int i=1;i<=m;i++){
int x,y,c;
fscanf(fin,"%d %d %d", &x, &y, &c);
G[x].pb(mp(y,c));
}
}