首页 > 试题广场 >

喜欢切数组的红

[编程题]喜欢切数组的红
  • 热度指数:9210 时间限制: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
k = int(input())
nums = list(map(int, input().split()))


def count_solution(nums_list):
    sum_list = []
    positive_list = []
    sum_temp = 0
    for num in nums_list:
        if num > 0:
            positive_list.append(1)
        else:
            positive_list.append(0)
        sum_temp += num
        sum_list.append(sum_temp)
    first_son_sum = sum_list[-1] / 3
    # 寻找第一次分割
    frist_maybe_c = sum_list.count(first_son_sum)
    if frist_maybe_c == 0:
        return 0
    else:
        frist_maybe_index = []
        i = -1
        while len(frist_maybe_index) < frist_maybe_c:
            i = sum_list.index(first_son_sum, i + 1)
            frist_maybe_index.append(i)
        # 寻找第二次分割位置
        second_maybe_index = []
        second_son_sum = 2 * first_son_sum
        second_maybe_c = sum_list.count(second_son_sum)
        i = 0  # 第二次不可能从第一位开始分割
        while len(second_maybe_index) < second_maybe_c:
            i = sum_list.index(second_son_sum, i + 1)
            # 防止出现和为零时导致第二次分割的位置在末尾
            if i < len(nums_list):
                second_maybe_index.append(i)
        all_solotion = []
        for m in frist_maybe_index:
            for n in second_maybe_index:
                if m < n:  # 呃附着的出现可能会导致N大于M
                    # 保证三个数组都有正shu存在
                    if (
                        sum(positive_list[: m + 1]) > 0
                        and sum(positive_list[m : n + 1]) > 0
                        and sum(positive_list[n:]) > 0
                    ):
                        all_solotion.append([m, n])
    return len(all_solotion)


print(count_solution(nums))
#超时,通过率50%,就当给大家提供思路吧

发表于 2025-04-13 18:13:04 回复(0)