Cod sursa(job #1828869)

Utilizator TincaMateiTinca Matei TincaMatei Data 13 decembrie 2016 23:11:01
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#include <cstdio>
#include <ctype.h>
#include <queue>

const int MAX_MUCHIE = 250000;
const int MAX_N = 50000;
const int INF = 1000000000;
const int VALUTA = 500;
int mc[1+2*MAX_MUCHIE], next[1+MAX_MUCHIE], cost[1+MAX_MUCHIE];
int viz[1+MAX_N], dist[1+MAX_N];
bool ch[1+MAX_N];
int last[1+MAX_N];
bool inQ[1+MAX_N];

std::queue<int> d;

void addMuchie(int a, int b, int id, int c) {
  next[id] = last[a];
  last[a] = id;
  mc[id] = b;
  cost[id] = c;
}

class InParser {
private:
    FILE *fin;
    char *buff;
    int sp;

    char read_ch() {
        ++sp;
        if (sp == 4096) {
            sp = 0;
            fread(buff, 1, 4096, fin);
        }
        return buff[sp];
    }

public:
    InParser(const char* nume) {
        fin = fopen(nume, "r");
        buff = new char[4096]();
        sp = 4095;
    }

    InParser& operator >> (int &n) {
        char c;
        while (!isdigit(c = read_ch()) && c != '-');
        int sgn = 1;
        if (c == '-') {
            n = 0;
            sgn = -1;
        } else {
            n = c - '0';
        }
        while (isdigit(c = read_ch())) {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }

    InParser& operator >> (long long &n) {
        char c;
        n = 0;
        while (!isdigit(c = read_ch()) && c != '-');
        long long sgn = 1;
        if (c == '-') {
            n = 0;
            sgn = -1;
        } else {
            n = c - '0';
        }
        while (isdigit(c = read_ch())) {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }
}fin("bellmanford.in");

int main() {
  int n, m, a, b, c, x;
  bool nc;
  fin >> n >> m;
  for(int i = 1; i <= m; ++i) {
    fin >> a >> b >> c;
    addMuchie(a, b, i, c);
  }

  d.push(1);
  inQ[1] = true;

  dist[1] = 0;
  for(int i = 2; i <= n; ++i)
    dist[i] = INF;
  nc = false;
  while(!d.empty() && !nc) {
    x = d.front();
    ch[x] = true;
    d.pop();
    inQ[x] = false;
    if(viz[x] > VALUTA)
      nc = true;
    int i = last[x];
    while(i != 0) {
      if(dist[x] + cost[i] < dist[mc[i]]) {
        dist[mc[i]] = dist[x] + cost[i];
        viz[mc[i]]++;
        if(!inQ[mc[i]]) {
          d.push(mc[i]);
          inQ[mc[i]] = true;
        }
      }
      i = next[i];
    }
  }

  FILE *fout = fopen("bellmanford.out", "w");
  if(nc)
    fprintf(fout, "Ciclu negativ!");
  else
    for(int i = 2; i <= n; ++i)
      fprintf(fout, "%d ", dist[i]);
  fclose(fout);
  return 0;
}