现在的位置: 首页 > 综合 > 正文

Codeforces 466 C. Number of Ways

2017年11月23日 ⁄ 综合 ⁄ 共 1458字 ⁄ 字号 评论关闭

二分+暴力

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>

using namespace std;

typedef long long int LL;

int n;
LL a[500500];
LL sum[500500];

vector<int> v1,v2;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        sum[i]=sum[i-1]+a[i];
    }
    if(sum[n]%3LL!=0)
    {
        puts("0");
        return 0;
    }
    LL X=sum[n]/3;

    for(int i=1;i<=n;i++)
    {
        if(sum[i]==X)
        {
            if(i!=n&&i!=n-1)
                v1.push_back(i);
        }
        if(sum[i]==2*X)
        {
            if(i!=n) v2.push_back(i);
        }
    }

    LL ans=0;
    int sz1=v1.size(),sz2=v2.size();
    if(X!=0)
    {
        for(int i=0;i<sz1;i++)
        {
            int p1=v1[i];
            int p2=lower_bound(v2.begin(),v2.end(),p1)-v2.begin();
            if(p1==v2[p2]) p2++;
            if(p2>=n) continue;
            ans+=sz2-p2;
        }
    }
    else
    {
        int LAST=0;
        for(int i=0;i<sz1;i++)
        {
            int id=-1;
            for(int j=LAST;j<sz2;j++)
            {
                if(v2[j]>v1[i])
                {
                    LAST=j;
                    id=j; break;
                }
            }
            ans+=sz2-id;
        }
    }
    cout<<ans<<endl;
    return 0;
}

抱歉!评论已关闭.