codeforces_466_C Python练习

本文解析了CodeForces466C题目,介绍了一种利用动态规划求解将数组分为三等和子数组的方法。通过计算前缀和,遍历数组并统计符合条件的分割方式,实现高效求解。

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)

  

转载于:https://www.cnblogs.com/oxxxo/p/9823205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值