洛谷P018 乘積最大 2000年NOIP提高組第二題真題
阿新 • • 發佈:2019-01-31
洛谷P018 乘積最大 2000年NOIP真題
解題思路:
用dfs搜一下就好了,然而需要注意的是,本題的數值已經超過了64位整數的儲存範圍了,所以應該用大數型別來儲存結果。所以我選擇用Java做這道題,嘿嘿,BigInteger用起來最合適不過了
AC程式碼(Java版):
package luogu;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner (System.in);
int n = cin.nextInt();
int k = cin.nextInt();
String s = cin.next();
System.out.println(dfs(s, k));
}
private static BigInteger dfs(String s, int k) {
if (k == 0) {
return new BigInteger(s);
}
if (k == s.length() - 1) {
BigInteger ret = BigInteger.ONE;
for (int i = 0; i < s.length(); i++) {
ret = ret.multiply(new BigInteger(s.substring(i, i + 1)));
}
return ret;
}
BigInteger max = BigInteger.ONE;
for (int i = 1; i < s. length() - k; i++) {
BigInteger
ret = new BigInteger(s.substring(0, i)).multiply(dfs(s.substring(i, s.length()), k - 1));
if (max.compareTo(ret) < 0) {
max = ret;
}
}
return max;
}
}