Cod sursa(job #3238913)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 31 iulie 2024 15:12:56
Problema Car Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.39 kb
//DIAL

#include <bits/stdc++.h>

using namespace std;

ifstream in("car.in");
ofstream out("car.out");

const int nmax=505, inf=1e9, dir=8;
const int ox[]= {-1,-1,-1,0,1,1,1,0};
const int oy[]= {-1,0,1,1,1,0,-1,-1};
//  0  1 2 3 4 5 6  7
int n, m, xs, ys, xf, yf;
int rez;
bitset<nmax> a[nmax];
bitset <nmax> used[10][nmax];
queue<tuple<int,int,int>>q[4];//op 0, 1, 2
vector<vector<vector<int>>>d;
bool inMatrix(int i,int j)
{
    if(i>=1 && i<=n && j>=1 && j<=m)
        return 1;
    return 0;
}
void dial()
{
    int x, y, direction;
    int nx, ny, newdirection;
    int nrcoada=0, elements=dir;
    d.assign(dir,vector<vector<int>>(n+1,vector<int>(m+1,inf)));
    for(int i=0; i<dir; i++)
    {
        d[i][xs][ys]=0;
        q[0].push({i,xs,ys});
    }
    while(elements>0)
    {
        while(q[nrcoada].empty())
            nrcoada=(nrcoada+1)%3;
        tie(direction,x,y)=q[nrcoada].front();
        q[nrcoada].pop();
        elements--;
        if(used[direction][x][y]==0)
        {
            for (int k = -2; k < 3; k++)
            {
                if (k < 0)
                {
                    newdirection = (direction + k + 8) % dir;
                }
                else
                {
                    newdirection = (direction + k) % dir;
                }

                nx = x + ox[newdirection];
                ny = y + oy[newdirection];

                if (inMatrix(nx, ny) && a[nx][ny] == 0 && used[newdirection][nx][ny] == 0)
                {
                    int cost = (k < 0) ? d[direction][x][y] - k : d[direction][x][y] + k;
                    if (cost < d[newdirection][nx][ny])
                    {
                        d[newdirection][nx][ny] = cost;
                        elements++;
                        q[d[newdirection][nx][ny] % 3].push({newdirection, nx, ny});
                    }
                }
            }

            used[direction][x][y]=1;
        }
    }
}
int main()
{
    in>>n>>m;
    in>>xs>>ys>>xf>>yf;
    bool ce;
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=m; j++)
        {
            in>>ce;
            a[i][j]=ce;
        }
    }
    dial();
    rez=inf;
    for(int i=0; i<dir; i++)//verific toate directiile
    {
        rez=min(rez, d[i][xf][yf]);
    }
    if(rez==inf)
        out<<-1;
    else
        out<<rez;
    return 0;
}