CF 466C Number of Ways(数学 / 思维 / DP)

Posted leonard-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CF 466C Number of Ways(数学 / 思维 / DP)相关的知识,希望对你有一定的参考价值。

题目链接:http://codeforces.com/problemset/problem/466/C

题目:

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
Copy
5
1 2 3 0 3
output
2
input
Copy
4
0 1 -1 0
output
1
input
Copy
2
4 1
output
0

 题解:前缀和暴力,找下规律。(好像还能用DP解,明天起来再看看!)

 1 #include <map>
 2 #include <cstdio>
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 typedef long long LL;
 8 const int N=1e6;
 9 LL f[N],c1[N],c2[N];
10 
11 int main(){
12     LL n,ans=0,cnt=0;
13     scanf("%lld",&n);
14     for(int i=1;i<=n;i++){
15         scanf("%lld",&f[i]);
16         f[i]+=f[i-1];
17         if(!f[i]) cnt++;
18     }
19     if(f[n]%3!=0) {printf("0\n");return 0;}
20     if(f[n]==0){
21         printf("%lld\n",(cnt-1)*(cnt-2)/2);
22         return 0;
23     }
24 
25     for(int i=1;i<=n;i++){
26         c1[i]=c1[i-1];c2[i]=c2[i-1];
27         if(f[i]==(f[n]/3)) c1[i]++;
28         if(f[i]==(f[n]/3*2)) c2[i]++;
29     }
30     for(int i=2;i<n;i++){
31         if(f[i]==(f[n]/3*2)) ans+=c1[i];
32     }
33     printf("%lld\n",ans);
34     return 0;
35 }

 

以上是关于CF 466C Number of Ways(数学 / 思维 / DP)的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces466C Number of Ways

数学CF27E Number With The Given Amount Of Divisors

1411. Number of Ways to Paint N × 3 Grid

C. Number of Ways 思维

Codeforces Round #266 (Div. 2)C. Number of Ways

Leetcode 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers