Cod sursa(job #3276600)

Utilizator tudor_costinCostin Tudor tudor_costin Data 13 februarie 2025 21:42:52
Problema Car Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.3 kb
#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];
        }
    }
    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;
        }
        for(int k=0; k<8; k++)
        {
            int newi=i+dx[k];
            int newj=j+dy[k];
            ///cout<<newi<<' '<<newj<<' '<<d[newi][newj][k]<<'\n';
            int turn;
            /// 0 degree "turn"
            if(abs(k-dr)==0 || dr==-1) turn=0;
            /// 45 degree turn
            else if(abs(k-dr)==1 || abs(k-dr)==7) turn=1;
            ///90 degree turn
            else if(abs(k-dr)==2 || abs(k-dr)==6) turn=2;
            /// 135 degree turn
            else if(abs(k-dr)==3 || abs(k-dr)==5) turn=3;
            ///180 degree turn
            else if(abs(k-dr)==4) turn=4;
            if(inmat(newi,newj))
            {
                ///cout<<newi<<' '<<newj<<' '<<d[newi][newj][k]<<'\n';
                if(d[newi][newj][k]==0 || d[newi][newj][k]>cost+turn)
                {
                    d[newi][newj][k]=cost+turn;
                    if(inmat(newi,newj) && !viz[newi][newj][k])
                    {
                        pq.push({newi,newj,cost+turn,k});
                    }
                }
            }
        }
    }
    fout<<-1<<'\n';
    return 0;
}