Cod sursa(job #1655837)

Utilizator cercVianuCerc Vianu cercVianu Data 18 martie 2016 13:28:32
Problema A+B Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.56 kb
#include <cstdio>
#include <queue>
#include <vector>

using std::vector;
using std::priority_queue;

const int MAX_N = 60;

int N, M;

struct cell {
  int l, c, cost;
  bool operator < (const cell &other) const {
    return this->cost > other.cost;
  }

  cell operator + (const cell &other) const {
    return (cell){this->l + other.l, this->c + other.c, this->cost + 1};
  }

  bool isInside() const {
    return 0 <= this->l && this->l < N &&
           0 <= this->c && this->c < M;
  }
};

const cell delta[] = {
    {-1,  0},
    { 0,  1},
    { 1,  0},
    { 0, -1},
};

const int MAX_DIR = sizeof(delta) / sizeof(cell);

int D[MAX_N][MAX_N];
int C[MAX_N][MAX_N];

int answer;

priority_queue <cell> heap;

int main(void) {
  int i, j;

  // citirea datelor
  scanf("%d %d", &N, &M);
  for (i = 0; i < N; ++i) {
    for (j = 0; j < M; ++j) {
      scanf("%d", &D[i][j]);
    }
  }

  // calcularea solutiei
  for (i = 0; i < N; i++) {
    for (j = 0; j < M; j++) {
      C[i][j] = D[i][j];
      heap.push((cell){i, j, D[i][j]});
    }
  }

   while (!heap.empty()) {
     cell nod = heap.top();
     heap.pop();

     if (C[nod.l][nod.c] == nod.cost) {
       for (i = 0; i < MAX_DIR; i++) {
         cell vecin = nod + delta[i];
         if (vecin.isInside()) {
           if (vecin.cost < C[vecin.l][vecin.c]) {
             C[vecin.l][vecin.c] = vecin.cost;
             heap.push(vecin);
           }
         }
       }
     }
   }

  // afisarea solutiei
  for (i = 0; i < N; ++i) {
    for (j = 0; j < N; ++j) {
      printf("%d ", C[i][j]);
    }
    printf("\n");
  }
  return 0;
}