题意:
有一个n米长的井,一直青蛙要跳上去,然后井上面有些地方可以抓住,如果它在地面以下x的位置,它可以跳到0-a[x]之间的任何距离,跳了之后会下滑b[x]米,问你它跳到地面最少需要多少步。
思路:
BFS,判断它可以到达的地方。
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
int n;
int a[N], b[N];
bool vis[N];
struct node
{
int pre, now;
}tr[N];
void bfs()
{
queue<int> q;
q.push(n);
vis[n] = 1;
int dis = n;
while (!q.empty())
{
int now = q.front(); q.pop();
int tmp = now - a[now];
if (tmp >= dis) continue;///可以到达
///从now可以到达的地方
for (int i = tmp; i < dis; i ++)///现在的位置是i,遍历
{
int ne = i + b[i];///下滑
if (vis[ne]) continue;
vis[ne] = 1;
tr[ne] = {now, i};
q.push(ne);
}
dis = tmp;
}
}
void solve()
{
cin >> n;
for (int i = 0; i <= n; i ++) tr[i].pre = tr[i].now = -1;
for (int i = 1; i <= n; i ++) cin >> a[i];
for (int i = 1; i <= n; i ++) cin >> b[i];
bfs();
if (!vis[0]) puts("NO");
else
{
int x = 0;///最终的位置是在地平面。
vector<int> ans;
while (tr[x].pre != -1) { ans.push_back(tr[x].now); x = tr[x].pre; }
cout << ans.size() << endl;
for (int i = ans.size() - 1; i >= 0; i --) cout << ans[i] << ' ';
cout << endl;
}
}
int main()
{
std::ios::sync_with_stdio(false);
solve();
return 0;
}