T4
这题颇似我们以前做过的抓住那头牛,一道基本的广搜题。
由 x -> x + 1
x -> x - 1
x -> 2 * x
WA90pts:
#include <bits/stdc++.h>
using namespace std;
int vis[200001];
int s,k;
struct st{
int x,dis;
};
void bfs(){
memset(vis,0,sizeof vis);
queue<st> q;
q.push({s,0});
while(!q.empty()){
st t = q.front();
q.pop();
if(t.x == k){
cout << t.dis<<'\n';
return;
}
for(int i = 1;i <= 3;i++){
int nx = t.x;
if(i == 1)nx ++;
if(i == 2)nx --;
if(i == 3)nx *= 2;
if(nx < 0 || nx > k * 2)continue; // 不一定x < y * 2
if(vis[nx])continue;
vis[nx] = 1;
q.push({nx,t.dis + 1});
}
}
}
int main(){
int T;
cin >>T;
while(T--){
cin >>s>>k;
bfs();
}
}
AC代码:
#include <bits/stdc++.h>
using namespace std;
int vis[300001];
int s,k;
struct st{
int x,dis;
};
void bfs(){
memset(vis,0,sizeof vis);
queue<st> q;
q.push({s,0});
while(!q.empty()){
st t = q.front();
q.pop();
if(t.x == k){
cout << t.dis<<'\n';
return;
}
for(int i = 1;i <= 3;i++){
int nx = t.x;
if(i == 1)nx ++;
if(i == 2)nx --;
if(i == 3)nx *= 2;
if(nx < 0 || nx > k * 3)continue;
if(vis[nx])continue;
vis[nx] = 1;
q.push({nx,t.dis + 1});
}
}
}
int main(){
int T;
cin >>T;
while(T--){
cin >>s>>k;
bfs();
}
}WA因:判定小了
T7
AC代码:
#include <bits/stdc++.h>
using namespace std;
int vis[1001][1001];
int h[1001][1001];
struct st{
int x,y,dis,hp;
};
queue<st> q;
int n,m;
int mx,my;
void bfs(){
while(!q.empty()){
st t = q.front();
q.pop();
if(t.x == mx && t.y == my){
cout << t.dis;
return;
}
if(t.hp <= 0)continue;//没体力了就躺地上
for(int i = 1;i <= 4;i++){
int nx = t.x,ny = t.y;
if(i == 1)nx ++;
if(i == 2)nx --;
if(i == 3)ny--;
if(i == 4)ny++;
if(nx < 1 || nx > n || ny < 1||ny > m)continue;
int hp = t.hp - 1;
if(vis[nx][ny] >= hp)continue;
//如果体力值比上次少就排掉
vis[nx][ny] = hp;
if(h[nx][ny] && hp > 0)hp = 6;//你过关!
q.push({nx,ny,t.dis + 1,hp});
}
}
cout << -1;//回不了家了QAQ
}
int main(){
cin >>n>> m;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
int c;
cin >> c;
if(c == 0){
vis[i][j] = 1e9;//无法跨越
}
if(c == 2){
vis[i][j] = 6;//6体力进去的
q.push({i,j,0,6});
}
if(c == 3){
mx = i,my = j;
}
if(c == 4){
h[i][j] = 1;//鼠标 * 1
}
}
}
bfs();
}
这道题一定要使用三维vis数组,因为在一个地点,可能有多个hp,我们需要保存最大hp,在
1 2 0 0 0
1 0 0 0 4
1 0 0 0 0
1 1 0 0 0
4 0 0 0 0
1 1 1 3 1这组样例在普通情况下,他会似在家门口,但先去加右边的血可以正常回家,这需要用三维vis数组保存hp。