第一行输入两个整数
代表数组中的元素数量。
第二行输入
个整数
代表数组元素。
在一行上输出一个整数,代表切分方案数。
3 3 3 3
1
6 1 1 4 5 1 4
0
10 0 3 4 2 3 2 1 -1 3 4
2
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
long[] nums = new long[n + 1];
for (int i = 1; i <= n; i++) {
nums[i - 1] = Long.parseLong(st.nextToken());
}
Solution solution = new Solution();
int res = solution.cutArray(nums);
pw.println(res);
pw.close();
}
}
class Solution {
public int cutArray(long[] nums) {
int n = nums.length;
long[] preSum = new long[n];
int[] posCnt = new int[n];
preSum[0] = nums[0];
posCnt[0] = nums[0] > 0 ? 1 : 0;
for (int i = 1; i < n; i++) {
preSum[i] = preSum[i - 1] + nums[i];
posCnt[i] = posCnt[i - 1] + (nums[i] > 0 ? 1 : 0);
}
long sum = preSum[n - 1];
if (sum % 3 != 0) return 0;
long target = sum / 3;
int ans = 0;
for (int i = 0; i < n - 2; i++) {
if (preSum[i] != target || posCnt[i] == 0) continue;
if (posCnt[i] == posCnt[n - 1]) break;
for (int j = i + 1; j < n - 1; j++) {
if (preSum[j] - preSum[i] != target) continue;
if (posCnt[i] == posCnt[j] || posCnt[j] == posCnt[n - 1]) continue;
ans++;
}
}
return ans;
}
} import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = Integer.parseInt(in.nextLine());
int sum = 0;
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = in.nextInt();
sum += arr[i];
}
if(sum % 3 != 0){
System.out.println(0);
continue;
}
int avg3 = sum / 3;
int sum1 = 0;//第一个子数组和
int count = 0;
int rightIndex = n - 1;
int firstflag = 0;//第一个数组是否有正数
int secondflag = 0;//第三个数组是否有正数
for(int i = 0; i < rightIndex - 3; i++){
firstflag = Math.max(firstflag,arr[i]);
sum1 += arr[i];
//从左往右找到第一刀
if(sum1 == avg3 && firstflag > 0){
int sum2 = 0;//第三个子数组和
//从右往左找到第二刀
secondflag = 0;
for(int j = rightIndex; j >= i+2; j--){
secondflag = Math.max(secondflag,arr[j]);
sum2 += arr[j];
if(sum2 == avg3 & secondflag > 0 && hasZhengShu(arr,i + 1,j)){
count++;
}
}
}
}
System.out.println(count);
}
}
//判断数组内是否有正数
static boolean hasZhengShu(int[] arr, int i, int j){
for(; i < j; i++){
if(arr[i] > 0){
return true;
}
}
return false;
}
}