codeforces 466 C. Number of Ways
http://codeforces.com/problemset/problem/466/C 题意:给定一个序列。要将序列分成三个非零的连续部分,使得三部分的和相等。问有多少中分法。 思路:首先可以知道,如果是序列的和不为3的倍数,那么一定无解,输出0.设序列的和为sum,那么每一部分的和就应该为sum/3。我们可以预处理出从1开始的和为sum/3的点(我开了数组表示前缀和。。想了下其实不用。。我只需要点的信息。。所以用一个变量表示即可),将点的下标存在p[i]里。对于每一个p[i],我想要知道比p[i]大且补与p[i]相邻的点中,有多少个j,使得从j到n的和为sum/3。因为如果有两部分的和都为sum/3,那么剩下的那部分也一定为sum/3.然后要知道有多少个满足题意的j,我们可以从后往前扫一遍,标记从n开始往前扫,和为sum/3的点,可以用一个0,1数组表示。如果和为sum/3,那么标记为1,否则为0.然后再用一个类似前缀和的思路。再开一个数组c记录从j到n有的和为多少,也就是从j到n有多少个点满足该点到n的和为sum/3.
预处理完这些之后。只需要从前往后扫一遍p[i],然后ans+=c[p[i]+2]即可。
/* ***********************************************
Author :111qqz
Created Time :2015年12月15日 星期二 20时28分44秒
File Name :code/cf/problem/466C.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=5E5+7;
7int n;
8int a[N];
9LL sum[N],rsum[N];
10int p[N],rp[N];
11int cnt,rcnt;
12int b[N];
13int c[N];
14LL ans;
15LL solve()
16{
17 LL total = sum[n];
18 if (total%3!=0) return 0;
19 LL ave = total/3;
20 cnt = 0 ;
21 for ( int i = 1 ; i <= n ; i++)
22 {
23 if (sum[i]==ave)
24 {
25 cnt++;
26 p[cnt] = i;
27 // cout<<"i:"<<i<<endl;
28 }
29 }
30 ms(b,0);
31 for ( int i = n ; i >= 1 ; i--)
32 {
33 if (rsum[i]==ave)
34 {
35 b[i] = 1; //b[i]为1表示可以,为0表示不可以。
36 }
37 }
38 c[n] = b[n]; //c[i]表示i..n一共有多少个b[i]可以。
39 for ( int i = n-1 ; i >= 1 ; i--)
40 {
41 c[i] = c[i+1] + b[i];
42 }
1 LL res = 0 ;
2 for ( int i = 1 ; i <= cnt ; i++)
3 {
4 res+= c[p[i]+2]; //中间至少隔一个,因为要分成三组。
5 }
6 return res;
1}
2int main()
3{
4 #ifndef ONLINE_JUDGE
5 freopen("code/in.txt","r",stdin);
6 #endif
cin>>n;
sum[0] = 0 ;
1 for ( int i = 1 ; i <= n ; i++)
2 {
3 scanf("%d",&a[i]);
4 sum[i] = sum[i-1] + a[i];
5 }
6 rsum[n+1] = 0 ;
7 for ( int i = n ; i >= 1 ; i --)
8 {
9 rsum[i] = rsum[i+1] + a[i];
10 }
11 ans = solve();
12 cout<<ans<<endl;
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}