fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define pb push_back
  5. #define yes cout<<"YES\n";
  6. #define no cout<<"NO\n";
  7. const int N=3e5+7;
  8. ll T=1;
  9. ll h[N];
  10. ll n, oo = 1e18, k;
  11. ll dp[N];
  12.  
  13. ll rec(ll i)
  14. {
  15. if(i > n)
  16. return oo;
  17. if(i == n)
  18. return 0;
  19.  
  20. ll &ret = dp[i];
  21.  
  22. if(ret != -1)
  23. return ret;
  24.  
  25. ret = oo;
  26.  
  27. for(int j = 1; j <= k; j++){
  28. ll p = rec(i + j) + abs(h[i] - h[i + j]);
  29. ret = min(ret, p);
  30. }
  31.  
  32. return ret;
  33. }
  34. void solve()
  35. {
  36. memset(dp, -1, sizeof dp);
  37. cin >> n >> k;
  38. for(int i = 1; i <= n; i++)
  39. cin >> h[i];
  40. cout << rec(1);
  41. }
  42. int main()
  43. {
  44. ios::sync_with_stdio(NULL);
  45. cin.tie(0);
  46. cout.tie(0);
  47.  
  48. // freopen("","r", stdin);
  49. // freopen("","w", stdout);
  50. // cin>>T;
  51. while(T--)
  52. solve();
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 7976KB
stdin
5 3
10 50 30 20 30
stdout
20