【洛谷OJ】【JAVA】P1018 乘积最大

https://www.luogu.org/problemnew/show/P1018

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	private static Scanner cin;
	private static char[] values;
	private static BigInteger max = new BigInteger("1");
	private static int n;
	private static int k;
	
	public static void main(String args[]) throws Exception {
		cin = new Scanner(System.in);
		n = cin.nextInt();
		k = cin.nextInt();
		String nvalue = cin.next();
		values = nvalue.toCharArray();
		calc(0,n-k,max,1);
		System.out.println(max);
	}
	
	/**
	 * 基于values数组,从startposition位置开始,有length个数字可以用来分割拼接成数字,当前处理到k+1个数字的第count个,tmpValue是之前count-1个数字的乘积
	 * @param startPosition
	 * @param length
	 * @param tmpValue
	 * @param count
	 */
	public static void calc(int startPosition, int length, BigInteger tmpValue, int count) {		
		String tmp = null;
		//如果是最后一个数,使用剩余的数字组成一个数字
		if(count == k+1) {
			tmp =String.valueOf(values,startPosition,values.length-startPosition);
			BigInteger value = new BigInteger(tmp);
			BigInteger tValue = tmpValue.multiply(value);
			if(tValue.compareTo(max)>0) {
				max = tValue;
			}
		}else {
			for(int j=1;j<=length;j++) {
				tmp = String.valueOf(values,startPosition,j);
				BigInteger value = new BigInteger(tmp);
				BigInteger tValue = tmpValue.multiply(value);
				calc(startPosition+j,n-startPosition-j-(k-count),tValue,count+1);
			}
		}
	}
}

 

你可能感兴趣的:(JAVA,OJ)