Pagini recente » Cod sursa (job #2743654) | Cod sursa (job #1679676) | Cod sursa (job #2257294) | Cod sursa (job #716484) | Cod sursa (job #661380)
Cod sursa(job #661380)
#include <fstream>
#include <vector>
#include <deque>
#include <bitset>
#define NMAX 50020
#define INF 200000000
#define pb push_back
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
bitset<NMAX> inque;
struct muchie{
int nodul,costul;
};
muchie mm(int a,int b) {
muchie c;
c.nodul=a;c.costul=b;
return c;
}
int n,i,m,a,b,c;
vector <muchie> A[NMAX];
deque <int> D;
int cm[NMAX];
bool cneg=false;
void push(int nod,int cost) {
if (cm[nod]<cost) {return;}
if (inque[nod]) return;
cm[nod]=cost;
D.pb(nod);inque[nod]=1;
}
void afis() {
if (cneg) {g << "Ciclu negativ!" << '\n';return;}
for (i=2;i<=n;i++) g << cm[i] << ' ';
return;
}
int main () {
f >> n >> m;
for (i=1;i<=m;i++) {
f >> a >> b >> c;
A[a].pb(mm(b,c));
}
for (i=1;i<=n;cm[i]=INF,i++);
cm[1]=0;
D.pb(1);inque[1]=1;
while (!D.empty() && !cneg) {
int nod=D.front();D.pop_front();inque[nod]=false;
for (int j=0;j<A[nod].size() && !cneg;j++)
push(A[nod][j].nodul,cm[nod]+A[nod][j].costul);
}
afis();
f.close();g.close();
return 0;
}