Cod sursa(job #3276602)

Utilizator tudor_costinCostin Tudor tudor_costin Data 13 februarie 2025 21:55:15
Problema Car Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.48 kb
#pragma GCC optimize("Ofast")
#pragma GCC target("avx2")
#include <bits/stdc++.h>

using namespace std;
ifstream fin("car.in");
ofstream fout("car.out");
const int dx[]= {-1,-1,0,1,1,1,0,-1};
const int dy[]= {0,1,1,1,0,-1,-1,-1};
const int Nmax=505;
bool a[Nmax][Nmax];
bool viz[Nmax][Nmax][10];
int d[Nmax][Nmax][10];
struct celula
{
    short int x,y;
    int val;
    short int dir;
    bool operator <(const celula cmp) const
    {
        return val>cmp.val;
    }
};
int n,m;
bool inmat(int i,int j)
{
    return (1<=i && i<=n && 1<=j && j<=m);
}
int main()
{
    fin>>n>>m;
    int sx,sy,fx,fy;
    fin>>sx>>sy>>fx>>fy;
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=m; j++)
        {
            fin>>a[i][j];
            for(int k=0; k<8; k++) d[i][j][k]=INT_MAX;
        }
    }
    priority_queue<celula> pq;
    pq.push({sx,sy,0,-1});
    while(!pq.empty())
    {
        int i=pq.top().x;
        int j=pq.top().y;
        int dr=pq.top().dir;
        int cost=pq.top().val;
        pq.pop();
        if(a[i][j]==1) continue;
        if(viz[i][j][dr]) continue;
        viz[i][j][dr]=0;
        ///cout<<i<<' '<<j<<' '<<dr<<' '<<cost<<'\n';
        if(i==fx && j==fy)
        {
            fout<<cost<<'\n';
            return 0;
        }
        if(inmat(i+dx[dr],j+dy[dr]))pq.push({i+dx[dr],j+dy[dr],cost,dr});
        for(int turn=1; turn<=4; turn++)
        {
            int aux=turn,auxdr=dr;
            bool ok=0;
            if(dr==-1)
            {
                dr=0;
                ok=1;
            }
            int newdr=(dr+turn)%8;
            int newdr2=(dr+8-turn)%8;
            if(ok) turn=0;
            int newi=i;
            int newj=j;
            if(d[newi][newj][newdr]>cost+turn)
            {
                d[newi][newj][newdr]=cost+turn;
                if(inmat(newi,newj) && !viz[newi][newj][newdr])
                {
                    pq.push({newi,newj,cost+turn,newdr});
                }
            }
            if(newdr!=newdr2)
            {
                if(d[newi][newj][newdr2]>cost+turn)
                {
                    d[newi][newj][newdr2]=cost+turn;
                    if(inmat(newi,newj) && !viz[newi][newj][newdr2])
                    {
                        pq.push({newi,newj,cost+turn,newdr2});
                    }
                }
            }
            turn=aux;
            dr=auxdr;
        }
    }
    fout<<-1<<'\n';
    return 0;
}