Codeforces Round #266 (Div. 2)C. Number of Ways(想法题)

传送门

Description

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.

Sample Input

5
1 2 3 0 3
4
0 1 -1 0

2
4 1

Sample Output

2

1

0

思路

题意:

给定n个数,将这n个数分成连续的三组,每组数的和相同,有几种分法。

题解:

维护一个前缀和与一个后缀和,找出前缀和为 sum / 3的位置,后缀和为 sum / 3的位置,组合搭配得出结果。一个降低复杂度的技巧,记录下后缀和为 sum / 3的组数,用cnt[pos]表示pos位置开始和为sum / 3的组数,然后从头遍历的时候,当在位置pos时,前缀和为 sum / 3,则方案数有cnt[pos]种,注意:sum /3 为0时,方案数应该为 cnt[pos + 2]种。

 

  

posted @   zxzhang  阅读(226)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航