Cod sursa(job #1556999)

Utilizator algebristulFilip Berila algebristul Data 26 decembrie 2015 15:56:57
Problema Car Scor 60
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.64 kb
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>

using namespace std;

const int INF = 0x3f3f3f3f;
const int nmax = 505;

int n, m;
int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1};
queue<pair<pair<int, int>, int> > C[3];
bool u[nmax][nmax][8];
int ans = INF;
int a[nmax][nmax];
int d[nmax][nmax][8];

inline int cost(int pd, int nd) {
    if (nd < pd)
        swap(nd, pd);

    if (nd - pd < pd - nd + 8)
        return nd - pd;

    return pd - nd + 8;
}

bool valid(int x, int y) {
    return (x >= 1 && x <= n) && (y >= 1 && y <= m) && a[x][y] == 0;
}

int main() {
    int x1, y1, x2, y2;

    freopen("car.in", "r", stdin);
    freopen("car.out", "w", stdout);

    scanf("%d %d", &n, &m);
    scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            scanf("%d", &a[i][j]);
        }
    }

    memset(d, INF, sizeof(d));

    for (int k = 0; k < 8; k++) {
        int x = x1 + dx[k];
        int y = y1 + dy[k];

        if (valid(x, y)) {
            u[x][y][k] = 1;
            d[x][y][k] = 0;
            C[0].push(make_pair(make_pair(x, y), k));
        }
    }

    int cst = 0;
    while ((!C[0].empty() || !C[1].empty())) {
        while (!C[cst % 2].empty()) {
            int x = C[cst % 2].front().first.first;
            int y = C[cst % 2].front().first.second;
            int pd = C[cst % 2].front().second;
            C[cst % 2].pop();

            if (valid(x + dx[pd], y + dy[pd]) && d[x+dx[pd]][y+dy[pd]][pd] > d[x][y][pd]) {
                d[x+dx[pd]][y+dy[pd]][pd] = d[x][y][pd];
                if (!u[x + dx[pd]][y + dy[pd]][pd]) {
                    u[x + dx[pd]][y + dy[pd]][pd] = 1;
                    C[cst % 2].push(make_pair(make_pair(x + dx[pd], y + dy[pd]), pd));
                }
            }

            for (int diff = -1; diff <= 1; diff++) {
                if (!diff) continue;

                int k = pd + diff;
                if (k < 0) k += 8;
                if (k >= 8) k -= 8;

                if (d[x][y][k] > d[x][y][pd] + 1) {
                    d[x][y][k] = d[x][y][pd] + 1;
                    if (!u[x][y][k]) {
                        u[x][y][k] = 1;
                        C[(cst + 1) % 2].push(make_pair(make_pair(x, y), k));
                    }
                }
            }
        }
        cst++;
    }

    for (int k = 0; k < 8; k++) {
        ans = min(ans, d[x2][y2][k]);
    }
    if (ans == INF) {
        printf("-1\n");
    } else {
        printf("%d\n", ans);
    }

    return 0;
}