{1, 2, 1}, {15, 78, 78, 15} , {112} 是迴文序列,
{1, 2, 2}, {15, 78, 87, 51} ,{112, 2, 11} 不是迴文序列。
現在給出一個數字序列,允許使用一種轉換操作:
選擇任意兩個相鄰的數,然後從序列移除這兩個數,並用這兩個數字的和插入到這兩個數之前的位置(只插入一個和)。
現在對於所給序列要求出最少需要多少次操作可以將其變成迴文序列。
輸入描述:
輸入爲兩行,第一行爲序列長度n ( 1 ≤ n ≤ 50)
第二行爲序列中的n個整數item[i] (1 ≤ iteam[i] ≤ 1000),以空格分隔。
輸出描述:
輸出一個數,表示最少需要的轉換次數
輸入例子:
4
1 1 1 3
輸出例子:
2
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int times = 0;
int n = scanner.nextInt();
int[] inputArr = new int[n];
for(int i = 0; i < n; i++){
inputArr[i] = scanner.nextInt();
}
int head = 0;
int tail = n - 1;
while(head < tail){
if(inputArr[head] > inputArr[tail]){
inputArr[--tail] += inputArr[tail + 1];
times++;
}else if(inputArr[head] < inputArr[tail]){
inputArr[++head] += inputArr[head - 1];
times++;
}else{
head++;
tail--;
}
}
System.out.println(times);
}
scanner.close();
}
}