#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class BajtazarHandlarzPrzedsiebiorca {
public:
static int toIleTegoPiachu(const vector<int>& heights, int k) {
const int n = heights.size();
if (n == 0) return 0;
vector<int> dp(n, INT_MAX);
dp[0] = 0;
for (int i = 1; i < n; ++i) {
for (int j = 1; j <= k; ++j) {
if (i - j >= 0) {
int cost = dp[i - j] + abs(heights[i] - heights[i - j]);
dp[i] = min(dp[i], cost);
}
}
}
return dp[n - 1];
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
vector<int> heights;
cin >> n >> k;
for (int i = 0; i < n; ++i) {
int height;
cin >> height;
heights.push_back(height);
}
cout << BajtazarHandlarzPrzedsiebiorca::toIleTegoPiachu(heights, k) << endl;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <iostream> #include <vector> #include <algorithm> #include <climits> using namespace std; class BajtazarHandlarzPrzedsiebiorca { public: static int toIleTegoPiachu(const vector<int>& heights, int k) { const int n = heights.size(); if (n == 0) return 0; vector<int> dp(n, INT_MAX); dp[0] = 0; for (int i = 1; i < n; ++i) { for (int j = 1; j <= k; ++j) { if (i - j >= 0) { int cost = dp[i - j] + abs(heights[i] - heights[i - j]); dp[i] = min(dp[i], cost); } } } return dp[n - 1]; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n, k; vector<int> heights; cin >> n >> k; for (int i = 0; i < n; ++i) { int height; cin >> height; heights.push_back(height); } cout << BajtazarHandlarzPrzedsiebiorca::toIleTegoPiachu(heights, k) << endl; } |
English