首页 > 试题广场 >

喜欢切数组的红

[编程题]喜欢切数组的红
  • 热度指数:9308 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 512M,其他语言1024M
  • 算法知识视频讲解
\hspace{15pt}小红有一个长度为 n 的数组 \{a_1,a_2,\dots,a_n\} ,她打算将数组切两刀变成三个非空子数组,使得每一个子数组中至少存在一个正数,且每个子数组的和都相等。
\hspace{15pt} 看起来不是很难,所以小红想让你求解,一共有多少种不同的切分方案。

输入描述:
\hspace{15pt}第一行输入两个整数 n \left( 3 \leqq n \leqq 2 \times 10^5 \right) 代表数组中的元素数量。
\hspace{15pt}第二行输入 n 个整数 a_1,a_2,\dots,a_n \left( -10^9 \leqq a_i \leqq 10^9 \right) 代表数组元素。


输出描述:
\hspace{15pt}在一行上输出一个整数,代表切分方案数。
示例1

输入

3
3 3 3

输出

1
示例2

输入

6
1 1 4 5 1 4

输出

0
示例3

输入

10
0 3 4 2 3 2 1 -1 3 4

输出

2
测试集中有规模超过10000的数据,因此算法的时间复杂度不能达到或超过O(n^2),贴一个自己的算法
while 1:
    try:
        n = int(input())
        ls = list(map(int,input().split()))
        if sum(ls)%3 != 0:
            print(0)
            break
        ans1 = sum(ls)//3
        ans2 = ans1*2
        sumls = [0]
        pls = [0]
        for i in range(n):
            sumls.append(sumls[-1]+ls[i])
            if ls[i]>0:
                pls.append(pls[-1]+1)
            else:
                pls.append(pls[-1])
        sumls = sumls[1:]
        pls = pls[1:]
        count = 0
        ans1ind = []
        ans2ind = []
        for i in range(n):
            if sumls[i]==ans1 and pls[i]>0:
                ans1ind.append(i)
            elif sumls[i]==ans2 and pls[-1]-pls[i]>0:
                ans2ind.append(i)
        for x in ans1ind:
            for y in ans2ind:
                if x<y and pls[y]-pls[x]>0:
                        count += 1
        print(count)
        break
    
    except:
        break


发表于 2025-10-08 20:06:35 回复(0)
num = int(input())
num_list = input().split(" ")
num_list = [int(item) for item in num_list]

obj = sum(num_list) / 3
if not obj == int(obj):
    print(0)
    exit(0)

sum_prefix = [0] * num
count_prefix = [0] * num
loc_dic = {"m": [], "2m": []}

temp = 0
count = 0
for i in range(0, num):
    if num_list[i] > 0:
        count += 1
    temp = temp + num_list[i]
    sum_prefix[i] = temp
    count_prefix[i] = count
    if temp == obj:
        loc_dic["m"].append(i)
    if temp == 2 * obj:
        loc_dic["2m"].append(i)

res = 0
for L in loc_dic["m"]:
    for R in loc_dic["2m"]:
        if L < R and count_prefix[R] - count_prefix[L] > 0:
            res += 1

print(res)
最后一个过不了, 超时了
发表于 2025-03-06 20:39:32 回复(0)