B - Frog 2
Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 100100 points
Problem Statement
There are NN stones, numbered 1,2,…,N1,2,…,N. For each ii (1≤i≤N1≤i≤N), the height of Stone ii is hihi.
There is a frog who is initially on Stone 11. He will repeat the following action some number of times to reach Stone NN:
- If the frog is currently on Stone ii, jump to one of the following: Stone i+1,i+2,…,i+Ki+1,i+2,…,i+K. Here, a cost of |hi−hj||hi−hj| is incurred, where jj is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone NN.
Constraints
- All values in input are integers.
- 2≤N≤1052≤N≤105
- 1≤K≤1001≤K≤100
- 1≤hi≤1041≤hi≤104
Input
Input is given from Standard Input in the following format:
NN KK h1h1 h2h2 …… hNhN
Output
Print the minimum possible total cost incurred.
Sample Input 1 Copy
5 3 10 30 40 50 20
Sample Output 1 Copy
30
If we follow the path 11 → 22 → 55, the total cost incurred would be |10−30|+|30−20|=30|10−30|+|30−20|=30.
Sample Input 2 Copy
3 1 10 20 10
Sample Output 2 Copy
20
If we follow the path 11 → 22 → 33, the total cost incurred would be |10−20|+|20−10|=20|10−20|+|20−10|=20.
Sample Input 3 Copy
2 100 10 10
Sample Output 3 Copy
0
If we follow the path 11 → 22, the total cost incurred would be |10−10|=0|10−10|=0.
Sample Input 4 Copy
10 4 40 10 20 70 80 10 20 70 80 60
Sample Output 4 Copy
40
If we follow the path 11 → 44 → 88 → 1010, the total cost incurred would be |40−70|+|70−70|+|70−60|=40|40−70|+|70−70|+|70−60|=40.
题目链接:https://atcoder.jp/contests/dp/tasks/dp_b
题意:这一篇的进阶版。
把每次只能跳1~2步改成1~k步。
做法只需要其他的不变,把转移方程那里循环1~k次就行了。
附上代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <map> #include <set> #include <vector> #define rep(i,x,n) for(int i=x;i<n;i++) #define repd(i,x,n) for(int i=x;i<=n;i++) #define pii pair<int,int> #define pll pair<long long ,long long> #define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0) #define MS0(X) memset((X), 0, sizeof((X))) #define MSC0(X) memset((X), ' ', sizeof((X))) #define pb push_back #define mp make_pair #define fi first #define se second #define gg(x) getInt(&x) using namespace std; typedef long long ll; inline void getInt(int* p); const int maxn=1000010; const int inf=0x3f3f3f3f; /*** TEMPLATE CODE * * STARTS HERE ***/ ll n; ll dp[maxn]; ll a[maxn]; ll k; int main() { gbtb; cin>>n>>k; repd(i,1,n) { cin>>a[i]; } dp[1]=0; dp[0]=0; repd(i,2,n) { dp[i]=inf; } repd(i,2,n) { for(int j=i-1;j>=max(1ll,i-k);j--) { dp[i]=min(dp[i],dp[j]+abs(a[i]-a[j])); } } cout<<dp[n]; return 0; } inline void getInt(int* p) { char ch; do { ch = getchar(); } while (ch == ' ' || ch == ' '); if (ch == '-') { *p = -(getchar() - '0'); while ((ch = getchar()) >= '0' && ch <= '9') { *p = *p * 10 - ch + '0'; } } else { *p = ch - '0'; while ((ch = getchar()) >= '0' && ch <= '9') { *p = *p * 10 + ch - '0'; } } }