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:
a_q_list = raw_input().split()
a = int(a_q_list[0])
q = int(a_q_list[1])

A_list = map(int, raw_input().split())

def get_near_x(A_list, x):
    #print(A_list, x)
    if x in A_list:
        return x
    else:
        plus = [i-x for i in A_list if i-x>0]
        minus = [i-x for i in A_list if i-x<0]
        #print("plus",plus,"minus",minus)
        if len(plus)==0:
            return x + minus[-1]
        elif len(minus) == 0:
            return x + plus[0]
        elif plus[0] == -(minus[-1]):
            return x + minus[-1]
        elif plus[0] > -(minus[-1]):
            return x + minus[-1]
        else:
            return x + plus[0]
def game(A_list,x):
    score=0
    while True:
        #A_list.sort()
        score+=A_list.pop()
        if len(A_list)==0:
            return score
        #print(A_list)
        A_list.remove(get_near_x(A_list, x))
        if len(A_list)==0:
            return score
        #print(A_list)

x_list = []
for _ in range(q):
    tmp = int(input())
    x_list.append(tmp)

for x in x_list:
    A = A_list[:]
    print(game(A, x))

#for x in x_list:
#    print(x,get_near_x(A_list, x))
#    print(A_list)

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 = At + sum
        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 sys

import numpy as np


def input():
    return sys.stdin.readline()[:-1]


def ii(t: type = int):
    return t(input())


def il(t: type = int):
    return list(map(t, input().split()))


def imi(N: int, t: type = int):
    return [ii(t) for _ in range(N)]


def iml(N: int, t: type = int):
    return [il(t) for _ in range(N)]


N, Q = il()
A_ = il()
X = imi(Q)
for x in X:
    takahashi = 0
    A = A_[:]
    while A:
        takahashi += A.pop()
        if A:
            aoki = [abs(a - x) for a in A]
            A.remove(A[np.argmin(aoki)])
    print(takahashi)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 20:44:00 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 20:43:41 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 18:42:51 2018

@author: Owner
"""

import collections
import scipy.misc
import sys
import numpy as np
import math
from operator import itemgetter
import itertools
import copy

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

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

"""
N, X = map(int, input().split())

x = [0]*N
x[:] = map(int, input().split())

P = [0]*M
Y = [0]*M
for m in range(M):
    P[m], Y[m] = map(int, input().split())
    
