Cod sursa(job #1164750)

Utilizator danny794Dan Danaila danny794 Data 2 aprilie 2014 12:00:49
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <cstdio>
#include <vector>
#include <algorithm>

#define MAX_INT (1<<30)

using namespace std;

struct edge {
  int to, cost;
};

const int NMAX = 50005;
int N, M, dist[NMAX], heap[NMAX], heap_count, index[NMAX];

vector<struct edge*> edges[NMAX];

void read() {
  freopen("dijkstra.in", "r", stdin);
  freopen("dijkstra.out", "w", stdout);
  scanf("%d %d", &N, &M);

  struct edge* new_edge;
  int from;
  for(int i = 1; i <= M; i++) {
    new_edge = new struct edge;
    scanf("%d%d%d", &from, &new_edge->to, &new_edge->cost);
    edges[from].push_back(new_edge);
  }

}

void init() {
  dist[1] = 0;
  heap[1] = 1;
  index[1] = 1;
  heap_count = N;
  for(int i = 2; i <= N; i++) {
    dist[i] = MAX_INT;
    heap[i] = i;
    index[i] = i;
  }
}

void down_heapify() {
  int idx = 1, min;
  while(true) {
    min = idx;
    if ((idx << 1) <= heap_count && dist[heap[idx << 1]] < dist[heap[min]])
      min = idx << 1;
    if ((idx << 1) < heap_count && dist[heap[(idx << 1) + 1]] < dist[heap[min]])
      min = (idx << 1) + 1;
    if (min == idx)
      return;
    else {
      swap(heap[idx], heap[min]);
      index[heap[idx]] = idx;
      index[heap[min]] = min;
      idx = min;
    }
  }
}

void up_heapify(int idx) {
  while((idx >> 1) > 0 && dist[heap[idx]] < dist[heap[idx >> 1]]) {
    swap(heap[idx], heap[idx >> 1]);
    index[heap[idx]] = idx;
    index[heap[idx >> 1]] = idx >> 1;
    idx >>= 1;
  }
}

int pop_heap() {
  swap(heap[1], heap[heap_count]);
  index[heap[1]] = 1;
  index[heap[heap_count]] = heap_count;
  heap_count--;
  down_heapify();
  return heap[heap_count + 1];
}

void solve() {
  int cost, to;
  while(heap_count != 0) {
    int from = pop_heap();

    for(unsigned int i = 0; i < edges[from].size(); i++) {
      to = edges[from][i]->to;
      cost = edges[from][i]->cost;
      if (dist[to] > cost + dist[from]) {
        dist[to] = cost + dist[from];
        up_heapify(index[to]);
      }
    }
  }
}

void print() {
  for(int i = 2; i <= N; i++)
    printf("%d ", dist[i] == MAX_INT ? 0 : dist[i]);
}

int main() {
  read();
  init();
  solve();
  print();
	return 0;
}