问题链接:Problem H
问题简述:
一个人有d点能量,地图上有K个炮塔会分别朝4个方向射击,每隔时间t射出一颗速度为v的子弹,当t时刻时,人的坐标与子弹重合,人就会被射杀。求人能否从0,0走到m,n。若能,则求出最短路径。
问题分析:
由求最短路径可知会用到BFS算法。人每移动一步,每个炮塔射出的炮弹也会跟着刷新位置,若在BFS内虽然人移动而刷新,显然时间复杂度太高,不可取,于是可选择先预处理每个子弹在整个过程中会某个时刻会出现的位置,可用三维数组实现,同时要注意子弹可被炮塔当下。同时考虑到人有可能会因躲避子弹而折回以往走过的道路,因此标记数组应多加一个时间的维度。
AC通过的C++语言程序如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
int m,n,k,d;
bool bullet[105][105][1005],vis[105][105][1005];
int map[105][105];
int dir[5][2]={0,0,0,-1,0,1,-1,0,1,0};
struct node{
int x;
int y;
int step;
};
struct tank{
int d;
int t,v,x,y;
}tk[105];
void init(){
for(int i=0;i<k;i++){
for(int j=0;j<=d;j+=tk[i].t)
for(int k=1;;k++){
int nx=tk[i].x+k*dir[tk[i].d][0];
int ny=tk[i].y+k*dir[tk[i].d][0];
if(nx<0||ny<0||nx>n||ny>m||map[nx][ny]) break;
if(k%tk[i].v==0)
bullet[nx][ny][j+k/tk[i].v]=1;
}
}
}
bool edge(int x,int y){
if(x>=0&&y>=0&&x<=m&&y<=n&&map[x][y]==0){
return 1;
}
else{
return 0;
}
}
int BFS(){
queue<node>q;
node p1;
p1.x=0;
p1.y=0;
p1.step=0;
vis[0][0][0]=1;
q.push(p1);
while(!q.empty()){
node p2;
p2=q.front();
q.pop();
if(p2.step>d){
return -1;
}
else if(p2.x==m&&p2.y==n){
return p2.step;
}
for(int i=0;i<5;i++){
int next_x=p2.x+dir[i][0];
int next_y=p2.y+dir[i][1];
p1.step=p2.step+1;
if(edge(next_x,next_y)&&vis[next_x][next_y][p1.step]==0&&bullet[next_x][next_y][p1.step]==0){
p1.x=next_x;
p1.y=next_y;
vis[p1.x][p1.y][p1.step]=1;
q.push(p1);
}
}
}
}
int main(){
std::ios::sync_with_stdio(false);
while(cin>>m>>n>>k>>d){
char ch;
for(int i=0;i<k;i++){
cin>>ch>>tk[i].t>>tk[i].v>>tk[i].x>>tk[i].y;
if(ch=='W') tk[i].d=1;
if(ch=='N') tk[i].d=3;
if(ch=='S') tk[i].d=4;
if(ch=='E') tk[i].d=2;
map[tk[i].x][tk[i].y]=1;
}
init();
int ans;
memset(vis,0,sizeof(vis));
memset(map,0,sizeof(map));
memset(bullet,0,sizeof(bullet));
ans=BFS();
if(ans){
cout<<ans<<endl;
}
else{
cout<<"Bad luck!"<<endl;
}
}
}