CodeForces 466C Number of Ways 【dp】

C. Number of Ways
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard 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
inputCopy
5
1 2 3 0 3
output
2
inputCopy
4
0 1 -1 0
output
1
inputCopy
2
4 1
output
0

思路:该题就是把一串数字分成连续的三段,让三个的和相等。这道题和之前做过的前缀和的题很像。都是将输入的数组 转化成为前 i 项和的数组。
尤其注意当一倍和 和二倍和 为零的时候,第二个循环的两句话不能颠倒。如果颠倒,遇到一倍和为0,总和为0时,x++,紧接着判断 a[i] * 3 == a[n-1] *2,同样满足,那么此时就标记为一种方法,但其实只满足的一倍和,会导致计数重复。

#include<iostream>
using namespace std;
long long int a[500005];
int main()
{
    int n;
    cin>>n;
    long long int x = 0,ans = 0;
    for(int i = 0;i<n;i++)
    {
        cin>>a[i];
        if(i>=1)
            a[i] = a[i] + a[i-1];
    }
    for(int i = 0;i<n-1;i++)//注意是循环到n-2 
    {
        //这两句话顺序不能颠倒 当一倍和 和 二倍和是0的时候 
        if(a[i]*3 == a[n-1]*2) ans+=x;
        if(a[i]*3 == a[n-1]) x++;

    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_38293125/article/details/79586919