动态规划练习

被3整除的子序列 (nowcoder.com)

O(n^2)解法:

状态表示:f[i][j]表示以位置i结尾,数位和模3后为j的集合

集合划分:

f[i+1,i+2,\dots,n][$(j + s[i]-'0')\,mod\,3$]=f[i][0,1,2] + f[i][$(j + s[i]-'0')\,mod\,3$]

#include<bits/stdc++.h>

using namespace std;

const int N = 55, P = 1e9 + 7;

int f[N][3];

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    string s;
    cin >> s;
    int n = s.size();
    s = " " + s;
    for (int i = 1; i <= n; i++){
        f[i][(s[i] - '0') % 3] = 1;
    }
    for (int i = 1; i <= n; i++){
        for (int j = 0; j < 3; j++){
            for (int k = i + 1; k <= n; k++){
                f[k][(j + s[k] - '0') % 3] = (f[i][j] + f[k][(j + s[k] - '0') % 3]) % P;
            }
        }
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) ans = (ans + f[i][0]) % P;
    cout << ans;
    return 0;
}

O(n)解法:

一个数如果可以被3整除,那么这个数的数位和一定可以被3整除

状态表示:f[i][j]表示前i个数中数位和模为j的子序列的个数

集合划分:f[i][j] = f[i-1][j]+f[i-1][$(j + s[i]-'0')\,mod\,3$]

#include<bits/stdc++.h>

using namespace std;

const int N = 55, P = 1e9 + 7;

int f[N][3];

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    string s;
    cin >> s;
    f[0][(s[0] - '0') % 3] = 1;
    for (int i = 1; i < s.size(); i++){
        int t = (s[i] - '0') % 3;
        f[i][t] = (f[i][t] + 1) % P;
        for (int j = 0; j < 3; j++){
            f[i][j] += (f[i - 1][j] + f[i - 1][(j + 3 - t) % 3]) % P;
        }
    }
    cout << f[s.size() - 1][0];
    return 0;
}

1010. 拦截导弹 - AcWing题库

最多能拦截的导弹数量为最长非递增子序列。

g来存每个非递增子序列的最大值,对于每个a[i]g数组中找到大于a[i]的最小值(g[k]),将g[k]的值更新为a[i]。如果找不到g[k],就创建一个新的结尾为a[i]的子序列,数组g的元素个数+1。最后答案为g数组的元素个数。

#include<bits/stdc++.h>

using namespace std;

const int N = 1010;

int n = 1;
int a[N], f[N], g[N];

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    while (cin >> a[n]) n++;
    int res = 0;
    for (int i = 1; i < n; i++){
        f[i] = 1;
        for (int j = 1; j < i; j++){
            if (a[j] >= a[i]) f[i] = max(f[i], f[j] + 1);
        }
        res = max(f[i], res);
    }
    cout << res << '\n';
    int cnt = 0;
    for (int i = 1; i < n; i++){
        int k = 0;
        while (k < cnt && g[k] < a[i]) k++;
        g[k] = a[i];
        if (k >= cnt) cnt++;
    }
    cout << cnt;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值