fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. /// Luu y code tham khao dung [0, n) thay vi [1, n]
  4. void minimize(int &a, int b) { a = min(a, b); }
  5. int main()
  6. {
  7. int n, k;
  8. cin >> n >> k;
  9.  
  10. vector<int> a(n);
  11. for (int &x : a) cin >> x;
  12.  
  13. vector<int> dp(n, 0);
  14. for (int i = 1; i < n; ++i)
  15. {
  16. dp[i] = dp[i - 1] + abs(a[i] - a[i - 1]);
  17. for (int j = i - 2; j >= max(0, i - k); --j)
  18. minimize(dp[i], dp[j] + abs(a[i] - a[j]));
  19. }
  20.  
  21. cout << dp.back();
  22. return 0;
  23. }
Success #stdin #stdout 0s 5308KB
stdin
5 3
10 30 40 50 20
stdout
30