Problem:


Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

The input is given from Standard Input in the following format:

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.



Sample input:
4 8
7 9 8 9


Sample output:
5

Submission status: Time Limit Exceeded

Solution code:
n, a = map(int, input().split())
x = list(map(int, input().split()))
x_max = max(x)
dp = [[[0]*(x_max*n+1) for k in range(n+1)] for i in range(n+1)]
ans = 0
dp[0][0][0] = 1
for i in range(n):
    for j in range(i+2):
        for k in range(x_max*n+1):
            if k>= x[i]:
                dp[i+1][j][k] = dp[i][j-1][k-x[i]] + dp[i][j][k]
            elif k<x[i]:
                dp[i+1][j][k] = dp[i][j][k]
for k in range(x_max*n+1):
    for j in range(1,n+1):
        if a*j == k:
            ans += dp[n][j][k]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, a = map(int, input().split())
x = list(map(int, input().split()))
dp = [[[0]*(50*50+1) for k in range(n+1)] for i in range(n+1)]
ans = 0
dp[0][0][0] = 1
for i in range(n):
    for j in range(i+2):
        for k in range(50*50+1):
            if k>= x[i]:
                dp[i+1][j][k] = dp[i][j-1][k-x[i]] + dp[i][j][k]
            elif k<x[i]:
                dp[i+1][j][k] = dp[i][j][k]
for k in range(50*50+1):
    for j in range(1,n+1):
        if a*j == k:
            ans += dp[n][j][k]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,A = map(int,input().split())
x = list(map(int,input().split()))
ans = 0
for i in range(2**N):
    num = 0
    waru = 0
    for j in range(N):
        if (i>>j)&1:
            num += x[j]
            waru += 1
    if waru==0:
        ans += 0
    elif (num/waru)==A:
        ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,A=tuple(map(lambda x:int(x),input().split()))
x=tuple(map(lambda x:int(x),input().split()))
dp=np.zeros((n+1,n+1,n*A+1), dtype=int)
dp[:,0,0]=1
for i in range(1,n+1):
    for k in range(1, n+1):
        for j in range(1,n*A+1):
            if k<=i and 0<=j-x[i-1]:
                dp[i,k,j]=dp[i-1,k,j]+dp[i-1,k-1,j-x[i-1]]
            else:
                dp[i,k,j]=dp[i-1,k,j]
c=0
for k in range(1,n+1):
    c+=dp[n,k,k*A]
print(c)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,A=tuple(map(lambda x:int(x),input().split()))
x=tuple(map(lambda x:int(x),input().split()))
dp=np.zeros((n+1,n+1,n*A+1), dtype=int)
dp[0,0,0]=1
for i in range(1,n+1):
    for k in range(n+1):
        for j in range(n*A+1):
            if 1<=k<=i and 0<=j-x[i-1]:
                dp[i,k,j]=dp[i-1,k,j]+dp[i-1,k-1,j-x[i-1]]
            else:
                dp[i,k,j]=dp[i-1,k,j]
c=0
for k in range(1,n+1):
    c+=dp[n,k,k*A]
print(c)

Submission status: Time Limit Exceeded

