C++ 代码优化:解决循环索引错误,实现最优解
很抱歉,可能是我在处理循环中的索引时出现了错误。我已经修复了代码中的索引问题,并提供了经过优化的代码。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<pair<int, int>> points;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
points.push_back({x, y});
}
sort(points.begin(), points.end());
int ans = 0;
vector<vector<int>> dp(n + 1, vector<int>(k + 1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
for (int pre = 0; pre < i; pre++) {
if (points[pre].second <= points[i - 1].second) {
dp[i][j] = max(dp[i][j], dp[pre][j - 1] + 1);
}
}
dp[i][j] = max(dp[i][j], dp[i][j - 1]);
ans = max(ans, dp[i][j]);
}
}
cout << ans << endl;
return 0;
}
这次我修复了循环的索引,并且在更新 dp[i][j] 时使用了正确的索引。这段代码应该可以正确地解决这个问题。非常抱歉给您带来的困扰。
原文地址: http://www.cveoy.top/t/topic/bs8b 著作权归作者所有。请勿转载和采集!