题目传送门:
https://www.luogu.com.cn/problem/B4533
题面:
6-roundness 是一个数在六进制下末尾零的个数。
给定 n 个数,从中选 k 个,让它们的乘积在六进制下的末尾零最多。输出最多的零的个数。
思路:
我们可以把每个数 aᵢ 分解成 (xᵢ, yᵢ),其中:
xᵢ = 该数质因数分解中 2 的指数
yᵢ = 该数质因数分解中 3 的指数
那么问题就变成: 选 k 个数,最大化 min(∑xᵢ, ∑yᵢ)。
Dp设计
设 dp[j][t] 表示:
选了 j 个数
这些数的 2 的指数总和为 t
能达到的最大的 3 的指数总和
初始化:
dp[0][0] = 0
其他为 -∞
转移: 对每个数 (x, y),从大到小更新:
dp[j][t] = max(dp[j][t], dp[j-1][t-x] + y)
表示选了该数后,2 的总指数变成 t,3 的总指数变为原来的最大可能加上 y。
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n,k;
cin >> n >> k;
vector<int> cnt(n), ccnt(n);
int maxn = 0;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
int cnt2 = 0, cnt3 = 0;
while (x % 2 == 0)
{
cnt2++;
x /= 2;
}
while (x % 3 == 0)
{
cnt3++;
x /= 3;
}
cnt[i] = cnt2;
ccnt[i] = cnt3;
maxn += cnt2;
}
vector<vector<int>> dp(k + 1, vector<int>(maxn + 1, -INF));
dp[0][0] = 0;
for (int i = 0; i < n; i++)
{
int cnt2 = cnt[i];
int cnt3 = ccnt[i];
for (int j = k; j >= 1; j--)
{
for (int t = maxn; t >= cnt2; t--)
{
if (dp[j - 1][t - cnt2] != -INF)
{
dp[j][t] = max(dp[j][t], dp[j - 1][t - cnt2] + cnt3);
}
}
}
}
int ans = 0;
for (int t = 0; t <= maxn; t++)
{
if (dp[k][t] != -INF)
{
ans = max(ans, min(t, dp[k][t]));
}
}
cout << ans << endl;
return 0;
}