Array Partition

描述

Given an integer array A1, A2 ... AN, you are asked to split the array into three continuous parts: 
A1, A2 ... Ap | Ap+1, Ap+2, ... Aq | Aq+1, Aq+2, ... AN.

Let S1, S2 and S3 denote the sums of each part:

S1 = A1 + A2 + ... + Ap

S2 = Ap+1 + Ap+2 + ... + Aq

S3 = Aq+1 + Aq+2 + ... + AN

A partition is acceptable if and only if the differences between S1, S2 and S3
 (i.e. |S1 - S2|, |S2 - S3|, |S3 - S1|) are no more than 1.

Can you tell how many different partitions are acceptable?

输入

The first line contains an integer N.

The second line contains N integers, A1, A2 ... AN.

For 30% of the data, N ≤ 100

For 70% of the data, N ≤ 1000

For 100% of the data, N ≤ 100000, -1000000 ≤ Ai ≤ 1000000

输出

The number of acceptable partitions.
样例解释

The three acceptable partitions are:

3 | 2 | 1 0 2

3 | 2 1 | 0 2

3 | 2 1 0 | 2
样例输入

5
3 2 1 0 2

样例输出

3

   思路:
        1.计算数组的前缀和
        2.枚举 注意p和q的数组范围
   时间复杂度O(n^2)
*/
#include <iostream>
using namespace std;

int n, a[100000 + 10],b[100000+10],ans;
int main()
{
	int s1, s2, s3;
	cin >> n;
	for (int i = 1; i <= n;i++)
	{
		cin >> a[i];
	}
	b[0] = 0;
	for (int i = 1; i <= n;i++)
	{
		//前缀和
		b[i] = b[i - 1] + a[i];
	}
	ans = 0;
	for (int p = 1; p <= n - 2;p++)
	{
		for (int q = p + 1; q <= n - 1;q++)
		{
			s1 = b[p];
			s2 = b[q] - b[p];
			s3 = b[n] - b[q];
			if (abs(s1-s2) &&abs(s1-s3)&&abs(s2-s3))
			{
				ans++;
			}
		}
	}
	cout << ans << endl;
	return 0;
}


猜你喜欢

转载自blog.csdn.net/m0_37806112/article/details/80729419
今日推荐