从前有一只鸽子。它生活在一个 N×MN \times MN×M 的网格里。网格从 000 开始标号, 有些网格是山,剩下的是平地。
他最开始在 (stx,sty)(stx,sty)(stx,sty ), 拥有 k 点体力。
每轮鸽子可以选择两个操作。
令CurK 为鸽子当前体力, 鸽子可以选择向上向下向左向右四个方向之一飞 CurK 的距离。注意鸽子不能飞出边界外,并且终点必须不能是山,但它可以飞越山。 CurK−1
现在鸽子发现他在 (edx,edy)(edx,edy)(edx,edy) 有个约会, 请问他能不能以自己无法到达为理由咕掉这个约会。
题解:
这题是一个不错的
BFS
练习题, 注意到我们倒过来做会更简单一些。
我们把每个点拆成四个点, 分别表示这个点是从哪里转移来的, 然后我们要求到达每个点所需
的能量最小值
如果我们当前在
(x,y)
, 从
where
转移来, 那么我们有两种转移
1. 转移到
(x+dx[where],y+dy[where],where)
, 更新答案为
CurK+1
2. 如果
(x,y)
处无山, 则分别向四个方向距离为
K
的点转移, 更新答案为
注意到第一种转移因为记录了从哪转移来, 所以显然是正确的, 我们也可以证明这些转移就是
充分必要的
具体实现细节可以参看 std
#include<bits/stdc++.h>
using namespace std;
inline int rd(){
char ch=getchar();int i=0,f=1;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){i=(i<<1)+(i<<3)+ch-'0';ch=getchar();}
return i*f;
}
const int Maxn=2e3+50;
int n,m,k,stx,sty,edx,edy,vis[Maxn][Maxn][5],ban[Maxn][Maxn];
struct node{
int x,y,ob;
node(int x,int y,int ob):x(x),y(y),ob(ob){}
};
vector<node>vv[Maxn];
const int fx[5]={0,1,-1,0,0};
const int fy[5]={0,0,0,1,-1};
inline bool check(int x,int y,int ob,int t){
return x>0&&x<=n&&y>0&&y<=m&&vis[x][y][ob]>t;
}
inline void upt(int t){
queue<node>q;
for(int i=0;i<vv[t].size();i++)if(vis[vv[t][i].x][vv[t][i].y][vv[t][i].ob]==t)q.push(vv[t][i]);
while(!q.empty()){
node u=q.front();q.pop();
if(ban[u.x][u.y])continue;
for(int i=1;i<=4;i++){
int xx=u.x+fx[i]*t,yy=u.y+fy[i]*t;
if(check(xx,yy,i,t))vis[xx][yy][i]=t,q.push(node(xx,yy,i)),vv[t].push_back(node(xx,yy,i));
}
}
for(int i=0;i<vv[t].size();i++)if(vis[vv[t][i].x][vv[t][i].y][vv[t][i].ob]==t)q.push(vv[t][i]);
while(!q.empty()){
node u=q.front();q.pop();
int xx=u.x+fx[u.ob],yy=u.y+fy[u.ob];
if(check(xx,yy,u.ob,t+1))vis[xx][yy][u.ob]=t+1,vv[t+1].push_back(node(xx,yy,u.ob));
}
}
int main(){
n=rd(),m=rd(),k=rd();
memset(vis,0x3f,sizeof(vis));
stx=rd()+1,sty=rd()+1,edx=rd()+1,edy=rd()+1;
for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)ban[i][j]=rd();
for(int i=1;i<=4;i++)vv[0].push_back(node(edx,edy,i)),vis[edx][edy][i]=0;
for(int i=0;i<=k;i++){
upt(i);for(int i=1;i<=4;i++)if(vis[stx][sty][i]<=k){puts("Possible");return 0;}
}
puts("Impossible");
}