Codeforces Round #751 D Frog Traveler(dp)

博客介绍了Codeforces Round #751中的一道题目D Frog Traveler的解决方案。文章通过转换问题的视角,将问题转化为滑动和跳跃的结合,并使用动态规划的方法来求解。作者给出了详细的代码实现,包括关键的dp和fa数组更新,并通过队列进行状态转移。最后,当找到可行解时,输出路径的长度及路径节点,否则输出-1表示无解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Codeforces Round #751 D Frog Traveler(dp)

cf链接

Solution

我们先将跳跃的步骤转换一下,
即 将每次先跳到一个点,然后滑一段距离
看作 每次先滑下一段距离,再向上跳一段距离

在这里插入图片描述
参考:知乎https://zhuanlan.zhihu.com/p/425837640

代码

#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
//#define int long long
#define lowbit(x) ((x) & (-x))
using namespace std;
typedef pair<int, int> pii;
typedef pair<long, long> pll;
typedef pair<double, int> pdi;
typedef double dd;
typedef long long ll;
const int MAXN = 300010;
const int MAXM = 3000010;
const dd eps = 1e-6;
const int inf = 0x3f3f3f3f;
const ll llinf = 0x3f3f3f3f3f3f3f3f;

int a[MAXN], b[MAXN], dp[MAXN], fa[MAXN];

int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n;i++)
		cin >> a[i];
	for (int i = 1; i <= n;i++)
		cin >> b[i];
	int last = n;
	queue<int> q;
	q.push(n);
	while(q.size())
	{
		int u = q.front();
		q.pop();
		int v = u + b[u];
		if (v - a[v] <= 0)
		{
			vector<int> ans;
			ans.push_back(0);
			int now = u;
			while(now!=n)
				ans.push_back(now), now = fa[now];
			reverse(ans.begin(), ans.end());
			printf("%d\n", ans.size());
			for(int i:ans)
				printf("%d ", i);
			printf("\n");
			return 0;
		}
		for (int i = min(v, last - 1); i >= v - a[v]; i--)
		{
			dp[i] = dp[u] + 1;
			fa[i] = u;
			q.push(i);
		}
		last = min(v - a[v], last);
	}
	printf("-1\n");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值