Problem:


Score : 500 points

Problem Statement

There are N cards. The i-th card has an integer A_i written on it.
For any two cards, the integers on those cards are different.

Using these cards, Takahashi and Aoki will play the following game:

Aoki chooses an integer x.

Starting from Takahashi, the two players alternately take a card. The card should be chosen in the following manner:

Takahashi should take the card with the largest integer among the remaining card.

Aoki should take the card with the integer closest to x among the remaining card. If there are multiple such cards, he should take the card with the smallest integer among those cards.

The game ends when there is no card remaining.

You are given Q candidates for the value of x: X_1, X_2, ..., X_Q.
For each i (1 \leq i \leq Q), find the sum of the integers written on the cards that Takahashi will take if Aoki chooses x = X_i.

Constraints

2 \leq N \leq 100 000

1 \leq Q \leq 100 000

1 \leq A_1 < A_2 < ... < A_N \leq 10^9

1 \leq X_i \leq 10^9 (1 \leq i \leq Q)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
A_1 A_2 ... A_N
X_1
X_2
:
X_Q

Output

Print Q lines. The i-th line (1 \leq i \leq Q) should contain the answer for x = X_i.

Sample Input 1

5 5
3 5 7 11 13
1
4
9
10
13

Sample Output 1

31
31
27
23
23

For example, when x = X_3(= 9), the game proceeds as follows:

Takahashi takes the card with 13.

Aoki takes the card with 7.

Takahashi takes the card with 11.

Aoki takes the card with 5.

Takahashi takes the card with 3.

Thus, 13 + 11 + 3 = 27 should be printed on the third line.

Sample Input 2

4 3
10 20 30 40
2
34
34

Sample Output 2

70
60
60



Sample input:
5 5
3 5 7 11 13
1
4
9
10
13


Sample output:
31
31
27
23
23

Submission status: Time Limit Exceeded

Solution code:
import bisect
INF = 10**12
n, q = [int(item) for item in input().split()]
a = [int(item) for item in input().split()]

# Calc cumrative sum
sum_even = [0] * (n + 1)
sum_odd = [0] * (n + 1)
sum_all = [0] * (n + 1)
for i, item in enumerate(a):
    if i % 2 == 0:
        sum_odd[i+1] = sum_odd[i] + a[i]
        sum_even[i+1] = sum_even[i]
    else:
        sum_even[i+1] = sum_even[i] + a[i]
        sum_odd[i+1] = sum_odd[i]
    sum_all[i+1] = sum_all[i] + a[i]

# Iterate in query
a.append(INF)
for i in range(q):
    # Get div of aoki - takahashi
    x = int(input())
    big = bisect.bisect_left(a, x)
    small = big - 1
    if (x - a[small]) ** 2 <= (x - a[big]) ** 2:
        l = small
    else:
        l = big
    r = n - 1
    while r - l > 1:
        m = (r + l) // 2
        rng = abs(x - a[m])
        taka = n - m
        aoki = n - taka - (bisect.bisect_left(a, x - rng))
        if taka <= aoki + 1:
            r = m
        else:
            l = m
    rng = abs(x - a[r])
    taka = n - r
    aoki = n - taka - (bisect.bisect_left(a, x - rng))
    taka_sum = sum_all[n] - sum_all[n - taka]
    aoki_sum = sum_all[r] - sum_all[r - taka]
    rest = n - taka * 2
    if rest > 0:
        if rest % 2 == 0:
            taka_sum += sum_even[rest]
            aoki_sum += sum_odd[rest]
        else:
            taka_sum += sum_odd[rest]
            aoki_sum += sum_even[rest]

    print(taka_sum)

Submission status: Time Limit Exceeded

Solution code:

import bisect

n, q = map(int, input().split())
a_list = list(map(int, input().split()))
xnum = [0]*q
for i in range(q):
    xnum[i] = int(input())

card = sorted(a_list)

