Problem p04013 (python)

Fixed submission:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, a = mi()
    L = lmi()
    diff = [elm - a for elm in L]
    # dp[i][num] = (diff から i 番目までを使用して和を num - 2500 にする場合の数)
    dp = [[0] * 5001 for _ in range(n + 1)]
    dp[0][2500] = 1

    for i in range(n):
        for j in range(5001):
            if dp[i][j]:
                dp[i+1][j + diff[i]] += dp[i][j]
            dp[i+1][j] += dp[i][j]
    

    print(dp[n][2500] - 1)    # n 番目までを使用して和を 0 にするには？ 最初の何も選ばない 1 通りを除く


if __name__ == "__main__":
    main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    def calc_pattern(seq, num):
        '''
        seq の要素を取り出して和を num にする場合の数
        '''
        cnt = 0
        n = len(seq)
        mid = n // 2
        left = seq[:mid]
        left_all = []
        for p in product([True, False], repeat=mid):
            left_all.append(sum([left[i] for i in range(mid) if p[i]]))
        right = seq[mid:]
        right_all = []
        for p in product([True, False], repeat=n-mid):
            right_all.append(sum([right[i] for i in range(n-mid) if p[i]]))
        right_all.sort()
        for i in left_all:
            if i <= num:
                cnt += bisect_right(right_all, num-i) - bisect_left(right_all, num-i)
        # debug
        # if num == 1:
        #     print(f"{seq} {left} {right} {left_all} {right_all}")
        return cnt

    
    n, a = mi()
    L = lmi()
    diff = [elm - a for elm in L]
    diff_neg = list(map(lambda x: - x, filter(lambda x: x < 0, diff)))
    diff_zero = list(filter(lambda x: x == 0, diff))
    diff_pos = list(filter(lambda x: x > 0, diff))


    ans = 0
    # pos, neg から 1 つも選ばない
    ans += pow(2, len(diff_zero)) - 1    # diff_zero の全てを選ばないのは許されぬ
    # pos, neg から 選ぶ ... diff_zero から選ぶものは 2 ^ len(diff_zero) 通り
    if len(diff_pos) != 0 or len(diff_neg) != 0:
        possible_max = min(sum(diff_pos), sum(diff_neg))
        possible_min = max(min(diff_pos), min(diff_neg))
        for i in range(possible_min, possible_max + 1):
            pattern_pos = calc_pattern(diff_pos, i)
            pattern_neg = calc_pattern(diff_neg, i)
            # debug
            # if pattern_pos > 0 and pattern_neg > 0:
            #     print(f"{i} {pattern_pos} {pattern_neg}")
            ans += pattern_pos * pattern_neg * pow(2, len(diff_zero))
    
    print(ans)



if __name__ == "__main__":
    main()