本文主要是介绍【CF1201】D. Treasure Hunting(dp动态规划),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:https://codeforces.com/problemset/problem/1201/D
分析
可以发现,若一行中所有的宝箱刚好都被拿完之后,只可能停在最左边或者最右边的宝箱。
那么该行的最左边的宝箱点可以从上一行的最左边或最右边的宝箱点的状态转移过来。
我们设 d p [ i ] [ 0 ] dp[i][0] dp[i][0]为刚好拿完前 i i i行宝箱后停留在第 i i i行最左端的宝箱的状态的最少步数, d p [ i ] [ 1 ] dp[i][1] dp[i][1]则为刚好拿完前 i i i行宝箱后停留在第 i i i行最右端的宝箱的状态的最少步数。
转移方程即为:
d p [ i ] [ 0 ] = m i n ( d p [ i − 1 ] [ 0 ] + d i s ( l [ i − 1 ] , r [ i ] ) , d p [ i − 1 ] [ 1 ] + d i s ( r [ i − 1 ] , r [ i ] ) ) + r [ i ] − l [ i ] ; dp[i][0] = min(dp[i - 1][0] + dis(l[i - 1], r[i]), dp[i - 1][1] + dis(r[i - 1], r[i])) + r[i] - l[i]; dp[i][0]=min(dp[i−1][0]+dis(l[i−1],r[i]),dp[i−1][1]+dis(r[i−1],r[i]))+r[i]−l[i];
d p [ i ] [ 1 ] = m i n ( d p [ i − 1 ] [ 0 ] + d i s ( l [ i − 1 ] , l [ i ] ) , d p [ i − 1 ] [ 1 ] + d i s ( r [ i − 1 ] , l [ i ] ) ) + r [ i ] − l [ i ] ; dp[i][1] = min(dp[i - 1][0] + dis(l[i - 1], l[i]), dp[i - 1][1] + dis(r[i - 1], l[i])) + r[i] - l[i]; dp[i][1]=min(dp[i−1][0]+dis(l[i−1],l[i]),dp[i−1][1]+dis(r[i−1],l[i]))+r[i]−l[i];
要知道从某行x位置到下一行y位置的步数,就从距离x位置两边最近的安全列上去取个小即可。
具体看代码
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define fi first
#define se second
#define lson (k << 1)
#define rson (k << 1 | 1)const ll LINF = 1e18;
const int INF = 1e9 + 7;
const int N = 2e5 + 10;
const int M = 1e6 + 10;
const ll P = 998244353;
const double eps = 1e-7;int n, m, k, q;
int l[N], r[N], sf[N];
ll dp[N][2];
vector<int> row;int dis(int x, int y)
{int res = INF;int qr = upper_bound(sf + 1, sf + 1 + q, x) - sf;int ql = qr - 1;if(ql > 0) res = min(res, abs(x - sf[ql]) + abs(y - sf[ql]));if(qr <= q) res = min(res, abs(x - sf[qr]) + abs(y - sf[qr]));return res;
}int main()
{ll ans = 0;scanf("%d%d%d%d",&n,&m,&k,&q);while(k--){int x, y;scanf("%d%d",&x,&y);if(l[x] == 0) l[x] = r[x] = y;else l[x] = min(l[x], y), r[x] = max(r[x], y);}for(int i=1;i<=q;i++) scanf("%d",&sf[i]);sort(sf + 1, sf + 1 + q);for(int i=1;i<=n;i++) if(l[i]) row.push_back(i);ans += row.back() - 1;if(row[0] == 1){dp[0][0] = r[row[0]] - 1 + r[row[0]] - l[row[0]];dp[0][1] = r[row[0]] - 1;}else{dp[0][0] = r[row[0]] - l[row[0]] + dis(1, r[row[0]]);dp[0][1] = r[row[0]] - l[row[0]] + dis(1, l[row[0]]);}for(int i=1;i<row.size();i++){dp[i][0] = min(dp[i - 1][0] + dis(l[row[i - 1]], r[row[i]]), dp[i - 1][1] + dis(r[row[i - 1]], r[row[i]])) + r[row[i]] - l[row[i]];dp[i][1] = min(dp[i - 1][0] + dis(l[row[i - 1]], l[row[i]]), dp[i - 1][1] + dis(r[row[i - 1]], l[row[i]])) + r[row[i]] - l[row[i]];}ans += min(dp[row.size() - 1][0], dp[row.size() - 1][1]);printf("%lld\n",ans);return 0;
}
这篇关于【CF1201】D. Treasure Hunting(dp动态规划)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!