for x in xnum:
    xpos = bisect.bisect(card, x)
    cnt = 0
    aoki_card = sorted(a_list, key=lambda a: (abs(a-x), a))
    for i, ac in enumerate(aoki_card):
        if ac > x:
            cnt += 1
        if i+1 + cnt >= n-xpos:
            break
    i += 1
    print(sum(card[-i:]) + (sum(card[:n-2*i][::-2]) if 2*i < n else 0))

Submission status: Time Limit Exceeded

Solution code:

import numpy as np
def gV(list, num):
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx
def nea(n,q,a,x):
    aa=a[:]
    taka=0
    for z in range(q):
        for i in range(n):
            if a[-i-1]==999999:
                pass
            else:
                taka+=a[-i-1]
                a[-i-1]=999999
                a[gV(a,x[z])]=999999
        print(taka)
        a=aa[:]
        taka=0

    exit()

n,q=map(int,input().split())
print(nea(n,q,list(map(int,input().split())),[int(input()) for i in range(q)]))

Submission status: Time Limit Exceeded

Solution code:
def gV(list, num):
    import numpy as np
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def nea(n,q,a,x):
    aa=a[:]
    taka=0
    for z in range(q):
        for i in range(n):
            if a[-i-1]==999999:
                pass
            else:
                taka+=a[-i-1]
                a[-i-1]=999999
                a[gV(a,x[z])]=999999
        print(taka)
        a=aa[:]
        taka=0

    exit()

n,q=map(int,input().split())
print(nea(n,q,list(map(int,input().split())),[int(input()) for i in range(q)]))

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split()) # NはリストAの要素数、Qはxの値の候補数
A = list(map(int, input().split())) # リストAは小さい方から順に並べられている
A_new = [list()] * Q
result = [0] * Q

for i in range(Q):
    
    x = int(input())
    A_new[i] = A[:]
    
    while A_new[i]:
        result[i] = result[i] + A_new[i].pop()
        if A_new[i]:
            for j in range(1000000000):
                if (x - j > 0) and (x - j in A_new[i]):
                    A_new[i].remove(x - j)
                    break
                if x + j in A_new[i]:
                    A_new[i].remove(x + j)
                    break

for i in range(Q):
    print(result[i])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
def solve(n, q, a, x):
    a = list(a)
    answer = 0
    while a:
        answer += a.pop()
        if a:
            _, i = min([ (abs(a_i - x), i) for i, a_i in enumerate(a) ])
            del a[i]
    return answer

n, q = map(int, input().split())
a = list(map(int, input().split()))
for _ in range(q):
    x = int(input())
    print(solve(n, q, a, x))

Submission status: Time Limit Exceeded

Solution code:
(N, Q)=list(map(int, input().split()))
A=list(map(int, input().split()))
X=[0] * Q
for x in range(Q):
    X[x] = int(input())

for x in X:
    vs=[]
    for i, v in enumerate(list(map(lambda a: a - x, A))):
        vs.append((i, v))

    list.sort(vs, key=lambda x: (abs(x[1]), x[1]))

    used=[False] * N
    aoki = N - 1   # in A
    takahashi = 0  # in vs

    count = 0
    use_count = 0
    num = 0
    while use_count < N:
        while used[aoki]:
            aoki -= 1
        used[aoki] = True
        count += A[aoki]
        aoki -= 1

        use_count += 1
        if use_count == N:
            break

        while used[vs[takahashi][0]]:
            takahashi += 1
        used[vs[takahashi][0]] = True
        takahashi += 1

        use_count += 1

    print(count)

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())
a = list(map(int, input().split()))
y = []