Solution code:
#!/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_left_all_right_all(seq):
        '''
        seq を半分全列挙し、left_all, right_all の形で返す (right_all はソートを行ってから返す)
        '''
        n = len(seq)
        mid = n // 2
        left = seq[:mid]
        left_all = []
        la_app = left_all.append    # 定数倍高速化
        for p in product([True, False], repeat=mid):
            tmp = 0
            for i in range(mid):
                if p[i]:
                    tmp += left[i]
            # left_all.append(tmp)
            la_app(tmp)
        right = seq[mid:]
        right_all = []
        ra_app = right_all.append
        for p in product([True, False], repeat=n-mid):
            tmp = 0
            for i in range(n-mid):
                if p[i]:
                    tmp += right[i]
            # right_all.append(tmp)
            ra_app(tmp)
        right_all.sort()
        return (left_all, right_all)


    def calc_pattern(left_all, sorted_right_all, num):
        '''
        seq の要素を取り出して和を num にする場合の数
        left_all, right_all という形に半分全列挙済み、right_all はソート済みとする
        '''
        cnt = 0
        for i in left_all:
            if i <= num:
                cnt += bisect_right(sorted_right_all, num-i) - bisect_left(sorted_right_all, num-i)
        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 and len(diff_neg) != 0:
        pos_left_all, pos_right_all = calc_left_all_right_all(diff_pos)
        neg_left_all, neg_right_all = calc_left_all_right_all(diff_neg)

        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(pos_left_all, pos_right_all, i)
            pattern_neg = calc_pattern(neg_left_all, neg_right_all, 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()

Submission status: Time Limit Exceeded

Solution code:
#!/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_left_all_right_all(seq):
        '''
        seq を半分全列挙し、left_all, right_all の形で返す (right_all はソートを行ってから返す)
        '''
        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()
        return (left_all, right_all)


    def calc_pattern(left_all, sorted_right_all, num):
        '''
        seq の要素を取り出して和を num にする場合の数
        left_all, right_all という形に半分全列挙済み、right_all はソート済みとする
        '''
        cnt = 0
        for i in left_all:
            if i <= num:
                cnt += bisect_right(sorted_right_all, num-i) - bisect_left(sorted_right_all, num-i)
        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 and len(diff_neg) != 0:
        possible_max = min(sum(diff_pos), sum(diff_neg))
        possible_min = max(min(diff_pos), min(diff_neg))
        pos_left_all, pos_right_all = calc_left_all_right_all(diff_pos)
        neg_left_all, neg_right_all = calc_left_all_right_all(diff_neg)

        for i in range(possible_min, possible_max + 1):
            pattern_pos = calc_pattern(pos_left_all, pos_right_all, i)
            pattern_neg = calc_pattern(neg_left_all, neg_right_all, 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()

Submission status: Time Limit Exceeded

Solution code:
#!/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 and 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()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


def add2(l):
    ys = np.empty(0, dtype=int)
    for i in range(len(l)):
        zs = l[i] + l[i+1:]
        ys = np.concatenate([ys, zs], 0)
    return ys


def add(n, l):
    if len(l) == 0:
        return np.empty(0)
    elif n == 1:
        return l
    elif n == 2:
        return add2(l)
    else:
        ys = add(n, l[1:])
        zs = l[0] + add(n-1, l[1:])
        return np.concatenate([ys, zs], 0)


def main():
    n, a = (int(x) for x in input().split())
    xs = np.array([int(x) for x in input().split()], dtype='int')
    tot = np.sum(xs)

    if n == 1:
        # count = len([x for x in xs if x == a])
        count = np.sum(xs == a)
    else:
        count = 0
        lop = n // 2 + 1
        for i in range(1, n//2+1):
            ys = add(i, xs)
            count += np.sum(ys == a * i)
            if n - i > i:
                zs = tot - ys
                count += np.sum(zs == a * (n - i))
        if np.sum(xs) == n * a:
            count += 1

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def add2(l):
    ys = []
    for i in range(len(l)):
        ys += [l[i] + x for x in l[i+1:]]
    return ys


def add(n, l):
    if not l:
        return []
    elif n == 1:
        return l
    elif n == 2:
        return add2(l)
    else:
        ys = add(n, l[1:])
        ys += [l[0] + x for x in add(n-1, l[1:])]
        return ys


def main():
    n, a = (int(x) for x in input().split())
    xs = [int(x) for x in input().split()]
    tot = sum(xs)

    if n == 1:
        count = len([x for x in xs if x == a])
    else:
        count = 0
        lop = n // 2 + 1
        for i in range(1, n//2+1):
            ys = add(i, xs)
            count += len([y for y in ys if y == a * i])
            if n - i > i:
                zs = [tot - x for x in ys]
                count += len([z for z in zs if z == a * (n - i)])
        if sum(xs) == n * a:
            count += 1

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def add2(l):
    ys = []
    for i in range(len(l)):
        ys += [l[i] + x for x in l[i+1:]]
    return ys


def add(n, l):
    if not l:
        return []
    elif n == 1:
        return l
    elif n == 2:
        return add2(l)
    else:
        ys = [x for x in add(n, l[1:])]
        ys += [l[0] + x for x in add(n-1, l[1:])]
        return ys


def main():
    n, a = (int(x) for x in input().split())
    xs = [int(x) for x in input().split()]
    tot = sum(xs)

    if n == 1:
        count = len([x for x in xs if x == a])
    else:
        count = 0
        lop = n // 2 + 1
        for i in range(1, n//2+1):
            ys = add(i, xs)
            count += len([y for y in ys if y == a * i])
            if n - i > i:
                zs = [tot - x for x in ys]
                count += len([z for z in zs if z == a * (n - i)])
        if sum(xs) == n * a:
            count += 1

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def add2(l):
    ys = []
    for i in range(len(l)):
        ys += [l[i] + x for x in l[i+1:]]
    return ys


def add(n, l):
    if not l:
        return []
    elif n == 1:
        return l
    elif n == 2:
        return add2(l)
    else:
        ys = [x for x in add(n, l[1:])]
        ys += [l[0] + x for x in add(n-1, l[1:])]
        return ys


def main():
    n, a = (int(x) for x in input().split())
    xs = [int(x) for x in input().split()]
    tot = sum(xs)

    if n == 1:
        count = len(list(filter(lambda x: x == a, xs)))
    else:
        count = 0
        lop = n // 2 + 1
        for i in range(1, n//2+1):
            ys = add(i, xs)
            count += len(list(filter(lambda x: x == a * i, ys)))
            if n - i > i:
                zs = [tot - x for x in ys]
                count += len(list(filter(lambda x: x == a * (n - i), zs)))
        if sum(xs) == n * a:
            count += 1

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def add2(l):
    ys = []
    for i in range(len(l)):
        ys += [l[i] + x for x in l[i+1:]]
    return ys


def add(n, l):
    if not l:
        return []
    elif n == 1:
        return l
    elif n == 2:
        return add2(l)
    else:
        ys = [x for x in add(n, l[1:])]
        ys += [l[0] + x for x in add(n-1, l[1:])]
        return ys


def main():
    n, a = (int(x) for x in input().split())
    xs = [int(x) for x in input().split()]
    tot = sum(xs)

    if n == 1:
        count = len(list(filter(lambda x: x == a, xs)))
    else:
        count = 0
        lop = n // 2 + 1
        for i in range(1, n//2+1):
            ys = add(i, xs)
            count += len(list(filter(lambda x: x == a * i, ys)))
            if n - i > i:
                zs = list(map(lambda x: tot - x, ys))
                count += len(list(filter(lambda x: x == a * (n - i), zs)))
        if sum(xs) == n * a:
            count += 1

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def add2(l):
    ys = []
    for i in range(len(l)):
        ys += [l[i] + x for x in l[i+1:]]
    return ys


def add(n, l):
    if not l:
        return []
    elif n == 2:
        return add2(l)
    else:
        ys = [x for x in add(n, l[1:])]
        ys += [l[0] + x for x in add(n-1, l[1:])]
        return ys


def main():
    n, a = (int(x) for x in input().split())
    xs = [int(x) for x in input().split()]

    count = len(list(filter(lambda x: x == a, xs)))
    for i in range(2, n+1):
        ys = add(i, xs)
        count += len(list(filter(lambda x: x == a * i, ys)))

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy


def add2(l):
    ys = []
    for i in range(len(l)):
        ys += [l[i] + x for x in l[i+1:]]
    return ys


def add(n, l):
    if not l:
        return []
    elif n == 2:
        return add2(l)
    else:
        ys = [x for x in add(n, l[1:])]
        ys += [l[0] + x for x in add(n-1, l[1:])]
        return ys


def main():
    n, a = (int(x) for x in input().split())
    xs = [int(x) for x in input().split()]

    # i == 1
    ys = copy.deepcopy(xs)
    count = len(list(filter(lambda x: x == a, ys)))

    # i == 2 ~ n-2
    for i in range(2, n+1):
        ys = add(i, xs)
        count += len(list(filter(lambda x: x == a * i, ys)))
    '''
    # i == n-1
    ys = [sum(xs[:i]+xs[i+1:]) for i in range(n)]
    print(ys)
    count += len(list(filter(lambda x: x == a * (n - 1), ys)))

    # i == n
    if sum(xs) == n*a:
        count += 1
    '''
    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy


def add2(l):
    ys = []
    for i in range(len(l)):
        ys += [l[i] + x for x in l[i+1:]]
    return ys


def add(n, l):
    if not l:
        return []
    elif n == 2:
        return add2(l)
    else:
        ys = [x for x in add(n, l[1:])]
        ys += [l[0] + x for x in add(n-1, l[1:])]
        return ys


def main():
    n, a = (int(x) for x in input().split())
    xs = [int(x) for x in input().split()]

    ys = copy.deepcopy(xs)
    count = len(list(filter(lambda x: x == a, ys)))
    for i in range(2, n+1):
        ys = add(i, xs)
        count += len(list(filter(lambda x: x == a * i, ys)))

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from itertools import combinations
    n, a, *x = map(int, open(0).read().split())
    ans = 0
    for i in range(1, n + 1):
        for c in combinations(x, i):
            v = sum(c) / i
            if v == a:
                ans += 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,a = map(int,input().split())
x = [int(i) for i in input().split()]
dp = [[[0]*(n+1) for _ in range(n*a+1)] for _ in range(n+1)] 
for k in range(n+1): dp[0][0][k] = 1

for i in range(1,n+1):
    for j in range(1,n*a+1):
        for k in range(1,n+1):
            dp[i][j][k] = dp[i][j][k-1]
            if j - x[k-1] >= 0:
                dp[i][j][k] += dp[i-1][j-x[k-1]][k-1]
ans = 0
for i in range(1,n+1): ans += dp[i][a*i][n]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
from itertools import combinations

def main():
    N, A = map(int, input().split(" "))
    x = list(map(int, input().split(" ")))
    count = 0
    x.sort()
    for i in range(1, N+1):

        comb = filter(lambda x: sum(x) / i - A == 0, list(combinations(x, i)))
        count += len(list(comb))

    print(count)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n,a = map(int,input().split())
x = list(map(int,input().split()))
ans = 0
for i in range(2**n):
  y = []
  item = 0
  for j in range(n):
    if ((i >> j) & 1):
      y.append(x[j])
      item += 1
  if item != 0 and sum(y) == item*a:
    ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

def avg(ary):
  size = len(ary)
  return sum(i for i in ary)/size

n, a = [int(i) for i in input().split(" ")]
ary = [int(i) for i in input().split(" ")]

ary_list = []
for i in range(len(ary)):
  tmp = list(itertools.combinations(ary, i + 1))
  ary_list[0:0] = tmp

print(len(list(filter(lambda x: avg(x) == a, ary_list))))

Submission status: Time Limit Exceeded

Solution code:
N, A = map(int, input().split())
num = sorted(list(map(int, input().split())))
cnt = 0

for i in range(1, 2**N):
    bin_str = format(i, '0{}b'.format(N))
    t = 0
    ave = 0
    for j in range(N):
        t += num[j]*int(bin_str[j])
        ave += A* int(bin_str[j])
    if t == ave:
        cnt +=1

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import itertools

configs = list(map(int, input().split()))
nums = list(map(int, input().split()))

target_avg = configs[1]
pattern_num = 0

for use_num in range(1, configs[0]+1):
    for pair in itertools.combinations(nums, use_num):
        this_sum = sum(pair)
        if this_sum / use_num == target_avg:
            pattern_num += 1

print(pattern_num)

Submission status: Time Limit Exceeded

Solution code:
import itertools

configs = list(map(int, input().split()))
nums = list(map(int, input().split()))

target_avg = configs[1]
pattern_num = 0

for use_num in range(1, configs[0]+1):
    for pair in itertools.combinations(nums, use_num):
        this_sum = sum(list(pair))
        if this_sum / use_num == target_avg:
            pattern_num += 1

print(pattern_num)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline
from collections import Counter

def main():
    N, A = map(int, readline().rstrip().split())
    X = list(map(int, readline().rstrip().split()))
    X = [x-A for x in X]
    ans = 0
    X1 = X[:N//2]
    X2 = X[N//2:]
    X1_sum = [0]
    for i in range(1, 2**len(X1)):
        b = bin(i)[2:].zfill(len(X1))
        su = sum([X1[i] for i, e in enumerate(b) if e == '1'])
        X1_sum.append(su)
    X2_sum = [0]
    for i in range(1, 2**len(X2)):
        b = bin(i)[2:].zfill(len(X2))
        su = sum([X2[i] for i, e in enumerate(b) if e == '1'])
        X2_sum.append(su)
    c = Counter(X2_sum)
    c_keys = c.keys()
    for x1 in X1_sum:
        if -x1 in c_keys:
            ans += c[-x1]

    print(ans - 1)

    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n, a = map(int, input().split())
x = list(map(int, input().split()))

dp = [[[0] * 2501 for _ in range(51)] for _ in range(51)]
dp[0][0][0] = 1

for i in range(n):
    for j in range(n):
        for k in range(2501):
            if k + x[i] <= 2500:
                dp[i+1][j+1][k+x[i]] += dp[i][j][k]
            dp[i+1][j][k] += dp[i][j][k]


ans = 0
for j in range(1, n+1):
    ans += dp[n][j][j * a]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    N, A = list(map(int, input().split()))
    X = sorted(list(map(int, input().split())))
    cnt = 0
    for bits in range(1, 1<<N):
        flags = list(bin(bits)[2:].zfill(N))
        _X = [x for i, x in enumerate(X) if flags[i]=="1"]
        cnt += 1 if sum(_X)/len(_X) == A else 0
    print(cnt)
    


if '__main__' == __name__:
    resolve()

Submission status: Time Limit Exceeded

Solution code:
n,a=map(int,input().split())
x=list(map(int,input().split()))
t=[[[0]*(n*a+1) for k in range(n+1)]for j in range(n+1)]
ans=0
for j in range(n+1):
  for k in range(n+1):
    if k>j:
      break
    for s in range(n*a+1):
      if s==0 and k==0 and j==0:
        t[j][k][s]=1
      elif j>=1 and x[j-1]>s:
        t[j][k][s]=t[j-1][k][s]
      elif j>=1 and k>=1 and x[j-1]<=s:
        t[j][k][s]=t[j-1][k][s]+t[j-1][k-1][s-x[j-1]]
      if j==n and k>=1 and s==k*a:
        ans+=t[j][k][s]
print(ans)