题目链接:传送门
G. Round Subset
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Let's call the roundness of the number the number of zeros to which it ends.
You have an array of n numbers. You need to choose a subset of exactly k numbers so that the roundness of the product of the selected numbers will be maximum possible.
Input
The first line contains two integer numbers n and k (1 ≤ n ≤ 200, 1 ≤ k ≤ n).
The second line contains n space-separated integer numbers a1, a2, ..., an (1 ≤ ai ≤ 1018).
Output
Print maximal roundness of product of the chosen subset of length k.
Examples
input
Copy
3 2 50 4 20
output
Copy
3
input
Copy
5 3 15 16 3 25 9
output
Copy
3
input
Copy
3 3 9 77 13
output
Copy
0
Note
In the first example there are 3 subsets of 2 numbers. [50, 4] has product 200 with roundness 2, [4, 20] — product 80, roundness 1, [50, 20] — product 1000, roundness 3.
In the second example subset [15, 16, 25] has product 6000, roundness 3.
In the third example all subsets has product with roundness 0.
题意描述:
给你n个数,让你从中选出k个数出来,使得这k个数相乘末尾0的个数最大。
题目分析:
首先,我们要明白,k个数相乘后末尾0的个数取决与这k个数质因数分解后2和5的最小值。那么,我们就可以用dp来做了,定义dp[i][j][k]来表示到第i个数字,我们选择其中j个数字, 质因子5的个数之和为k中质因子2的个数。(当然,你把2和5互换也行,但这样子会增加空间和时间复杂度)。转换方程就是dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j-1][k-div5[i]]+div2[i]).其中,div5[i]表示第i个数的质因数分解5的个数,div2类似。但你会发现开不了这么大的空间,但他的状态转移方程只跟上一次的状态有关,所以可以用滚动数组,以时间换空间。
代码:
#include
using namespace std;
typedef long long ll;
ll dp[2][205][6000];
ll div2[205], div5[205];
ll n, k, m;
ll Div_two(ll x){
int res = 0;
while(x % 2 == 0){
res++;
x /= 2;
}
return res;
}
ll Div_five(ll x){
int res = 0;
while(x%5 == 0){
res++;
x /= 5;
}
return res;
}
int main(){
ll ans = 0, temp;
cin >> n >> m;
for(int i=1;i<=n;++i){
cin >> temp;
div2[i] = Div_two(temp);
div5[i] = Div_five(temp);
}
memset(dp, -1, sizeof(dp));
dp[0][0][0] = 0;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
for(ll k=0;k<=5200;++k){
dp[1][j][k] = max(dp[1][j][k], dp[0][j][k]);
if(div5[i] <= k && dp[0][j-1][k-div5[i]] != -1){
dp[1][j][k] = max(dp[1][j][k], dp[0][j-1][k-div5[i]]+div2[i]);
}
ans = max(ans, min(dp[1][j][k], k));
}
}
for(int j=1;j<=n;++j){
for(int k=0;k<=5200;++k){
dp[0][j][k] = dp[1][j][k];
}
}
}
cout << ans << endl;
return 0;
}