标签:
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 .
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.
Print a single integer — the number of ways to split the array into three parts with the same sum.
大意是给你n个数,将他们分成连续的三个部分使得每个部分的和相同,求出分法的种数。
做法是用一个数组a[i]记下从第一个点到当前i点的总和。最后一个点是总和为sum的点,只需求出总和为1/3sum的点和总和为2/3sum的点搭配的所有情况。遍历一遍总和为2/3sum的点前总和为1/3sum的点的个数。
#include<stdio.h> #include<string.h> #include<iostream> using namespace std; const int MAXN=500005; typedef long long ll; ll a[MAXN]; int main() { int n; while(~scanf("%d",&n)) { a[0]=0; for(int i=1;i<=n;i++) { cin>>a[i]; a[i]=a[i]+a[i-1]; } if(a[n]%3!=0) { printf("0\n"); continue; } ll sum1=a[n]/3; ll sum2=sum1*2; int cn1=0;ll cut=0; for(int i=1;i<n;i++) { if(a[i]==sum2 ) { cut+=cn1; } if(a[i]==sum1 && i<n-1) { cn1++; } } cout<<cut<<endl; } return 0; }
应该模拟过程而不是自己考虑多种情况做成数学题(...),还有一个点是记录总和的数组以及记录总和的值应用long long,认真读题,看清题目数据范围,不要怕就是干。
I
cmp写错过...最开始两个语句写反了以为效果一样...
bool cmp(post a,post b) { if(a.x==b.x) return a.y<b.y; return a.x<b.x; }
标签:
原文地址:http://www.cnblogs.com/LinesYao/p/5449670.html