Codeforces 837D 动态规划

本文介绍了一个动态规划问题的解决方案,该问题是Codeforces837D,旨在求解从n个数中选择k个数使得这些数的乘积末尾含有最多的0。通过分析2和5的数量来构建动态规划的状态转移方程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Codeforces 837D 动态规划

传送门:https://codeforces.com/contest/837/problem/D

题意:

给你n个数,问你从这n个数中取出k个数,这k个数的乘积的末尾最多有多少个0

题解:

要想让乘积的末尾有0,实际上就是2的倍数和5的倍数相乘才能得到贡献,所以每个数对答案的贡献实际上就是这个数中包含的2的个数还有这个数中包含的5的数对答案的贡献

设定dp状态为

\(dp[i][j]表示从n个数中选出i个数,其中有j个5的个数,最多有多少个2\)

边界 dp[0][0]=0, else dp[i][j]=-INF

转移:dp[i][j]=max(dp[i][j],dp[i-1][j-cnt5[i]]+cnt2[i])

代码:

#include <set>
#include <map>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef unsigned long long uLL;
#define ls rt<<1
#define rs rt<<1|1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define bug printf("*********\n")
#define FIN freopen("input.txt","r",stdin);
#define FON freopen("output.txt","w+",stdout);
#define IO ios::sync_with_stdio(false),cin.tie(0)
#define debug1(x) cout<<"["<<#x<<" "<<(x)<<"]\n"
#define debug2(x,y) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<"]\n"
#define debug3(x,y,z) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<" "<<#z<<" "<<z<<"]\n"
const int maxn = 3e5 + 5;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
LL quick_pow(LL x, LL y) {
    LL ans = 1;
    while(y) {
        if(y & 1) {
            ans = ans * x % mod;
        } x = x * x % mod;
        y >>= 1;
    } return ans;
}
struct node {
    int cnt2;
    int cnt5;
} a[maxn];
int dp[205][205 * 64];
int main() {
#ifndef ONLINE_JUDGE
    FIN
#endif
    int n, k;
    scanf("%d%d", &n, &k);
    for(int i = 1; i <= n; i++) {
        LL x;
        scanf("%lld", &x);
        while(x % 2 == 0) {
            a[i].cnt2++;
            x /= 2;
        }
        while(x % 5 == 0) {
            a[i].cnt5++;
            x /= 5;
        }
    }
    LL sum = 0;
    memset(dp, -INF, sizeof(dp));
    dp[0][0]=0;
    for(int i = 1; i <= n; i++) {
        sum += a[i].cnt5;
                // debug1(a[i].cnt2);
            // debug1(sum);
        for(int j = min(k, i); j >= 1; j--) {
            for(int k = sum; k >= a[i].cnt5; k--) {
                // debug2(k,a[i].cnt5);
                dp[j][k] = max(dp[j][k], dp[j - 1][k - a[i].cnt5] + a[i].cnt2);
                // debug3(j,k,dp[j][k]);
            }
        }
    }
    LL ans = 0;
    for(int i = 1; i <= sum; i++) {
        ans = max(ans, 1LL * min(i, dp[k][i]));
    }
    printf("%lld\n", ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值