Cod sursa(job #1556961)

Utilizator algebristulFilip Berila algebristul Data 26 decembrie 2015 15:05:17
Problema Car Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.15 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 = -1;
int a[nmax][nmax];

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]);
        }
    }

    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;
            if (x == x2 && y == y2)
                ans = 0;
            C[0].push(make_pair(make_pair(x, y), k));
        }
    }

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

            if (x == x2 && y == y2) {
                ans = cst;
                break;
            }

            for (int k = 0; k < 8; k++) {
                int l = cost(pd, k);
                int nx = x + dx[k];
                int ny = y + dy[k];
                if (l > 2) continue;
                if (!valid(nx, ny))
                    continue;

                if (!u[nx][ny][k]) {
                    C[(cst + l) % 3].push(make_pair(make_pair(nx, ny), k));
                    u[nx][ny][k] = 1;
                }
            }
        }
        cst++;
    }

    printf("%d\n", ans);

    return 0;
}