Description
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Sample Input
4 1 2 3 3
1
5 1 2 3 4 5
0
题意 给一串长N的数列,把它们划成3段使每段和相等(数列的顺序不能打乱)
解析
标算动规,开始我用二分强行水过(附代码)就是看前缀和为piece和后缀和为piece的能凑成多少对
//二分强行水过
#include<cstdio>
#include<vector>
using namespace std;
typedef long long LL;
LL prefix[100100],a[100100],N;
LL qr[100100],ql[100100],suml,sumr;
int cal(LL x)//二分[l,r)
{
int l=1,r=sumr+1;
while(l<r)
{
int mid=(l+r)>>1;
if(qr[mid]<=x) r=mid;
else l=mid+1;
}
return l-1;
}
int main()
{
scanf("%I64d",&N);
for(int i=1;i<=N;i++)
{
scanf("%I64d",&a[i]);
prefix[i]=a[i]+prefix[i-1];
}
if(prefix[N] % 3 != 0){printf("0");return 0;}
LL piece=prefix[N]/3;
suml=0;sumr=0;
int suffix=0;
for(int i=N;i>=1;i--)
{
if(prefix[i]==piece) ql[++suml]=i;
suffix=a[i]+suffix;
if(suffix==piece) qr[++sumr]=i;
}
LL ans=0;
for(int i=1;i<=suml;i++)//1end
{
ans+=cal(ql[i]+1);
}
printf("%I64d",ans);
return 0;
}
动规思路:也是把前缀和为piece和前缀和为piece*2凑对子 sum记录的是之前前缀和为piece的个数,因为在后面每次遇到的piece*2的一定可以与之前的piece配对,所以每次遇到piece*2都ans+=sum;
这里有一个特殊情况:
5
0 0 0 0 0
在这种情况下piece==piece*2==piece*3
特别注意每段不可为空的限制条件,所以:
1.if(prefix_sum[i]==piece*2) ans+=sum;要在if(prefix_sum[i]==piece) sum++;之前操作(否则第2段为空)
2.for(int i=1;i<N;i++)而不是for(int i=1;i<=N;i++) (否则i==N时第3段为空)
//动规
#include<cstdio>
using namespace std;
int N;
long long prefix_sum[100100];
int main()
{
scanf("%d",&N);
for(int i=1;i<=N;i++)
{
int a; scanf("%d",&a);
prefix_sum[i]=a+prefix_sum[i-1];
}
if(prefix_sum[N] % 3 != 0) {printf("0"); return 0;}
long long ans=0,sum=0,piece=prefix_sum[N]/3;
for(int i=1;i<N;i++)
{
if(prefix_sum[i]==piece*2) ans+=sum;
if(prefix_sum[i]==piece) sum++;
}
printf("%I64d",ans);
return 0;
}