codeforces 466C Number of Ways

来源:互联网 发布:最好的照片打印软件 编辑:程序博客网 时间:2024/05/21 14:41

点击打开链接

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.

Examples
input
51 2 3 0 3
output
2
input
40 1 -1 0
output
1
input
24 1
output
0
题意:将这个数组分成三段,每段的和相等,求有几种分法。

我自己没想出来,这个是我比较喜欢的一种

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<vector>const int ma=5*1e5+10;typedef long long ll;using namespace std;ll a[ma];ll s=0,n;vector<int>vec;ll solve(){    if(s%3)        return 0;    s/=3;    ll p=0;    for(int i=0; i<n; i++)    {        p+=a[i];        if(p==s)            vec.push_back(i);    }    p=0;    ll ans=0;    for(int i=n-1;i>=0;i--)    {        p+=a[i];        if(p==s)            ans+=lower_bound(vec.begin(),vec.end(),i-1)-vec.begin();    }    return ans;}int main(){    cin>>n;    for(int i=0; i<n; i++)    {        cin>>a[i];        s+=a[i];    }    cout<<solve()<<endl;    return 0;}
这个也能过,但是不明白all为0时,那个几种为什么是(cnt-1)*(cnt-2)/2这个,如果你知道,欢迎评论,感激不尽。

#include<iostream>#include<cstdio>#include<algorithm>#define ll long longusing namespace std;const int ma=500005;ll a[ma],sum[ma];int main(){    int n;    cin>>n;    sum[0]=0;    for(int i=1;i<=n;i++)    {        cin>>a[i];        sum[i]=sum[i-1]+a[i];    }    if(n==1)        cout<<0<<endl;    else    {        ll all=sum[n];        if(all%3!=0)            cout<<0<<endl;        else if(all)        {            ll s=0;            ll w1=all/3;            ll w2=all/3*2;            int cnt=0;            for(int i=1;i<=n;i++)            {                if(sum[i]==w2)                    s+=cnt;                if(sum[i]==w1)                    cnt++;            }            cout<<s<<endl;        }        else        {            ll cnt=0;            for(int i=1;i<=n;i++)            {                if(sum[i]==0)                    cnt++;            }            cout<<(cnt-1)*(cnt-2)/2<<endl;        }    }    return 0;}

原创粉丝点击