比较简单的DP, 利用滚动数组,代码如下: #include <iostream> using namespace std; int dp[2][31][2]; int t, w; int tree[1001]; #define max(a, b) ((a)>(b) ? (a):(b)) int main() { int i, j, k, ans, sel; while (cin>>t>>w) { for (i=1; i<=t; i++) cin >> tree[i]; memset(dp, 0, sizeof(dp)); dp[0][0][0] = 0; dp[0][0][1] = -1; for (sel=1, i=1; i<=t; i++, sel=1-sel) for (j=0; j<=w; j++) { if (j<=i) { dp[sel][j][0] = max(dp[sel][j][0], dp[1-sel][j][0]+(tree[i]==1)); dp[sel][j][1] = max(dp[sel][j][1], dp[1-sel][j][1]+(tree[i]==2)); if (j>=1) dp[sel][j][1] = max(dp[sel][j][1], dp[1-sel][j-1][0]+(tree[i]==2)); if (j>=1) dp[sel][j][0] = max(dp[sel][j][0], dp[1-sel][j-1][1]+(tree[i]==1)); } } ans = 0; for (i=0; i<=w; i++) ans = max(ans, max(dp[1-sel][i][0], dp[1-sel][i][1])); cout << ans << endl; } return 0; }