Cod sursa(job #1715463)

Utilizator killer301Ioan Andrei Nicolae killer301 Data 10 iunie 2016 19:18:48
Problema Car Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.52 kb
#include <cstdio>
#include <vector>
#include <cstring>

using namespace std;

const int NMAX = 500;
const int INF = 2000000000;

int n, m;
int a[NMAX+5][NMAX+5];
int dp[NMAX+5][NMAX+5][10];
pair <int, int> start, finish;
int Ans;

struct nod
{
    int x, y, c;
    nod() {x=y=c=0;}
    nod(int a, int b, int cost)
    {
        x=a; y=b; c=cost;
    }
};

int abs(int x)
{
    return x>0 ? x : -x;
}

vector <nod> q[4];

int dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};

int main()
{
    freopen("car.in", "r", stdin);
    freopen("car.out", "w", stdout);
    int n, m;
    scanf("%d%d", &n, &m);
    scanf("%d%d%d%d", &start.first, &start.second, &finish.first, &finish.second);
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            scanf("%d", &a[i][j]);
    for(int i=1; i<=n; i++)
        for(int j=0; j<=m; j++)
            for(int k=0; k<10; k++)
                dp[i][j][k] = INF;
    for(int i=0; i<8; i++)
    {
        q[0].push_back(nod(start.first, start.second, i));
        dp[start.first][start.second][i] = 0;
    }
    for( int c = 0; q[0].size() + q[1].size() + q[2].size() + q[3].size() != 0; c ++ ) {
        while( q[c & 3].size() != 0 ) {
            nod node = q[c & 3][ q[c & 3].size() - 1 ];
            q[c & 3].pop_back();

            if( dp[ node.x ][ node.y ][ node.c ] < c )
                continue;
            if( node.x + dx[ node.c ] >= 1 && node.x + dx[ node.c ] <= n )
            if( node.y + dy[ node.c ] >= 1 && node.y + dy[ node.c ] <= m )
            if( a[ node.x + dx[ node.c ] ][ node.y + dy[ node.c ] ] == 0 )
            if( dp[ node.x + dx[ node.c ] ][ node.y + dy[ node.c ] ][ node.c ] > c ) {
                dp[ node.x + dx[ node.c ] ][ node.y + dy[ node.c ] ][ node.c ] = c;
                q[c & 3].push_back( {node.x + dx[ node.c ], node.y + dy[ node.c ], node.c } );
            }

            for( int p = -2, dir = ( node.c + 8 + p ) & 7; p <= 2; p ++, dir = ( dir + 1 ) & 7 ) {
                if( dp[ node.x ][ node.y ][ dir ] > dp[ node.x ][ node.y ][ node.c ] + abs(p) ) {
                    dp[ node.x ][ node.y ][ dir ] = dp[ node.x ][ node.y ][ node.c ] + abs(p);
                    q[ (c + abs(p)) & 3 ].push_back( {node.x, node.y, dir} );
                }
            }
        }
    }
    Ans = INF;
    for(int i=0; i<8; i++)
        Ans = min(Ans, dp[finish.first][finish.second][i]);
    if(Ans == INF)
        printf("-1\n");
    else printf("%d", Ans);
    return 0;
}