Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <inttypes.h>
- #include <string.h>
- enum { bigInt = 10000000000 };
- long long Abs(int c)
- {
- return (2 * (c > 0) - 1) * c * 1LL;
- }
- struct cell
- {
- int to;
- int cost;
- };
- struct heapA
- {
- long long size;
- struct cell *a;
- }H;
- void shiftDown(struct heapA *h, int i)
- {
- struct cell *b = NULL;
- b = h -> a;
- while(2 * i + 1 < (h -> size))
- {
- int l = 2 * i + 1;
- int r = 2 * i + 2;
- int j = l;
- if(r < h -> size && (*(b + r)).cost < (*(b + l)).cost)
- {
- j = r;
- }
- if((*(b + i)).cost <= (*(b + j)).cost)
- {
- break;
- }
- struct cell c;
- c = *(b + i);
- *(b + i) = *(b + j);
- *(b + j) = c;
- i = j;
- }
- }
- void shiftUp(struct heapA *h, int i)
- {
- struct cell *b = h->a;
- while(((b + i)->cost) < ((b + (i - 1)/2) -> cost))
- {
- struct cell c;
- c = *(b + i);
- *(b + i) = *(b + (i-1)/2);
- *(b + (i-1)/2) = c;
- i = (i - 1) / 2;
- }
- }
- struct cell extrMin(struct heapA *h)
- {
- struct cell m = *(h -> a);
- *(h -> a) = *(h -> a + h -> size - 1);
- (h -> size) -= 1;
- shiftDown(h, 0);
- return m;
- }
- void insert(struct heapA *h, struct cell value)
- {
- (h -> size) += 1;
- *((h -> a) + (h -> size) - 1) = value;
- shiftUp(h, (h->size) - 1);
- }
- const int dx[4] = {1, 0, -1 , 0};
- const int dy[4] = {0, 1, 0, -1};
- int main(void)
- {
- int n, m, x1, x2, y1, y2;
- scanf("%d%d%d%d%d%d", &n, &m, &y1, &x1, &y2, &x2);
- int *a = malloc(sizeof(int) * n * m);
- long long *d = malloc(n * m * sizeof(long long));
- H.a = malloc((n + 1) * (m + 1) * sizeof(struct cell));
- H.size = 0;
- for(int i = 0; i < n; i++)
- {
- for(int j = 0; j < m; ++j)
- {
- int x;
- scanf("%d", &x);
- *(a + i * m + j) = x;
- }
- }
- for(int i = 0; i < n; ++i)
- {
- for(int j = 0; j < m; ++j)
- {
- *(d + i * m + j) = bigInt;
- }
- }
- *(d + x1 + y1 * m) = 0;
- struct cell tmp = {x1 + y1 * m, 0};
- insert(&H, tmp);
- while(H.size)
- {
- struct cell t = extrMin(&H);
- int v = t.to;
- long long cst = t.cost;
- if(cst > *(d + v)) continue;
- int y = v / m;
- int x = v % m;
- for(int i = 0; i < 4; ++i)
- {
- if(x + dx[i] < m && x + dx[i] >= 0 && y + dy[i] >= 0 && y + dy[i]< n)
- {
- int to = x + dx[i] + (y + dy[i]) * m;
- long long path = Abs(*(a + v) - *(a + to));
- if(*(d + v) + path < *(d + to))
- {
- *(d + to) = *(d + v) + path;
- tmp.cost = *(d + to);
- tmp.to = to;
- insert(&H, tmp);
- }
- }
- }
- }
- printf("%lld", *(d + x2 + y2 * m));
- free(a);
- free(d);
- free(H.a);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement