截断数组
思想:
- 前缀和。
- 特殊情况:
- 当数组元素小于三个时,无解。
- 当该数组所有数之和不为 \(3\) 的整数倍时,无解。
- 设数组均分的值为
res,循环遍历前缀和数组a。 - 设
i为第一个分割点,若a[i] == res,则cnt ++。 - 设
i+1为第二个分割点,若a[n] - a[i + 1] == res,则ans += cnt。
- 特殊情况:
代码:
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 3;
typedef long long LL;
LL a[N];
void solve(){
int n; cin >> n;
for(int i = 1; i <= n; i ++){
cin >> a[i]; a[i] += a[i - 1];
}
if(n < 3 || a[n] % 3 != 0){ //特殊情况
cout << 0 << endl;
return ;
}
else{
LL res = a[n] / 3;
LL cnt = 0, ans = 0;
for(int i = 1; i + 2 <= n; i ++){
if(a[i] == res) cnt ++;
if(a[n] - a[i + 1] == res) ans += cnt;
}
cout << ans << endl;
}
}
int main(){
solve();
return 0;
}