我有一组三元组,希望以最小的总和方式将其中的数字相加,且每个三元组只能选择一个数字。例如:
10 10 1 //minimum 1
1 10 21 //minimum 1
10 1 10 //minimum 1 Ans : 1+1+1 = 3
然而,您不能选择同一列中相邻的元素。
10 10 1 //select 1
10 10 1 //cannot select 1, that's adjacent!
10 10 1 //safe to select 1
但问题在于,如果出现平局,我需要扫描序列中的下一个三元组,并确保不选择前一个序列中的数字以获得最大利润。 例如:
10 10 10 // step 2.select 10 from column 1 or 2
10 10 1 // step 1.make sure not to select element in column 3 in previous sequence
// step 3. select 1 from column 3
由于我们无法替换Scanner的位置,因此我无法将Scanner的readLine移动到上一个位置,那么我该如何提前扫描?
我的想法是:(由于数字范围很大,我使用了BigInt)
for(long j=0; j<noOfTriples ; j++){
firstNumber = in.nextBigInteger();
secNumber = in.nextBigInteger();
thirdNumber = in.nextBigInteger();
if(areEqual(firstNumber, secNumber, thirdNumber)){
while(true){
firstNumber2 = in.nextBigInteger();
secNumber2 = in.nextBigInteger();
thirdNumber2 = in.nextBigInteger();
noOfTriples--;
if(areEqual(firstNumber2, secNumber2, thirdNumber2)){
count.add(secNumber2); // add any number to the count
// since all of them are same
}else
break;
}
pass(firstNumber, secNumber, thirdNumber, least(firstNumber2, secNumber2, thirdNumber2));
//pass adds up the minimum of three to the count
//where the last field indicates which element to NOT use while adding &
//least returns minimum of the three
}else
pass(firstNumber, secNumber, thirdNumber, -1); //-1 indicates no bias
}
编辑:
- sprinter 指出,我需要扫描整个三元组列表。仅仅顺序扫描下一个不会有所帮助。
- 输入数量可能高达一百万,因此穷举搜索无法帮助。