all(nstr.count(c) for c in '753')
"""

N, Q = map(int, input().split())

A = [0]*N
A[:] = map(int, input().split())

X = [0]*Q
for q in range(Q):
    X[q] = int(input())

for q in range(Q):
    tmpA = copy.deepcopy(A)    
    T=[]
    while len(tmpA) != 0:
        T.append(tmpA.pop())
        if len(tmpA)!=0:
            tmpA.pop(getNearestValue(tmpA, X[q]))
        else:
            pass
    print(sum(T))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
INFTY = -100000000000

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

for x in X:
    takahashi = 0
    B = A.copy()
    for _ in range(Q//2+1):
        # print(takahashi)
        # print(B)
        takahashi += B.max()
        B[B.argmax()] = INFTY
        B[np.abs(B-x).argmin()] = INFTY
    print(takahashi)

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)]

def game(a, x):
    s = 0
    taka_a = list(sorted(a))
    aoki_a = list(sorted(a, key=lambda s: abs(s - x) + 1E-11 * s, reverse=True))
    while True:
        n = taka_a.pop()
        aoki_a.remove(n)
        s += n
        if not taka_a:
            break
        n = aoki_a.pop()
        taka_a.remove(n)
        if not taka_a:
            break
    return s
    
    
for x in X:
    print(game(A, x))

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int,input().split())
card_num = list(map(int,input().split()))
card_num.sort()
x_i = []
for i in range(q):
    x_i.append(int(input()))
for i in range(q):
    card = []
    for num in range(n):
        card.append(card_num[num])
    taka = []
    for j in range(n//2):
        temp = max(card)
        card.remove(temp)
        taka.append(temp)
        up = [x for x in card if x >= x_i[i]]
        down = [y for y in card if y < x_i[i]]
        if up == []:
            card.remove(down[-1])
        elif down == []:
            card.remove(up[0])
        elif up[0]-x_i[i]<x_i[i]-down[-1]:
            card.remove(up[0])
        else:
            card.remove(down[-1])
    if n%2==1:
        taka.append(card[0])
    print(sum(taka))

Submission status: Time Limit Exceeded

Solution code:
import copy

n, q = map(int, input().split())
a = list(map(int, input().split()))
x = [int(input()) for i in range(q)]
taka = 0

c = copy.copy(a)
for j in range(q):
  b = list(map(lambda y : abs(y - x[j]), a))
  for i in range(n):
    if i % 2 == 0:
      taka = taka + max(a)
      del a[len(a) - 1]
      del b[len(b) - 1]
    if i % 2 == 1:
      ind = b.index(min(b))
      del a[ind]
      del b[ind]
    
  print(taka)
  a = copy.copy(c)
  taka = 0

Submission status: Time Limit Exceeded

Solution code:
import sys
import bisect
import copy
input = sys.stdin.readline
N, Q = map(int, input().split())
card = list(map(int, input().split()))
card.sort()

def calc(x):
    nums = copy.deepcopy(card)
    l = N
    y = -1
    tot = 0
    while l:
        tot += nums[l-1]
        del nums[l-1]
        l -= 1
        if l == 0:
            break
        if y == -1:
            y = bisect.bisect_left(nums, x)
        if y >= l:
            y = l - 1
        mi = nums[y-1]
        ma = nums[y]
        if abs(x - mi) <= abs(ma - x):
            del nums[y-1]
        else:
            del nums[y]
        l -= 1
    return tot
        

for _ in range(Q):
    x = int(input())
    print(calc(x))

Submission status: Time Limit Exceeded

Solution code:
n,q=map(int,input().split())
a=list(map(int,input().split()))
x=[]
for i in range(q):
    x.append(int(input()))
for xi in x:
    takahashi=0
    a2=a.copy()
    diff=[a2[i]-xi for i in range(n)]
    # print(a2)
    while True:
        takahashi+=a2.pop()
        diff.pop()
        # print(a2)
        if len(a2)==0:
            break
        mDiff=min(diff,key=abs)
        index=diff.index(mDiff)
        a2.pop(index)
        diff.pop(index)
        if len(a2)==0:
            break
        # print(a2)
    print(takahashi)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 20:44:00 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 20:43:41 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 18:42:51 2018

@author: Owner
"""

import collections
import scipy.misc
import sys
import numpy as np
import math
from operator import itemgetter
import itertools
#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

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

"""
N, X = map(int, input().split())

x = [0]*N
x[:] = map(int, input().split())

P = [0]*M
Y = [0]*M
for m in range(M):
    P[m], Y[m] = map(int, input().split())
    
all(nstr.count(c) for c in '753')
"""

N, Q = map(int, input().split())

A = [0]*N
A[:] = map(int, input().split())

X = [0]*Q
for q in range(Q):
    X[q] = int(input())

for q in range(Q):
    tmpA = A[:]    
    T=[]
    while len(tmpA) != 0:
        T.append(tmpA.pop())
        if len(tmpA)!=0:
            tmpA.pop(getNearestValue(tmpA, X[q]))
        else:
            pass
    print(sum(T))

Submission status: Time Limit Exceeded

Solution code:
def searchAokiGetCard(xi, A):
    Adistance = list(map(lambda ai: abs(ai-xi), A))
    geta = xi - min(Adistance)
    if geta not in A:
        geta = xi + min(Adistance)
    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()))

#print(A)

for xi in X:
    sum = 0
    #print("**************")
    A = Aorig.copy()
    for ai in A:
        At = max(A)
        A.remove(At)
        sum = At + sum
        if A != []:
            Aa = searchAokiGetCard(xi, A)
            A.remove(Aa)
            #print(A)
            #print(At, Aa)
    if A != []:
        print(sum + max(A))
    else:
        print(sum)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy

