[USACO13OPEN]重力异常What’s Up With Gravity
最短路
题解:
按要求模拟,跑最短路。
Code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 505;
const int INF = 0x3f3f3f3f;
int n,m,g[N][N],sx,sy,tx,ty; char s[N];
int d[N][N][2]; bool vis[N][N][2];
struct State{
int x,y,op;
State(){}
State(int _x,int _y,int _op){ x=_x; y=_y; op=_op; }
};
queue<State> q;
void upd(State u,State v){
if(d[v.x][v.y][v.op] > d[u.x][u.y][u.op]){
d[v.x][v.y][v.op] = d[u.x][u.y][u.op] + (u.op==v.op?0:1);
if(!vis[v.x][v.y][v.op]){
vis[v.x][v.y][v.op]=true; q.push(v);
}
}
}
int spfa(){
memset(d,0x3f,sizeof(d));
memset(vis,false,sizeof(vis));
q.push(State(sx,sy,1)); vis[sx][sy][1]=true; d[sx][sy][1]=0;
while(!q.empty()){
State u=q.front(); q.pop(); vis[u.x][u.y][u.op]=false;
int dx=(u.op==1?1:-1);
if(u.x+dx>=1 && u.x+dx<=n){
if(g[u.x+dx][u.y]==0){
upd(u,State(u.x+dx,u.y,u.op));
}
else{
if(u.y+1<=m && g[u.x][u.y+1]==0){
upd(u,State(u.x,u.y+1,u.op));
}
if(u.y-1>=1 && g[u.x][u.y-1]==0){
upd(u,State(u.x,u.y-1,u.op));
}
upd(u,State(u.x,u.y,u.op^1));
}
}
}
return min(d[tx][ty][1],d[tx][ty][0]);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%s",s+1);
for(int j=1;j<=m;j++){
if(s[j]=='#') g[i][j]=1;
else g[i][j]=0;
if(s[j]=='C') sx=i, sy=j;
if(s[j]=='D') tx=i, ty=j;
}
}
int ans=spfa();
if(ans==INF) puts("-1");
else printf("%d\n",ans);
}