1. 程式人生 > >codeforces-466C-Number of Ways

codeforces-466C-Number of Ways

466C-Number of Ways

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.

input
5
1 2 3 0 3
output
2
input
4
0 1 -1 0
output
1
input
2
4 1
output
0

題目大意:給出一個n長度序列,問多少種方法使得這個n長度序列分成3份,每一份值都相同

題目思路:這裡寫圖片描述
找到一個1/3的地方則ret++,找到一個2/3的地方就+=ret

以下是程式碼:

//
//  466C.cpp
//  codeforces
//
//  Created by pro on 16/4/9.
//  Copyright (c) 2016年 loy. All rights reserved.
//

#include <cstdio>
#include <iostream> #include <algorithm> #include <map> using namespace std; int num[500005]; long long Sum[500005]; int main() { int n; cin >> n; long long s = 0; for (int i = 1; i <= n; i++) { cin >> num[i]; Sum[i] = Sum[i - 1] + num[i]; s += num[i]; } long long ret = 0,ans = 0; for (int i = 1; i < n; i++) { if (Sum[i] * 3 == 2 * s) //找到中間點即,2/3位置 { ans += ret; } if (Sum[i] * 3 == s) //找到第一部分結尾 { ret++; } } cout << ans << endl; return 0; }