【CODEFORCES】 C. Number of Ways

C. Number of Ways
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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


题解:此题并不算难,我们设lsum[i]是从1到i所有数组元素的和(前缀和),rsum[i]是从i到n所有数组元素的和,那么现在就是要找到一组i,j,i<j,j-i>=2,lsum[i]=lsum[j]=sum/3。看到题目数据较大,n方算法不划算,所以用一个c数组记录,c[i]表示i之后有多少个rsum[i]与sum/3相等,这样就把时间复杂度降为O(n)了。

感觉主要是前缀和...

#include <iostream>
#include <cstdio>

using namespace std;

int a[500003],c[500003],n;
long long lsum[500003],rsum[500003],sum,ans;
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        sum+=a[i];
        lsum[i]=a[i]+lsum[i-1];
    }
    if (sum%3!=0)
    {
        cout <<0<<endl;
        return 0;
    }
    for (int i=1;i<=n;i++) rsum[i]=sum-lsum[i]+a[i];
    for (int i=n;i>=1;i--) if (rsum[i]==sum/3) c[i]=c[i+1]+1;
                           else c[i]=c[i+1];
    for (int i=1;i<=n-1;i++) if (lsum[i]==sum/3) ans+=c[i+2];
    cout <<ans<<endl;
    return 0;
}






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值