You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .
Input
The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1],a[2], ..., a[n] (|a[i]| ≤ 109) — the elements of array a.
Output
Print a single integer — the number of ways to split the array into three parts with the same sum.
Sample test(s)
input
5 1 2 3 0 3
output
2
input
4 0 1 -1 0
output
1
input
2 4 1
output
0
map的应用,首先枚举i,如果满足条件dp1[i]%2==0 && sum - dp1[i] = dp1[i]/2,则是可能存在满足条件的方案的,方案数加m1[dp1[i]/2].
#include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <algorithm> #include <functional> using namespace std; const int maxn = 100010; typedef long long ll; map<ll, int> m1; ll dp1[5*maxn]; int arr[5*maxn]; int n; int main() { ll ans = 0, sum = 0; scanf("%d", &n); dp1[0] = 0; for(int i = 1; i <= n; ++i) { scanf("%d", &arr[i]); dp1[i] = dp1[i-1] + arr[i]; sum += arr[i]; } m1[dp1[1]]++; for(int i = 2; i < n; ++i) { if(dp1[i]%2==0 && sum - dp1[i] == dp1[i]/2) { ans += m1[dp1[i]/2]; } m1[dp1[i]]++; } cout << ans << endl; return 0; }