一.队列小操作:
1.queue<int>q:建立int类型队列q
2.q.push(x):把x压进队尾
3.q.pop():弹出对首
4.q.front():查询队首
5.q.back():查询队尾
6.q.empty():查询队列是否为空(非空0,空1)
二.广搜(BFS):
以《洛谷》P1135,奇怪的电梯为例:
#include<bits/stdc++.h>
using namespace std;
int n, a, b, k[204];
bool vis[204];
struct pos {
int x, cost;
};
queue<pos>q;
int main() {
cin >> n >> a >> b;
for (int i = 1; i <= n; i++) {
cin >> k[i];
}
q.push(pos{a,0});
vis[a]=1;
pos now;
while(!q.empty()){
now=q.front();//取队首的值
q.pop();//弹出队首
if(now.x==b)break;
for(int sign=-1;sign<=1;sign+=2){//计算现阶段能到达楼层的BFS
int tmp=now.x+k[now.x]*sign;
if(tmp>=1&&tmp<=n&&!vis[tmp]){
q.push(pos{tmp,now.cost+1});
vis[tmp]=1;
}
}
}
if(now.x==b)cout<<now.cost;
else cout<<-1;
return 0;
}