Pagini recente » Cod sursa (job #2055057) | Istoria paginii runda/eusebiu_oji_2017_cls11-12/clasament | Cod sursa (job #2148976) | Monitorul de evaluare | Cod sursa (job #608431)
Cod sursa(job #608431)
#include <cstdio>
#include <cstring>
#include <cstdlib>
// ATENTIE LA CITIRE!
#include <vector>
#include <queue>
#define f "bellmanford.in"
#define g "bellmanford.out"
#define nmax 50001
#define inf 0x3f3f3f
#define verf ++poz == hg ? fread ( ch, 1, hg, stdin ), poz = 0 : 0
#define hg 1 << 13
using namespace std;
vector < pair<int, int> > gf[nmax];
int d[nmax], viz[nmax], c_neg[nmax], n, m, poz;
char ch[hg];
inline void cit ( int &x ) {
int semn = 1;
if ( ch[0] == '\0' ) fread ( ch, 1, hg, stdin ) ;
else for ( ; (ch[poz] < '0' || ch[poz] > '9') && ch[poz] != '-' ; verf ) ;
for ( x = 0 ; ch[poz] >= '0' && ch[poz] <= '9' || ch[poz] == '-' ; (ch[poz] == '-' ? semn = -1 : x = x * 10 + ch[poz] - '0'), verf ) ;
x *= semn;
}
struct comp{
bool operator () (const int &a, const int &b){
return d[a]>d[b];
}
};
bool bellman_ford(){
memset(d, inf, sizeof(d));
viz[1]=1;
d[1]=0;
priority_queue<int, vector<int>, comp > Q;
for(Q.push(1); !Q.empty();){
int nod_princ = Q.top();
viz[nod_princ]=0;
Q.pop();
for(vector< pair<int, int> >::iterator it=gf[nod_princ].begin(); it!=gf[nod_princ].end(); it++){
int vecin = it->first;
int cost = it->second;
if (d[vecin] > d[nod_princ] + cost){
d[vecin] = d[nod_princ] + cost;
if(viz[vecin] == 0){
if(c_neg[vecin] > n)
return 1;
else {
Q.push(vecin);
c_neg[vecin]++;
viz[vecin]=1;
}
}
}
}
}
return 0;
}
int main(){
freopen(f, "r", stdin);
freopen(g, "w", stdout);
cit(n);cit(m);
for(int i=1; i<=m; i++){
int x, y, c;
cit(x); cit(y); cit(c);
gf[x].push_back(make_pair(y,c));
}
if (bellman_ford()==0)
for(int i=2; i<=n; i++)
if (d[i] >= inf) printf("0");
else printf("%d ",d[i]);
else printf("Ciclu negativ!");
return 0;
}