CodeForces 676D Theseus and labyrinth

时间:2022-05-22 13:36:56

最短路。

$dis[i][j][k]$记录到点$(i,j)$,门的状态为$k$时的最短路。转移的时候有$8$种方案,即直接走向周围四个点,或者进行旋转。比较烦的是判断两个相邻的点在状态$k$下是否连通,仔细一些就可以了。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-;
void File()
{
freopen("D:\\in.txt","r",stdin);
freopen("D:\\out.txt","w",stdout);
}
template <class T>
inline void read(T &x)
{
char c=getchar(); x=;
while(!isdigit(c)) c=getchar();
while(isdigit(c)) {x=x*+c-''; c=getchar();}
} const int INF=0x7FFFFFFF;
const int maxn=;
int n,m,sx,sy,ex,ey;
char s[maxn][maxn];
int dir[][]={ {-,},{,},{,-},{,} };
int dis[maxn][maxn][];
bool f[maxn*maxn*];
int tmp[],tt[],p1[],p2[]; struct X
{
int st,dis;
X(int ST,int DIS){ st=ST; dis=DIS;}
bool operator <(const X&a) const
{
return dis>a.dis;
}
}; bool p(int x,int y)
{
if(x<||x>=n) return ;
if(y<||y>=m) return ;
if(s[x][y]=='*') return ;
return ;
} void get(int a,int b,int st)
{
memset(tmp,,sizeof tmp);
memset(tt,,sizeof tt); if(s[a][b]=='+') tmp[]=,tmp[]=,tmp[]=,tmp[]=;
else if(s[a][b]=='-') tmp[]=,tmp[]=;
else if(s[a][b]=='|') tmp[]=,tmp[]=; else if(s[a][b]=='^') tmp[]=;
else if(s[a][b]=='>') tmp[]=;
else if(s[a][b]=='v') tmp[]=;
else if(s[a][b]=='<') tmp[]=; else if(s[a][b]=='U') tmp[]=,tmp[]=,tmp[]=;
else if(s[a][b]=='R') tmp[]=,tmp[]=,tmp[]=;
else if(s[a][b]=='D') tmp[]=,tmp[]=,tmp[]=;
else if(s[a][b]=='L') tmp[]=,tmp[]=,tmp[]=; for(int i=;i<;i++) tt[(i+st)%]=tmp[i];
} bool check(int x1,int y1,int x2,int y2,int st)
{
get(x1,y1,st); for(int i=;i<;i++) p1[i]=tt[i];
get(x2,y2,st); for(int i=;i<;i++) p2[i]=tt[i]; if(x1==x2)
{
if(y1+==y2)
{
if(p1[]==&&p2[]==) return ;
return ;
}
else
{
if(p1[]==&&p2[]==) return ;
return ;
}
} else if(y1==y2)
{
if(x1+==x2)
{
if(p1[]==&&p2[]==) return ;
return ;
}
else
{
if(p1[]==&&p2[]==) return ;
return ;
}
} return ;
} void spfa()
{
for(int i=;i<n;i++)
for(int j=;j<m;j++)
for(int k=;k<;k++)
dis[i][j][k]=INF; dis[sx][sy][]=;
priority_queue<X>Q; Q.push(X(sx*m+sy,)); while(!Q.empty())
{
X top=Q.top(); Q.pop();
int st,r,c,h=top.st;
st=h/(n*m); h=h-st*(n*m); r=h/m; c=h%m; if(dis[r][c][st]<top.dis) continue; for(int i=;i<;i++)
{
int t=(st+i)%;
if(dis[r][c][st]+i<dis[r][c][t])
{
dis[r][c][t]=dis[r][c][st]+i;
Q.push(X(r*m+c+t*n*m,dis[r][c][t]));
}
} for(int i=;i<;i++)
{
int tx=r+dir[i][],ty=c+dir[i][];
if(p(tx,ty)==) continue;
if(check(r,c,tx,ty,st)==) continue; if(dis[r][c][st]+<dis[tx][ty][st])
{
dis[tx][ty][st]=dis[r][c][st]+;
Q.push(X(tx*m+ty+st*n*m,dis[tx][ty][st]));
}
}
}
} int main()
{
scanf("%d%d",&n,&m);
for(int i=;i<n;i++) scanf("%s",s[i]);
scanf("%d%d",&sx,&sy); sx--; sy--;
scanf("%d%d",&ex,&ey); ex--; ey--;
spfa();
int ans=INF;
for(int i=;i<;i++) ans=min(ans,dis[ex][ey][i]);
if(ans==INF) printf("-1\n");
else printf("%d\n",ans);
return ;
}