http://codeforces.com/contest/1006/problem/C
解题思路:
1.暴力:
弄两根指针分别指向头尾,再弄一个前序和和一个后序和
两和相等,更新ans,并增加前序和(左指针右移)
前序和比后序和小,增加前序和(左指针右移)
前序和比后序和大,增加后序和(右指针左移)
直到两指针相遇
2.二分:
枚举前序和
枚举后序和,在前序和中二分查找后序和,找到就更新ans
总结:其实两个思路都是枚举前序和与后序和,其实根本不需要二分,只是二分可能相对更好懂,毕竟指针这种东西很多人都比较讨厌
brute force:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] num = new int[200010];
for(int i = 1;i <= n;i++) {
num[i] = sc.nextInt();
}
int i = 1,j = n;
long left = num[1],right = num[n];
long ans = 0;
while(i < j) {
if(left == right) {
ans = Math.max(ans,left);
}
if(left <= right) {
i++;
left += num[i];
} else if(left > right) {
j--;
right += num[j];
}
}
System.out.println(ans);
}
}
binary search:
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] num = new int[200010];
long cnt = 0;
for(int i = 1;i <= n;i++) {
num[i] = sc.nextInt();
cnt += num[i];
}
Vector<Long> ve = new Vector<>(); //存下小于1/2序列和的所有左序列和
long res = 0;
for(int i = 1;i <= n;i++) {
if(res > cnt / 2) {
break;
}
ve.add(res);
res += num[i];
}
res = 0;
long ans = 0;
for(int i = n;i >= 1;i--) {
res += num[i];
if (res > cnt / 2) {
break;
}
if(Collections.binarySearch(ve,res) >= 0) { //二分找到相等和就更新ans
ans = Math.max(ans,res);
}
}
System.out.println(ans);
}
}