Pagini recente » Cod sursa (job #781316) | Cod sursa (job #2468362) | Cod sursa (job #2194183) | Cod sursa (job #217937) | Cod sursa (job #2225887)
#include<cstdio>
#include<cctype>
#include<vector>
#include<queue>
#define MAX_N 50000
#define BUF_SIZE 1 << 19
#define oo 0x3f3f3f3f
using namespace std;
vector<pair<int,int> >g[MAX_N+1];
int dist[MAX_N+1], cnt[MAX_N+1], n, m, pos = BUF_SIZE;
bool used[MAX_N+1], cycle;
char buf[BUF_SIZE];
queue<int>q;
inline char getChar(FILE* fin) {
if(pos == BUF_SIZE) {
fread(buf,1,BUF_SIZE,fin);
pos = 0;
}
return buf[pos++];
}
inline int read(FILE* fin) {
int semn ,res = 0;
char c;
semn = 1;
do {
c = getChar(fin);
if(c == '-')
semn = -semn;
}while(!isdigit(c));
do {
res = 10*res + c - '0';
c = getChar(fin);
}while(isdigit(c));
return res * semn;
}
void readGraph() {
int i, x, y, cost;
FILE* fin = fopen("bellmanford.in","r");
n = read(fin); m = read(fin);
for(i = 0; i < m; i++) {
x = read(fin); y = read(fin); cost = read(fin);
g[x].push_back(make_pair(y,cost));
}
fclose(fin);
}
void bellmanFord(int x) {
vector<pair<int,int> >::iterator it;
int i, node;
for(i = 1; i <= n; i++)
dist[i] = oo;
dist[x] = 0;
q.push(x);
used[x] = true;
while(!q.empty() && !cycle) {
node = q.front();
q.pop();
used[node] = false;
for(it = g[node].begin(); it != g[node].end(); it++) {
if(dist[(*it).first] > dist[node] + (*it).second) {
dist[(*it).first] = dist[node] + (*it).second;
if(!used[(*it).first]) {
used[(*it).first] = true;
q.push((*it).first);
if(++cnt[(*it).first] > n)
cycle = true;
}
}
}
}
}
void printDistances() {
FILE* fout = fopen("bellmanford.out","w");
bellmanFord(1);
if(!cycle) {
for(int i = 2; i <= n; i++)
fprintf(fout,"%d ",dist[i]);
fprintf(fout,"\n");
}
else fprintf(fout,"Ciclu negativ!\n");
fclose(fout);
}
int main() {
readGraph();
printDistances();
return 0;
}