N, Q = map(int, input().strip().split())
A = list(map(int, input().strip().split()))
_A = list(sorted(A))
for _ in range(Q):
  tmpa = copy.deepcopy(_A)
  t = 0
  x = int(input())
  while (tmpa):
    t += tmpa[-1]
    del tmpa[-1]
    if not tmpa:
      break
    ai = bisect.bisect_left(tmpa, x) - 1
    if ai == -1:
      del tmpa[0]
    elif ai == len(tmpa)-1:
      del tmpa[ai]
    elif x-tmpa[ai] == tmpa[ai+1]-x:
      del tmpa[ai]
    elif x-tmpa[ai] < tmpa[ai+1]-x:
      del tmpa[ai]
    elif x-tmpa[ai] > tmpa[ai+1]-x:
      del tmpa[ai+1]
  print(t)

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())
    a = copy.copy(A)
    s = 0

    while len(a) > 0:
        max_a = max(a)
        s += max_a
        a.remove(max_a)
        if len(a) == 0:
            break

        min_a = min([abs(x - X) for x in a])
        a.remove(X - min_a if X - min_a in a else X + 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 = list(map(int,input().split()))
A.sort()
for i in range(Q):
  B = A.copy()
  X = int(input())
  ans = 0
  riv = 0
  for j in range(N):
    if len(B) < 1:
      break
    ans += B.pop(-1)
    if len(B) < 1:
      break
    ao = B[0]
    ak = 0
    if len(B) > 1:
      for l in range(len(B)-1):
        if abs(B[l]-X) > abs(B[l+1]-X):
          ao = B[l+1]
          ak = l+1
    del B[ak]
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
NQ = list(map(int, input().split(" ")))
N = NQ[0]
Q = NQ[1]

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

for i in range(Q):
    turn = "t"
    S = 0
    At = []
    Aa = []
    x = X[i]
    for j in (A):
        At.append(j)
        Aa.append(abs(j-x))
        
    while len(At):
        #print(At)
        #print(Aa)
        if turn == "t":
            S += At[-1]
            At = At[:-1]
            Aa = Aa[:-1]
            turn = "a"
            
        else:
            Min = Aa[0]
            No = 0
            for j,k in enumerate(Aa):
                if Min<=k:
                    continue
                else:
                    Min = k
                    No = j
            At = At[:No]+At[No+1:]
            Aa = Aa[:No]+Aa[No+1:]
            turn = "t"
            
    print(S)

Submission status: Time Limit Exceeded

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

for i in range(q):
    b=list(a)
    xx=x[i]
    sum=0
    while len(b)>0:
        sum+=b[len(b)-1]
        b.pop()
        if len(b)>0:
            ll=bisect.bisect_left(b, xx)-1
            rr=ll+1
            if ll>=len(b)-1:
                b.pop()
            elif abs(b[rr]-xx)<abs(b[ll]-xx):
                b.pop(rr)    
            else:
                b.pop(ll)
    print(sum)

Submission status: Time Limit Exceeded

Solution code:
N, Q = [int(a) for a in input().split()]
a_list = [int(a) for a in input().split()]

from copy import deepcopy
def distance(a1, x1):
    if a1 > x1:
        return a1 - x1 + 10 ** -7
    else:
        return x1 - a1


x_list = [1, 4, 9, 10, 13]

# N, Q = 5, 5
# a_list = [3, 5, 7, 11, 13]
hist_dict = {-1: -1}
for i in range(Q):
    x = int(input())
    # x = x_list[i]
    if x > a_list[-2]:
        # print("type1")
        print(str(sum([a_list[-2 * i - 1] for i in range(int((len(a_list) / 2 + 0.6)))])))
    elif x <= a_list[0]:
        # print("type2")
        print(str(sum(a_list[len(a_list) // 2:])))
    elif x in hist_dict.keys():
        # print("type3")
        print(str(hist_dict[x]))
    else:
        # print("type4")
        dist_list = [distance(a, x) for a in a_list]
        dist_list2 = deepcopy(dist_list)
        dist_list.sort()
        max_num = 0
        for i in range(len(a_list)):
            dist_index = dist_list2.index(dist_list[i])
            if dist_index in (len(a_list) - i - 1, len(a_list) - i - 2) or max_num == len(a_list) - 1 - i - 1:
                add = str(sum(a_list[-i-1:]) + sum([a_list[-2 * j - 1] for j in range(i + 1, int((len(a_list) / 2 + 0.6)))]))
                print(add)
                hist_dict[x] = add
                break
            max_num = max(max_num, dist_index)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,Q=map(int,input().split())
l = list(map(int,input().split()))

for i in range(Q):
  y=int(input())
  ans=0
  l2=sorted(l,key=lambda x:(abs(y-x),x),reverse=True)
  p=deque(l)
  q=deque(l2)
  for j in range(N//2):
    t=p.pop()
    ans+=t
    q.remove(t)
    s=q.pop()
    p.remove(s)
  if N%2==1:
    ans+=p.pop()
  print(ans)

Submission status: Time Limit Exceeded

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

for i in range(q):
    b=list(a)
    xx=x[i]
    sum=0
    while len(b)>0:
        sum+=b[len(b)-1]
        b.pop(len(b)-1)
        if len(b)>0:
            ll=bisect.bisect_left(b, xx)-1
            rr=ll+1
            if ll>=len(b)-1:
                b.pop(len(b)-1)
            elif abs(b[rr]-xx)<abs(b[ll]-xx):
                b.pop(rr)    
            else:
                b.pop(ll)
    print(sum)

Submission status: Time Limit Exceeded

Solution code:
n,q=map(int,input().split())
a=list(map(int,input().split()))
x=[]
for i in range(q):
    x.append(int(input()))
for xi in x:
    takahashi=0
    a2=a.copy()
    diff=[a2[i]-xi for i in range(n)]
    # print(a2)
    while True:
        takahashi+=a2.pop()
        diff.pop()
        # print(a2)
        if len(a2)==0:
            break
        diff2=list(enumerate(diff))
        diff2.sort(key=lambda x:abs(x[1]))
        a2.pop(diff2[0][0])
        diff.pop(diff2[0][0])
        if len(a2)==0:
            break
        # print(a2)
    print(takahashi)

Submission status: Time Limit Exceeded

Solution code:
def game(xi, aa):
    first = 0
    i = 0
    flag = 0
    while aa:
        if i % 2 == 0:
            if flag == 1:
                for k in aa[::-2]:
                    first += k
                aa = []
                break
            elif flag == 2:
                for k in aa[len(aa)//2:]:
                    first += k
                aa = []
                break
            else:
                first += aa[-1]
                aa.pop(-1)
                i += 1
        else:
            if xi >= aa[-1]:
                aa.pop(-1)
                flag = 1
            elif xi <= aa[0]:
                aa.pop(0)
                flag = 2
            else:
                for j in range(1, len(aa)):
                    if xi <= aa[j]:
                        if abs(xi-aa[j-1]) <= abs(xi-aa[j]):
                            aa.pop(j-1)
                        else:
                            aa.pop(j)
                        break
            i += 1
    return(first)


n, q = [int(_) for _ in input().split()]
a = [int(_) for _ in input().split()]
x = []
for i in range(q):
    x.append(int(input()))


for xi in x:
    a_sorted = sorted(a)
    print(game(xi, a_sorted))

Submission status: Time Limit Exceeded

Solution code:
import copy

def main():
    N, Q = [int(x) for x in input().split()]
    A_tr = sorted([int(x) for x in input().split()])
    
    for _ in range(Q):
        A = copy.copy(A_tr)
        X = int(input())
        l = len(A)
        tar = l - 1
        result = 0
        
        for i in range(l):
            if X < A[i]:
                tar = i
                break
        
        for i in range(l):
            if tar == 0:
                result += sum(A[(len(A) + i % 2) // 2:])
                break

            elif tar == len(A):
                result += sum(A[::-1][::2]) if i % 2 == 0 else sum(A[::-1][1::2])
                #print(i, A, X, tar, len(A), A[::-1][::2], A[::-1][1::2])
                break

            else:
                if i % 2 == 0:
                    result += A[-1]
                    A.pop(-1)
                    
                else:
                    if A[tar] - X >= X - A[tar - 1]:
                        A.pop(tar - 1)
                        tar -= 1
                    else:
                        A.pop(tar)
                        
        
        print(result)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy

N, Q = map(int, input().split())
Alist = list(map(int, input().split()))

Xlist = []

for i in range(Q):
    Xtmp = int(input())
    Xlist.append(Xtmp)




for i in range(len(Xlist)):
    Tlist = []
    A = copy.deepcopy(Alist)
    Adifflist = []

    for j in range(len(A)):
        Adifflist.append([abs(A[j]-Xlist[i]), A[j]])

    Adifflist.sort(reverse=False)
        
    while 1:
        Ttmp = A.pop(-1)
        Tlist.append(Ttmp)

        Adifflist.remove([abs(Ttmp-Xlist[i]), Ttmp])

        if A == []:
            print(sum(Tlist))
            break

        Atmp = Adifflist[0][1]
        del Adifflist[0]
        A.remove(Atmp)

        if A == []:
            print(sum(Tlist))
            break

Submission status: Time Limit Exceeded

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

for i in range(q):
    b=list(a)
    xx=x[i]
    sum=0
    while len(b)>0:
        sum+=b[len(b)-1]
        b.pop(len(b)-1)
        if len(b)>0:
            ll=bisect.bisect_left(b, xx)-1
            rr=ll+1
            if ll>=len(b)-1:
                b.pop(len(b)-1)
            elif abs(b[rr]-xx)>abs(b[ll]-xx):
                b.pop(ll)
            elif abs(b[rr]-xx)<abs(b[ll]-xx):
                b.pop(rr)
            else:
                b.pop(ll)
    print(sum)

Submission status: Time Limit Exceeded

Solution code:
import copy
N,Q = map(int,input().split(" "))
A = list(map(int,input().split(" ")))
a = len(A)
for i in range(Q):
    X = int(input())
    B = copy.deepcopy(A)
    C = list(map(lambda x:abs(x-X),B))
    ans = 0
    for j in range(a):
        if j%2 == 0:
            ans += max(B)
            C[B.index(max(B))] = 10**9
            B[B.index(max(B))] = 0
        else:
            B[C.index(min(C))] = 0
            C[C.index(min(C))] = 10**9
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def aising2019_d():
    import numpy as np

    n, q = map(int, input().split())
    a = np.array(sorted(list(map(int, input().split()))))
    x_list = [int(input()) for _ in range(q)]
    for x in x_list:
        score = 0
        tmp_a = a.copy()
        while len(tmp_a):
            score += tmp_a[-1]
            tmp_a = np.delete(tmp_a, -1)
            if len(tmp_a):
                tmp_a = np.delete(tmp_a, np.argmin(np.abs(tmp_a - x)))
        print(score)


aising2019_d()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import copy
N, Q = map(int, input().split())
A = [int(x) for x in input().split()]
X = [int(input()) for x in range(Q)]

def getNearestValue(list, num):

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


for x in X:
    ans = 0
    a = copy.deepcopy(A)
    for i in range(N):

        if len(a) == 0:
            break

        ans += a.pop()

        if len(a) == 0:
            break

        a.remove(getNearestValue(a, x))

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def get_sorted_and_argsort_index(L, reverse=False):
    R = list(range(len(L)))
    Z = zip(L, R)
    Z = sorted(Z, key=lambda x: x[0], reverse=reverse)
    L, R = map(list, zip(*Z))
    return L, R


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

R = 0
A.sort()

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

for x in X:
    CRD = A.copy()
    TAK = []
    AOK = []
    while len(CRD) > 0:
        TAK.append(CRD[-1])
        del CRD[-1]
        if len(CRD) == 0:
            break
        CRX = [abs(c - x) for c in CRD]
        idx = get_sorted_and_argsort_index(CRX)[1][0]
        del CRD[idx]
    print(sum(TAK))

Submission status: Time Limit Exceeded

Solution code:
import copy
import numpy as np
import sys
def input(): return sys.stdin.readline().strip()
n, q = [int(i) for i in input().split()]
As = np.sort(np.array([int(i) for i in input().split()]))
for i in range(q):
    x = int(input())
    As_tmp = copy.copy(As)
    As_abs = abs(As - x)
    # print(As_abs)
    ans = 0
    while len(As_abs):
        ans += As_tmp[-1]
        # print(ans)
        As_tmp = np.delete(As_tmp, -1)
        As_abs = np.delete(As_abs, -1)
        if not len(As_abs):
            break
        # ans += As[As_abs.index(min(As_abs))]
        # idx = As_abs.index(min(As_abs))
        idx = As_abs.argmin()
        # idx = np.where()
        # idx = np.where()
        As_tmp = np.delete(As_tmp, idx)
        As_abs = np.delete(As_abs, idx)
        # print(As_abs)

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
n,q=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
for i in range(q):
    x=int(input())
    ans=0
    cul=[[0,a[i]] for i in range(n)]
    for j in range(n):
        cul[j][0]=abs(x-a[j])
    cul.sort()
    a_copy=a.copy()
    for j in range(n):
        if j%2==0:
            ans+=a_copy[len(a_copy)-1]
            a_copy.pop(len(a_copy)-1)
        else:
            while 1:
                if cul[0][1] in a_copy:
                    a_copy.remove(cul[0][1])
                    break
                else:
                    cul.pop(0)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int, input().split())
a = list(map(int, input().split()))
import numpy as np
def getIndex(list, num):
  idx = np.abs(np.asarray(list) - num).argmin()
  return idx
a = [a[:] for j in range(q)]
for i in range(q):
  x = int(input())
  sum = 0
  while len(a[i]) >= 1:
    sum += a[i].pop(-1)
    if len(a[i]) >= 1:
      del a[i][getIndex(a[i],x)]
  print(sum)

Submission status: Time Limit Exceeded

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

def aoki(cards, x):
    res = [abs(x-card) for card in cards]
    min_res = min(res)
    for idx, r in enumerate(res):
        if r == min_res:
            return cards[idx]
        
def game(cards, x):
    taka_sum = 0
    while(len(cards)>0):
        taka_card = cards.pop(np.argmax(cards))
        taka_sum += taka_card
        if len(cards) == 0:
            break
        aoki_card = aoki(cards, x)
        cards.remove(aoki_card)
    return taka_sum

import copy
for X in X_list:
    A_list_copy = copy.copy(A_list) 
    print(game(A_list_copy, X))

Submission status: Time Limit Exceeded

Solution code:
import copy
import numpy as np
n, q = [int(i) for i in input().split()]
As = np.sort(np.array([int(i) for i in input().split()]))
for i in range(q):
    x = int(input())
    As_tmp = copy.copy(As)
    As_abs = abs(As - x)
    # print(As_abs)
    ans = 0
    while len(As_abs):
        ans += As_tmp[-1]
        # print(ans)
        As_tmp = np.delete(As_tmp, -1)
        As_abs = np.delete(As_abs, -1)
        if not len(As_abs):
            break
        # ans += As[As_abs.index(min(As_abs))]
        # idx = As_abs.index(min(As_abs))
        idx = As_abs.argmin()
        # idx = np.where()
        # idx = np.where()
        As_tmp = np.delete(As_tmp, idx)
        As_abs = np.delete(As_abs, idx)
        # print(As_abs)

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def game(xi, aa):
    first = 0
    i = 0
    while aa:
        if i % 2 == 0:
            first += aa[-1]
            aa.pop(-1)
            i += 1
        else:
            if xi >= aa[-1]:
                aa.pop(-1)
            elif xi <= aa[0]:
                aa.pop(0)
            else:
                for j in range(1, len(aa)):
                    if xi <= aa[j]:
                        if abs(xi-aa[j-1]) <= abs(xi-aa[j]):
                            aa.pop(j-1)
                        else:
                            aa.pop(j)
                        break
            i += 1
    return(first)


n, q = [int(_) for _ in input().split()]
a = [int(_) for _ in input().split()]
x = []
for i in range(q):
    x.append(int(input()))


for xi in x:
    a_sorted = sorted(a)
    print(game(xi, a_sorted))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,q=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
u=[int(input())for i in range(q)]
def l(p,x):
    k=np.abs(np.asarray(p)-x).argmin()
    return k
def h(p,x):
    c=0
    s=0
    for i in range(n):
        c+=1
        if c%2!=1:
            p.pop(l(p,x))
        else:
            s+=p[-1]
            p.pop(-1)
    else:
        return s
for i in range(q):
    o=u[i]
    f=a[:]
    print(h(f,o))

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:
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)