2023年2月27日-AcWing-316. 减操作-线性dp+逆推

思路见代码
AC代码:

#include <bits/stdc++.h>
#define IN                   \
    ios::sync_with_stdio(0); \
    cin.tie(0);
using namespace std;
#define ll long long
const int N = 1e2 + 10, M = 1e4 + 10;
int n, m, ans;
int a[N];
int h = 10000;
bool f[N][M * 2];  // f[i][j]表示前i个数能否形成j
bool g[N][M * 2];  // g[i][j]表示前i个数形成j时,第i个数的正负
bool st[N];
bool volid(int x) {
    return x >= -10000 && x <= 10000;
}
int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    f[2][a[1] - a[2] + h] = true;
    for (int i = 2; i <= n; i++) {
        for (int j = -10000; j <= 10000; j++) {
            if (f[i][j + h]) {              // 如果前i个数能形成j
                if (volid(a[i + 1] + j)) {  // 情况1:第i+1个数为正
                    f[i + 1][a[i + 1] + j + h] = true;
                    g[i + 1][a[i + 1] + j + h] = true;
                }
                if (volid(j - a[i + 1])) {  // 情况2:第i+1个数为负
                    f[i + 1][j - a[i + 1] + h] = true;
                    g[i + 1][j - a[i + 1] + h] = false;
                }
            }
        }
    }
    int id = n;
    while (id > 2) {  // 确定所有数的正负
        st[id] = g[id][m + h];
        if (st[id]) {
            m -= a[id];
        } else {
            m += a[id];
        }
        id--;
    }
    st[1] = true;
    st[2] = false;
    // 正数对它前面的数进行cut操作,随后一直cut(1)
    int cnt = 0;
    for (int i = 3; i <= n; i++) {
        if (st[i] == true) {
            cout << i - 1 - cnt << endl;
            cnt++;
        }
    }
    for (int i = 1; i <= n - 1 - cnt; i++) {  // 一共为n-1次操作
        cout << "1" << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值