Cod sursa(job #1812984)

Utilizator TincaMateiTinca Matei TincaMatei Data 22 noiembrie 2016 16:49:55
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <cstdio>

const int MAX_MUCHIE = 250000;
const int MAX_N = 50000;
const int INF = 1000000000;
int mc[1+2*MAX_MUCHIE], next[1+MAX_MUCHIE], cost[1+MAX_MUCHIE];
int dist[1+MAX_N], last[1+MAX_N];

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

int heapS;
int heap[MAX_N], poz[1+MAX_N];

int root() {
  return heap[0];
}

bool cmp(int a, int b) {
  return dist[a] < dist[b];
}

void swap(int *a, int *b) {
  int aux;
  aux = *a;
  *a = *b;
  *b = aux;
}

void swapHeap(int p1, int p2) {
  swap(&heap[p1], &heap[p2]);
  swap(&poz[heap[p1]], &poz[heap[p2]]);
}

void add(int e) {
  int i = heapS;
  heapS++;
  heap[i] = e;
  poz[e] = i;
  while(i > 0 && cmp(heap[i], heap[i / 2])) {
    swapHeap(i, i / 2);
    i = i / 2;
  }
}

void erase(int pos) {
  int i = pos;
  int targ;
  poz[heap[pos]] = -1;
  swapHeap(i, heapS - 1);
  heapS--;
  while(i < heapS) {
    targ = i;
    if(i * 2 + 1 < heapS && cmp(heap[i * 2 + 1], heap[targ]))
      targ = i * 2 + 1;
    if(i * 2 + 2 < heapS && cmp(heap[i * 2 + 2], heap[targ]))
      targ = i * 2 + 2;

    if(targ == i)
      i = heapS;
    else {
      swapHeap(i, targ);
      i = targ;
    }
  }
}

int main() {
  int n, m, a, b, c, x;
  FILE *fin = fopen("dijkstra.in", "r");
  fscanf(fin, "%d%d", &n, &m);
  for(int i = 1; i <= m; ++i) {
    fscanf(fin, "%d%d%d", &a, &b, &c);
    addMuchie(a, b, i, c);
  }
  fclose(fin);

  add(1);
  for(int i = 2; i <= n; ++i) {
    dist[i] = INF;
    add(i);
  }

  while(heapS > 0) {
    x = root();
    erase(0);
    int i = last[x];
    while(i != 0) {
      if(dist[x] + cost[i] < dist[mc[i]]) {
        dist[mc[i]] = dist[x] + cost[i];
        if(poz[mc[i]] != -1)
          erase(poz[mc[i]]);
        add(mc[i]);
      }
      i = next[i];
    }
  }

  FILE *fout = fopen("dijkstra.out", "w");
  for(int i = 2; i <= n; ++i)
    fprintf(fout, "%d ", dist[i]);
  fclose(fout);
  return 0;
}