fork download
  1. #include<iostream>
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. int main(){
  7.  
  8. int n;
  9. cin>>n;
  10. int k;
  11. cin>>k;
  12. vector<int> arr(n+1,0);
  13.  
  14. for(int i=1; i<=n; i++){
  15. cin>>arr[i];
  16. }
  17.  
  18. vector<int> dp(n+1, 0);
  19.  
  20. dp[1] = 0;
  21. dp[2] = abs(arr[1] - arr[2]);
  22.  
  23. int i = 3;
  24. while(i<=n){
  25.  
  26. int ans=INT_MAX;
  27.  
  28. for(int j=1; j<i && j<=k; j++){
  29. ans = min(ans, dp[i-j] + abs(arr[i]-arr[i-j]));
  30. }
  31. dp[i]=ans;
  32. cout<< "for position "<<i<<" dp:-"<<dp[i];
  33. i++;
  34. }
  35.  
  36. cout << dp[n];
  37. return 0;
  38. }
Success #stdin #stdout 0.01s 5288KB
stdin
5 3
10 30 40 50 20
stdout
for position 3 dp:-30for position 4 dp:-40for position 5 dp:-3030