Array Game (Thuật toán chia để trị)
package Advance;
import java.io.FileInputStream;
import java.util.Scanner;
public class ArrayGame {
public static void main(String[] args) throws Exception {
new ArrayGame().inIt();
}
int N;
int[] array;
long Sum;
int Result;
private void inIt() throws Exception {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int test_case = 1; test_case <= 20; test_case++) {
N = sc.nextInt();
Sum = 0;
Result = 0;
array = new int[N + 1];
for (int i = 0; i < N; i++) {
array[i] = sc.nextInt();
Sum += array[i];
}
Result = check(Sum,0,N);
System.out.println(Result);
}
}
private int findMid(long sum, int s, int e) {
long total = 0;
int mid = 0;
for (int i = s; i < e; i++) {
if (total < sum) {
total += array[i];
mid = i;
} else
break;
}
if (total != sum){
return -1;
}
return mid;
}
private int check(long sum, int start, int end) {
if(sum == 0) return end - start - 1;
if (sum % 2 != 0)
return 0;
if (end - start <= 1)
return 0;
int mid = findMid(sum / 2, start, end);
if (mid == -1)
return 0;
int a = 1 + check(sum / 2, start, mid + 1);
int b = 1 + check(sum / 2, mid + 1, end);
return a > b ? a : b;
}
}
import java.io.FileInputStream;
import java.util.Scanner;
public class ArrayGame {
public static void main(String[] args) throws Exception {
new ArrayGame().inIt();
}
int N;
int[] array;
long Sum;
int Result;
private void inIt() throws Exception {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int test_case = 1; test_case <= 20; test_case++) {
N = sc.nextInt();
Sum = 0;
Result = 0;
array = new int[N + 1];
for (int i = 0; i < N; i++) {
array[i] = sc.nextInt();
Sum += array[i];
}
Result = check(Sum,0,N);
System.out.println(Result);
}
}
private int findMid(long sum, int s, int e) {
long total = 0;
int mid = 0;
for (int i = s; i < e; i++) {
if (total < sum) {
total += array[i];
mid = i;
} else
break;
}
if (total != sum){
return -1;
}
return mid;
}
private int check(long sum, int start, int end) {
if(sum == 0) return end - start - 1;
if (sum % 2 != 0)
return 0;
if (end - start <= 1)
return 0;
int mid = findMid(sum / 2, start, end);
if (mid == -1)
return 0;
int a = 1 + check(sum / 2, start, mid + 1);
int b = 1 + check(sum / 2, mid + 1, end);
return a > b ? a : b;
}
}
Nhận xét
Đăng nhận xét