newcode wyh的吃鸡(优势队列+BFS)题解
思路:
要用优势队列,因为有的+2,有的+1,所以队列中的步长是不单调的,所以找到一个答案但不一定最小,所以用优势队列把小的放在队首。
要记录状态,所以开了三维,题目和昨天做的那道小明差不多
vis开的int型赋值bool型WA了半天
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define ll long long
using namespace std;
const int N = 100+5;
char mp[N][N];
int vis[3][N][N],k,x,y,n,to[4][2] = {0,1,0,-1,1,0,-1,0};
struct node{
int x,y;
int step,speed;
bool operator < (const node &a) const{
return step > a.step;
}
};
void BFS(){
priority_queue<node> q;
while(!q.empty()) q.pop();
node a,b;
a.x = x,a.y = y,a.speed = 2,a.step = 0;
vis[a.speed][a.x][a.y] = 1;
q.push(a);
while(!q.empty()){
a = q.top();
q.pop();
if(mp[a.x][a.y] == 'X' && a.step <= k){
printf("YES\n%d\n",a.step);
return;
}
for(int i = 0;i < 4;i++){
b.x = a.x + to[i][0];
b.y = a.y + to[i][1];
b.speed = a.speed;
if(b.x < 1 || b.y < 1 || b.x > n || b.y > n) continue;
if(mp[b.x][b.y] == 'O') continue;
if(vis[b.speed][b.x][b.y]) continue;
vis[b.speed][b.x][b.y] = 1;
b.step = a.step + b.speed;
if(mp[b.x][b.y] == 'C') b.speed = 1;
if(b.step <= k) q.push(b);
}
}
printf("NO\n");
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&k);
for(int i = 1;i <= n;i++){
scanf("%s",mp[i] + 1);
for(int j = 1;j <= n;j++){
if(mp[i][j] == 'S') x = i,y = j;
}
}
memset(vis,0,sizeof(vis));
BFS();
}
return 0;
}