codeforces_466_C Python练习
codeforces466C 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 .
原意:n个数组,切2刀,找出.的次数
题解:a[i]的总和为3的倍数的话,有解。设X=(sum(a[i]))/3,dp[i]=dp[i-1]+a[i](前i个a的总和)。
遍历一遍dp,找到dp[i]=X*2的时候,timg+time;找到dp[i]=X的时候time+1,最后输出timg
因为我们知道找到一个dp[i]=X的时候,就是一次切法,time+1;
那么找到dp[i]=X*2的时候,可能是一次切法,也可能不是(因为负数的存在)。如果找到的dp[i]=X*2在之前的i有过dp[k]=X(k<i),那么,就算作是一次切法,那么就timg+time;
(看官方Tag是binary search、 brute force、 data structures 、dp 、two pointers, 太复杂的证法我也不会,反正感觉这样做就是对的)
代码:
n = int(input()) a = list(map(int,input().split())) dp = list(range(0,n+1)) dp[0] =a[0] for i in range(1,n): dp[i] = dp[i-1]+a[i] if (dp[n-1] %3 != 0): print(0) exit() div = dp[n-1]/3 time = 0 timg = 0 for i in range(0,n-1): if (dp[i] == div*2): timg += time if (dp[i] == div): time += 1 print(timg)