for i in range(Q):
  x = int(input())
  z = 0
  b = [a[j] - x for j in range(N)]
  c = list(map(abs, b))
  
  while len(b) > 1:
    z += b[len(b)-1]
    b.pop(len(b)-1)
    c.pop(len(c)-1)
    b.pop(c.index(min(c)))
    c.pop(c.index(min(c)))
    if len(b) == 1:
      z += b[0]
  z += x*((N+1)//2)
  y.append(z)

for i in range(Q):
  print(y[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from bisect import bisect_left
from itertools import accumulate

n,q = li()
a = list(li())
x = [ni() for _ in range(q)]


cum_nor = list(accumulate(a))
cum_odd = list(accumulate(a[::2]))
cum_evn = list(accumulate(a[1::2]))
cum_kog = [cum_odd[i//2] if i%2==0 else cum_evn[i//2] for i in range(n)]

def check(a:list, tak:int, pivot:int):
    rng = a[-tak] - pivot
    left = bisect_left(a, pivot-rng)
    right = bisect_left(a, pivot+rng)
    aok = right-left
    if aok >= tak-1:
        return True
    else:
        return False
    
def binsearch(a:list,xi:int):
    low = 1
    high = len(a)
    while high-low > 1:
        mid = (high+low) // 2
        if check(a,mid,xi):
            low = mid
        else:
            high = mid
            
    return low

for xi in x:
    tak = binsearch(a,xi)
    ans = cum_nor[-1] - cum_nor[-tak-1]
    if 2*tak < n:
        ans += cum_kog[-2*tak-1] 
    
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
input = sys.stdin.readline
N,Q = map(int,input().split())
A = list(map(int,input().split()))
for i in range(Q):
    A_ = A[:]
    x = int(input())
    sum = 0
    turn = 1
    while True:
        if len(A_) > 0 and turn > 0:
            #T
            '''
            print(1)
            print(A_)
            print()
            '''
            maxcard = max(A_)
            maxcardindex = A_.index(maxcard)
            sum += maxcard
            del A_[maxcardindex]
            turn = turn*-1
        elif len(A_) > 0 and turn < 0:
            #A
            '''
            print(-1)
            
            print(A_)
            print()
            '''
            A_x = []
            if len(A_) == 1:
                print(sum)
                break
            else:
                for i in range(len(A_)):
                    A_x.append(abs(A_[i]-x))
                '''
                print("x距離list")
                print(A_x)
                print()
                '''
                mindis = min(A_x)
                mdi = A_x.index(mindis)
                #print(mdi)
                del A_[mdi]
                '''
                print("x距離")
                print(A_)
                print()
                '''
                turn = turn*-1
        else:
            print(sum)
            break

Submission status: Time Limit Exceeded

Solution code:
import copy
 
N,Q = map(int,input().split())
A = list(map(int,input().split()))
X = [0]*Q
 
for i in range(Q):
  X[i] = int(input())
  #初期値
  j= -1
  Takahashi = 0
  Aoki = 0
  B = copy.deepcopy(A)
  flag =0
  
  for k in range(N):
    if flag == 0: #高橋くんの行動
      Takahashi += B[-1]
      del B[-1]
      flag = 1
    
    elif flag ==1: #青木くんの行動
      
      #j-1番目のカード値B[j-1] <= 青木くんが決めた整数X[i] < j番目のカード値B[j]
      #となるようにjの値を決める
      #ただしX[i]がいずれのBの要素よりも大きい場合はi=N-k-1とする
      if j == -1:
        for l in range(N-k):
          if X[i] < B[l]:
            j = l 
            break
        if j == -1:
          j = N-k-1
          
      if len(B) == j:
         j = len(B)-1

          
      #j=0（青木くんが決めた整数は残りカードのいずれよりも小さい）の場合、B[0]を取る
      if j == 0:
        Aoki +=B[0]
        del B[0]
        flag =0
      #j=0（青木くんが決めた整数は残りカードのいずれよりも小さい）の場合、B[0]を取る
      #j番目のカードB[j]を取る     
      elif abs(X[i]-B[j]) < abs(X[i]-B[j-1]):
        Aoki += B[j]
        del B[j]
        flag =0
        if len(B) == j:
           j=j-1
      #j番目のカードB[j-1]を取る   
      else:
        Aoki += B[j-1]
        del B[j-1]
        flag = 0
        j = j-1
  print(Takahashi)

Submission status: Time Limit Exceeded

Solution code:
import itertools
def inpl(): return [int(i) for i in input().split()]
def f(y):
    return abs(x-A[y])
N, Q = inpl()
A = inpl()
SA = list(itertools.accumulate(A))
if N%2 :
    B = [v for i, v in enumerate(A) if not i%2]
    B = [0] + list(itertools.accumulate(B))
else:
    B = [v for i, v in enumerate(A) if i%2]
    B = [0] + list(itertools.accumulate(B))
    
for _ in range(Q):
    x = int(input())
    lo = 1
    hi = -(-N//2) + 1
    while hi - lo >1:
        mid = (lo+hi)//2
        if mid == 1:
            continue
        if max(f(N-mid-1), f(N-2*mid+1)) <= f(N-mid):
            lo = mid
        else:
            hi = mid    
    print(SA[N-1] - SA[N-lo-1] + B[-((2*lo-N)//2)])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import copy
N, Q = list(map(int, input().split()))
A = list(map(int, input().split()))
def nearest(x, A):
  ans = 0
  a = copy.copy(A)
  while a:
    dif = 10**9
    n = 0
    ans += a[-1]
    a.pop(-1)
    if not a: break
    for i, j in enumerate(a):
      d = abs(j - x)
      if dif > d:
        dif = d
        n = i
    a.pop(n)
  print(ans)

for _ in range(Q):
  x = int(input())
  nearest(x, A)

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int, input().split())
a = list(map(int, input().split()))
x = [int(input()) for _ in range(q)]
sort_x = sorted(x)
ans = {}
if n%2== 1:
    small_position = 0
    border_position = int((n-1)/2)
    sum_all = sum(a[border_position:])
    a.append(1000000000)
    a.append(1000000000)
    for x_i in sort_x:
        for compare in a[border_position:]:
            if x_i - a[small_position] > compare-x_i:
                sum_all = sum_all + a[small_position] - compare
                small_position += 2
                border_position += 1
                ans[x_i] = sum_all
            else:
                ans[x_i] = sum_all
                break

else:
    small_position = 1
    border_position = int(n/2)
    sum_all = sum(a[border_position:])
    a.append(1000000000)
    a.append(1000000000)
    for x_i in sort_x:
        for compare in a[border_position:]:
            if x_i - a[small_position] > compare-x_i:
                sum_all = sum_all + a[small_position] - compare
                small_position += 2
                border_position += 1
                ans[x_i] = sum_all
            else:
                ans[x_i] = sum_all
                break

for x_i in x:
    print(ans[x_i])

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left as bisectl, bisect_right as bisectr
N, Q = map(int, input().split())
A = list(map(int, input().split()))

S = [A[0], A[0]+A[1]]
S2 = A[:2]
for a in A[2:]:
  S.append(a + S[-1])
  S2.append(a + S2[-2])

for _ in range(Q):
  x = int(input())
  if x >= A[-1]:
    print(S2[-1])
    continue
  # 二分探索で、合流する所を見つける
  left = bisectl(A, x) - 1
  right = N - 1
  while True:
    mid = left + (right - left ) // 2
    numTaka = N - (mid+1)
    numAoki = mid + 1 - bisectl(A, x - (A[mid] - x), hi=mid)
    if numTaka == numAoki or numTaka == numAoki+1:
      break
    if numTaka > numAoki:
      left = mid
    else:
      right = mid
  mid = left + (right - left ) // 2
  numTaka = N - (mid+1)
  if numTaka * 2 >= N:
    print(S[-1] - S[-numTaka-1])
  else:
    print(
      S[-1] - S[-numTaka-1] + # 合流まで
      S2[-(numTaka*2)-1]# 合流から
    )

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import copy

tmp=input()
nf = int(tmp.split(" ")[0])
q = int(tmp.split(" ")[1])
tmp=input()
af=[int(k) for k in tmp.split()]
x=[]
t=[]
for k in range(q):
    x.append(int(input()))
    t.append(int(0))

i=int(0)
for i in range(q):
    a=copy.deepcopy(af)
    n=nf
    while a != []:
        t[i]=t[i]+a.pop(len(a)-1)
        if a == []:
            break
        n=n-1
        b=[abs(int(a[k]-x[i])) for k in range(n)]
        minb=b.index(min(b))
        n=n-1
        del a[minb]
    print(t[i])
    i = i+1

Submission status: Time Limit Exceeded

Solution code:
n, q = [int(x) for x in input().split(' ')]
a = sorted([int(x) for x in input().split(' ')])
x = [int(input()) for i in range(0, q)]


def game(arr, aoki):
    a = arr[:]
    score=0
    while a:
        score += a.pop()
        if not a:
            break
        nearest_index = sorted(enumerate([abs(y-aoki) for y in a]), key=lambda x: x[1])[0][0]
        a.pop(nearest_index)
    return score

for aoki in x:
    print(game(a, aoki))

Submission status: Time Limit Exceeded

Solution code:
N,Q=map(int,input().split())
A=list(map(int,input().split()))
s=sum(A)
for _ in range(Q):
    x=int(input())
    U=N
    L=-1
    while U-L>1:
        t=(U+L)//2
        if x<A[t]: U=t
        else: L=t
    B=A[:U]
    C=A[U:]
    is_takahashi=True
    aoki=0
    takahashi=0
    while len(B)+len(C):
        if is_takahashi:
            if C==[]: takahashi+=B.pop(-1)
            else: takahashi+=C.pop(-1)
        else:
            if C==[]: aoki+=B.pop(-1)
            elif B==[]: aoki+=C.pop(0)
            elif x-B[-1]<=C[0]-x:
                aoki+=B.pop(-1)
            else:
                aoki+=C.pop(0)
        is_takahashi = not is_takahashi
    print(takahashi)

Submission status: Time Limit Exceeded

Solution code:
N,Q=map(int,input().split())
A=list(map(int,input().split()))
s=sum(A)
for _ in range(Q):
    x=int(input())
    U=N
    L=-1
    while U-L>1:
        t=(U+L)//2
        if x<A[t]: U=t
        else: L=t
    B=A[:U]
    C=A[U:]
    is_takahashi=True
    aoki=0
    takahashi=0
    while len(B)+len(C):
        if is_takahashi:
            if C==[]: takahashi+=B.pop(-1)
            else: takahashi+=C.pop(-1)
        else:
            if C==[]: aoki+=B.pop(-1)
            elif B==[]: aoki+=C.pop(0)
            elif x-B[-1]<=C[0]-x:
                aoki+=B.pop(-1)
            else:
                aoki+=C.pop(0)
        is_takahashi = not is_takahashi
    print(takahashi)

Submission status: Time Limit Exceeded

Solution code:
#encoding:utf-8

import numpy as np
N,Q = map(int,input().split())

A = [int(i) for i in input().split()]
X = []
for i in range(Q):
    X.append(int(input()))

def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return list[idx]

def turn_taka(answer,game_A):
    answer += game_A[-1]
    game_A.pop(-1)
    return answer,game_A

def turn_ao(game_A):
    tem = getNearestValue(game_A,x)
    game_A.remove(tem)
    return game_A


def game(x):
    answer = 0
    game_A = sorted(A)
    while True:
        if len(game_A) > 0:
            answer,game_A = turn_taka(answer,game_A)
        else:
            break
        if len(game_A) > 0:
            game_A = turn_ao(game_A)
        else:
            break
    return answer


#chose x
for x in X:

    print(game(x))

Submission status: Time Limit Exceeded

Solution code:
def searchAokiGetCard(xi, A):
    Adistance = list(map(lambda ai: abs(ai-xi), A))
    Adismin = min(Adistance)
    geta = xi - Adismin
    if geta not in A:
        geta = xi + Adismin
    A.remove(geta)
    return A


N, Q = map(int, input().split())
A = list(map(int, input().split()))
Aorig = A.copy()

X = []
for i in range(Q):
    X.append(int(input()))

A.sort()
for xi in X:
    sum = 0
    A = Aorig.copy()
    for _ in A:
        At = A.pop()
        sum = sum + At
        if A != []:
            A = searchAokiGetCard(xi, A)

    if A != []:
        print(sum + max(A))
    else:
        print(sum)

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split()) # NはリストAの要素数、Qはxの値の候補数
A = list(map(int, input().split())) # リストAは小さい方から順に並べられている
A_new = [list()] * Q
result = [0] * Q

for i in range(Q):
    
    x = int(input())
    A_new[i] = A[:]
    
    while A_new[i]:
        result[i] = result[i] + A_new[i].pop()
        if A_new[i]:
            state = 0
            for j in range(x):
                if x - j in A_new[i]:
                    A_new[i].remove(x - j)
                    state = 1
                    break
                if x + j in A_new[i]:
                    A_new[i].remove(x + j)
                    state = 1
                    break          
            if state == 0:
                del A_new[i][0]

for i in range(Q):
    print(result[i])

Submission status: Time Limit Exceeded

Solution code:
def searchAokiGetCard(xi, A):
    Adistance = list(map(lambda ai: abs(ai-xi), A))
    Adismin = min(Adistance)
    geta = xi - Adismin
    if geta not in A:
        geta = xi + Adismin
    return geta


N, Q = map(int, input().split())
A = list(map(int, input().split()))
Aorig = A.copy()

X = []
for i in range(Q):
    X.append(int(input()))

A.sort()
for xi in X:
    sum = 0
    A = Aorig.copy()
    for _ in A:
        At = A.pop()
        sum = sum + At
        if A != []:
            Aa = searchAokiGetCard(xi, A)
            A.remove(Aa)

    if A != []:
        print(sum + max(A))
    else:
        print(sum)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,Q = list(map(int,input().split()))
A = list(map(int,input().split()))
X = [int(input()) for x in range(Q)]
def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return idx

for x in X:
    score = 0
    turn = 1
    T = np.array(A)
    while T.shape[0] > 0:
        if turn:
            score += T[-1]
            T = T[:-1]
            turn = 0
        else:
            T = np.delete(T,find_nearest(T,x))
            turn = 1
        # print(T)
    print(score)

Submission status: Time Limit Exceeded

Solution code:
# N = int(input())
# A = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]

import sys
import bisect


N, Q = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
X = []
for _ in range(Q):
    X.append(int(input()))

A.sort()
A_COPY = A.copy()

T = []


def takahashi():
    a = A[-1]
    T.append(a)
    del A[-1]


def aoki(x):
    l = bisect.bisect_left(A, x) - 1
    idx = l
    if l == len(A):
        idx = l - 1
    elif l + 1 < len(A):
        if abs(A[l] - x) > abs(A[l + 1] - x):
            idx = l + 1
    del A[idx]


for x in X:
    A = A_COPY.copy()
    T = []
    while True:
        takahashi()
        if len(A) == 0:
            break
        aoki(x)
        if len(A) == 0:
            break
    print(sum(T))

Submission status: Time Limit Exceeded

Solution code:
import copy

N,Q = map(int,input().split())
A = list(map(int,input().split()))
X = [0]*Q

for i in range(Q):
  X[i] = int(input())
  #初期値
  Takahashi = 0
  Aoki = 0
  B = copy.deepcopy(A)
  flag =0
  
  for k in range(N):
    if flag == 0: #高橋くんの行動
      Takahashi += B[-1]
      del B[-1]
      flag = 1
    
    elif flag ==1: #青木くんの行動
      j=-1
      for l in range(N-k):
        if X[i] < B[l]:
          j = l 
          break
      if j==-1:
        j = N-k-1
        
      if j == 0:
        Aoki +=B[0]
        del B[0]
        flag =0
      elif abs(X[i]-B[j]) < abs(X[i]-B[j-1]):
        Aoki += B[j]
        del B[j]
        flag =0
      else:
        Aoki += B[j-1]
        del B[j-1]
        flag = 0
  print(Takahashi)

Submission status: Time Limit Exceeded

Solution code:
N,Q=map(int,input().split())
A=list(map(int,input().split()))
s=sum(A)
for _ in range(Q):
    x=int(input())
    U=N
    L=-1
    while U-L>1:
        t=(U+L)//2
        if x<A[t]: U=t
        else: L=t
    b=L
    c=U
    aoki=0
    turn=1
    while turn<=N//2:
        if N-turn==c:
            while b>=0:
                aoki+=A[b]
                b-=2
            break
        if N-turn<c:
            b-=1
            while b>=0:
                aoki+=A[b]
                b-=2
            break
        if b<0:
            while c<N-turn:
                aoki+=A[c]
                c+=1
                turn+=1
            break
        if x-A[b]<=A[c]-x:
            aoki+=A[b]
            b-=1
        else:
            aoki+=A[c]
            c+=1
        turn+=1
    print(s-aoki)

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy
sys.setrecursionlimit(1000000)

n, q = map(int, input().split())
num_list = sorted(list(map(int, input().split())))

def rec_get_card(num_list, abs_list, res_list, num_turn=0):
  if len(num_list) == 0:
    return res_list
  if num_turn % 2 == 0:
    res_list.append(num_list.pop())
    abs_list.pop()
  else:
    pop_index = abs_list.index(min(abs_list))
    num_list.pop(pop_index)
    abs_list.pop(pop_index)
  num_turn += 1
  return rec_get_card(num_list, abs_list, res_list, num_turn)
  
for i in range(q):
  tmp_num_list = copy.deepcopy(num_list)
  base = int(input())
  abs_list = [abs(x - base) for x in tmp_num_list]
  res_list = []
  print(sum(rec_get_card(tmp_num_list, abs_list, res_list)))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,Q = map(int,input().split())
Alist_z = np.array(list(map(int,input().split())))
Qlist = [int(input()) for _ in range(Q)]


for q in Qlist:
    TAKA = []
    Alist = Alist_z
    if N%2 == 0:
        kais = N//2
        for i in range(kais):
            max = Alist.max()
            TAKA.append(max)
            Alist = Alist[~(Alist==max)]
            sa = abs(Alist-q)
            min = sa.min()
            ind = np.where(sa == min)
            dlt = Alist[ind[0][0]]
            Atest = list(Alist)
            Atest.remove(dlt)
            Alist = np.array(Atest)
    else:
        kais = N//2
        for i in range(kais):
            max = Alist.max()
            TAKA.append(max)
            Alist = Alist[~(Alist==max)]
            sa = abs(Alist-q)
            min = sa.min()
            ind = np.where(sa == min)
            dlt = Alist[ind[0][0]]
            Atest = list(Alist)
            Atest.remove(dlt)
            Alist = np.array(Atest)
        TAKA.append(Alist[0])
    print(sum(TAKA))

Submission status: Time Limit Exceeded

Solution code:
from operator import itemgetter

N, Q = map(int, input().split(' '))
A = sorted(list(map(int, input().split(' '))))

X = [int(input()) for i in range(Q)]

for q in X:
    B = [[abs(a-q), i] for i, a in enumerate(A)]
    B = sorted(B, key=itemgetter(0))
    flag = [False for i in range(N)]
    a = N-1
    b = 0
    ans = 0
    count = N
    while count > 0:
        while flag[a]:
            a -= 1
        ans += A[a]
        flag[a] = True
        a -= 1
        count -= 1
        if count <= 0:
            break
        while flag[B[b][1]]:
            b += 1
        flag[B[b][1]] = True
        b += 1
        count -= 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
n,q = map(int, input().split())
a = list(map(int, input().split()))
x=[]
for i in range(0,q):
  x.append(int(input()))
x.sort()

for xii in range(0,q):
  xi=x[xii]
  y=a.copy()
  r=0
  while len(y)>0:
    val=y.pop()
    r=r+val
    if len(y)==0:
      break
    index = np.abs(np.asarray(y) - xi).argmin()
    y.pop(index)
  print(r)

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())
A = list(map(int, input().split()))

X = [int(input()) for i in range(Q)]


def main():
    for x in X:
        result = 0
        A1 = [a for a in A if a <= x]
        A2 = [a for a in A if a > x]

        for turn in range(N):
            if turn % 2 == 0:
                if len(A2) > 0:
                    result += A2[-1]
                    del A2[-1]
                else:
                    result += A1[-1]
                    del A1[-1]

            else:
                if len(A1) == 0:
                    del A2[0]
                elif len(A2) == 0:
                    del A1[-1]
                elif x - A1[-1] <= A2[0] - x:
                    del A1[-1]
                else:
                    del A2[0]

        print(result)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def searchAokiGetCard(xi, A):
    Adistance = list(map(lambda ai: abs(ai-xi), A))
    Adismin = min(Adistance)
    geta = xi - Adismin
    if geta not in A:
        geta = xi + Adismin
    return geta


N, Q = map(int, input().split())
A = list(map(int, input().split()))
Aorig = A.copy()

X = []
for i in range(Q):
    X.append(int(input()))

A.sort()
for xi in X:
    sum = 0
    A = Aorig.copy()
    for ai in A:
        At = A.pop()
        sum = sum + At
        if A != []:
            Aa = searchAokiGetCard(xi, A)
            A.remove(Aa)

    if A != []:
        print(sum + max(A))
    else:
        print(sum)

Submission status: Time Limit Exceeded

Solution code:
import copy
N, Q = map(int, input().split())
A_in = list(map(int, input().split()))
X=[int(input()) for _ in range(Q)]


for x in X:
    tmp=0
    A=copy.copy(A_in)
    A.sort()
    A_ = [abs(a-x) for a in A]
    while len(A)!=0:
        tmp+=A[-1]
        A.pop()
        A_.pop()
        if len(A_)==0:
            break
        ind=A_.index(min(A_))
        A.pop(ind)
        A_.pop(ind)
    print(tmp)

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split()) # NはリストAの要素数、Qはxの値の候補数
A = list(map(int, input().split())) # リストAは小さい方から順に並べられている
A_new = [list()] * Q
result = [0] * Q

for i in range(Q):
    
    x = int(input())
    A_new[i] = A[:]
    
    while A_new[i]:
        result[i] = result[i] + A_new[i].pop()
        if A_new[i]:
            for j in range(1000000000):
                if (x - j > 0) and (x - j in A_new[i]):
                    A_new[i].remove(x - j)
                    break
                if x + j in A_new[i]:
                    A_new[i].remove(x + j)
                    break

for i in range(Q):
    print(result[i])

Submission status: Time Limit Exceeded

Solution code:
import copy

N, Q = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
s_list = []

for q in range(Q):
    X = int(input())
    a1 = sorted([int(x - X) for x in A], reverse=True)
    a2 = [abs(x) for x in a1]
    s = 0

    while len(a1) > 0:
        s += a1.pop(0) + X
        if len(a1) == 0:
            break

        a2.pop(0)
        min_a = min(a2)
        a1.remove(-min_a if -min_a in a1 else min_a)
        a2.remove(min_a)
        
    s_list.append(s)

for s in s_list:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int, input().split())
a = [int(i) for i in input().split()] 
x = [int(input()) for i in range(q)] 

# たぶん計算時間的に無理だけど一応やってみる

import math

for k in range(0,q):

    b = [i for i in a]
    b.sort()
    b.reverse() # b 高橋くんが取りたい順
    
    c = [abs(i - x[k] + 0.1) for i in b]
    dic = {}
    
    for m in range(0, n):
        dic[c[m]] = b[m]

    c.sort()
    d = [dic[ci] for ci in c]  # d 青木くんが取りたい順
    
    taka_b = b
    aoki_b = d

    taka = [] # 実際に高橋くんがとったもの
    aoki = [] # 実際に青木くんがとったもの

    for m in range(0, math.ceil(n/2)+1):
        try:
            t = taka_b[0]
            taka.append(t) # 高橋くんが取る
            taka_b.remove(t)
            aoki_b.remove(t)
        except:
            break

        try:
            t = aoki_b[0]
            aoki.append(d[0]) # 青木くんが取る
            taka_b.remove(t)
            aoki_b.remove(t)
        except:
            break
    
    print(sum(taka))