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
Copy
5
1 2 3 0 3
output
Copy
2
input
Copy
4
0 1 -1 0
output
Copy
1
input
Copy
2
4 1
output
Copy
0
题意:一段数组,分三块“和”相同的块,问有多少种分法?
思路:用前缀和
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstring>
#include<string>
#include<iostream>
#include<iomanip>
#define mset(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
//const ll mod=1e9+7;
const int N=1000000;
const int inf=0x3f3f3f3f;
//priority_queue<int,vector<int>,greater<int> >q;
ll a[500005];
int main()
{
int n;
while(~scanf("%d",&n))
{
ll sum=0;
a[0]=0;
for(int i=0;i<n;i++)
{
scanf("%lld",&a[i]);
a[i]+=a[i-1];
}
// for(int i=0;i<n;i++)
// printf("%lld ",a[i]);printf("\n");
if(a[n-1]%3)
printf("0\n");
else
{
for(int i=0;i<n-1;i++)
{
if(a[i]*3==a[n-1])
{
for(int j=i+1;j<n-1;j++)
{
if(a[j]*3==a[n-1]*2)
{
sum++;
}
}
}
}
printf("%lld\n",sum);
}
}
return 0;
}
上面爆搜…………超时…………我也很无奈啊 ,然后是下面
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstring>
#include<string>
#include<iostream>
#include<iomanip>
#define mset(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
//const ll mod=1e9+7;
const int N=1000000;
const int inf=0x3f3f3f3f;
//priority_queue<int,vector<int>,greater<int> >q;
ll a[500005];
int main()
{
int n;
while(~scanf("%d",&n))
{
ll sum=0;
ll ans=0;
a[0]=0;
for(int i=0;i<n;i++)
{
scanf("%lld",&a[i]);
a[i]+=a[i-1];
}
// for(int i=0;i<n;i++)
// printf("%lld ",a[i]);printf("\n");
if(a[n-1]%3)
printf("0\n");
else
{
for(int i=0;i<n-1;i++)
{
if(a[i]*3==a[n-1]*2)
sum+=ans;//第二块和第三块
if(a[i]*3==a[n-1])
ans++;//第一块和第三块
}
printf("%lld\n",sum);
}
}
return 0;
}