Problem:


Score : 500 points

Problem Statement

Takahashi has come to a party as a special guest.
There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.

Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0).
A handshake will be performed as follows:

Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same).

Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y.

However, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold:

Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \leq p < q \leq M) such that (x_p,y_p)=(x_q,y_q).

What is the maximum possible happiness after M handshakes?

Constraints

1 \leq N \leq 10^5

1 \leq M \leq N^2

1 \leq A_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the maximum possible happiness after M handshakes.

Sample Input 1

5 3
10 14 19 34 33

Sample Output 1

202

Let us say that Takahashi performs the following handshakes:

In the first handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 4.

In the second handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 5.

In the third handshake, Takahashi shakes the left hand of Guest 5 and the right hand of Guest 4.

Then, we will have the happiness of (34+34)+(34+33)+(33+34)=202.

We cannot achieve the happiness of 203 or greater, so the answer is 202.

Sample Input 2

9 14
1 3 5 110 24 21 34 5 3

Sample Output 2

1837

Sample Input 3

9 73
67597 52981 5828 66249 75177 64141 40773 79105 16076

Sample Output 3

8128170



Sample input:
5 3
10 14 19 34 33


Sample output:
202

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans






N,M = m()

a = l()

a.sort()

po = [0 for i in range(10**5+1)]
ans = 0
for i in range(N):
    po[a[i]] += 1
for i in range(10**5-1,-1,-1):
    po[i] += po[i+1]
ll = 0
rr = 10**5 * 2

while True:
    mid = (ll+rr)//2
    if mid == ll:
        co = 0
        for i in range(N):
            ui = a[i]
            if mid > ui + 10**5:
                continue
            elif ui >= mid:
                co += N
            else:
                co += po[mid-ui]
        cco = 0
        mid = rr

        for i in range(N):
            ui = a[i]
            if mid > ui + 10**5:
                continue
            elif ui >= mid:
                cco += N
            else:
                cco += po[mid-ui]
        if cco == M:
            mid = rr
            co=cco

        else:
            mid = ll

        break

    co = 0
    for i in range(N):
        ui = a[i]
        if mid > ui + 10**5:
            continue
        elif ui >= mid:
            co += N
        else:
            co += po[mid-ui]
    
    if co < M:
        rr = mid-1                    
    else:
        ll = mid


a.sort(reverse = True)
dp = [0]

ans -= mid * (co - M)



for i in range(N):
    dp.append(dp[-1]+a[i])

for i in range(N):
    pl = a[i]
    if pl >= mid:
        ans += pl*N + dp[-1]
        
    elif pl + 10**5 < mid:
        continue
    else:
        ans += pl*po[mid-pl] + dp[po[mid-pl]]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans






N,M = m()

a = l()

a.sort()

po = [0 for i in range(10**5+1)]
ans = 0
for i in range(N):
    po[a[i]] += 1
for i in range(10**5-1,-1,-1):
    po[i] += po[i+1]
ll = 0
rr = 10**5 * 2

while True:
    mid = (ll+rr)//2
    if mid == ll:
        co = 0
        for i in range(N):
            ui = a[i]
            if mid > ui + 10**5:
                continue
            elif ui >= mid:
                co += N
            else:
                co += po[mid-ui]
        cco = 0
        mid = rr

        for i in range(N):
            ui = a[i]
            if mid > ui + 10**5:
                continue
            elif ui >= mid:
                cco += N
            else:
                cco += po[mid-ui]
        if cco == M:
            mid = rr
        else:
            mid = ll

        break

    co = 0
    for i in range(N):
        ui = a[i]
        if mid > ui + 10**5:
            continue
        elif ui >= mid:
            co += N
        else:
            co += po[mid-ui]
    
    if co < M:
        rr = mid-1                    
    else:
        ll = mid


a.sort(reverse = True)
dp = [0]

ans -= mid * (co - M)

for i in range(N):
    dp.append(dp[-1]+a[i])

for i in range(N):
    pl = a[i]
    if pl >= mid:
        ans += pl*N + dp[-1]
        
    elif pl + 10**5 < mid:
        continue
    else:
        ans += pl*po[mid-pl] + dp[po[mid-pl]]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans






N,M = m()

a = l()

a.sort()

po = [0 for i in range(10**5+1)]
ans = 0
for i in range(N):
    po[a[i]] += 1
for i in range(10**5-1,-1,-1):
    po[i] += po[i+1]
ll = 0
rr = 10**5 * 2

while True:
    mid = (ll+rr)//2
    if mid == ll:
        break
    co = 0
    for i in range(N):
        ui = a[i]
        if mid > ui + 10**5:
            continue
        elif ui >= mid:
            co += N
        else:
            co += po[mid-ui]
    
    if co < M:
        rr = mid-1
        if (ll+rr)//2 == ll:
            mid = rr
            co = 0
            for i in range(N):
                ui = a[i]
                if mid > ui + 10**5:
                    continue
                elif ui >= mid:
                    co += N
                else:
                    co += po[mid-ui]
                    
            break
    else:
        ll = mid
        if (ll+rr)//2 == ll:
            mid = ll
            co = 0
            for i in range(N):
                ui = a[i]
                if mid > ui + 10**5:
                    continue
                elif ui >= mid:
                    co += N
                else:
                    co += po[mid-ui]
            break


a.sort(reverse = True)
dp = [0]

ans -= mid * (co - M)

for i in range(N):
    dp.append(dp[-1]+a[i])

for i in range(N):
    pl = a[i]
    if pl >= mid:
        ans += pl*N + dp[-1]
        
    elif pl + 10**5 < mid:
        continue
    else:
        ans += pl*po[mid-pl] + dp[po[mid-pl]]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans






N,M = m()

a = l()

a.sort()

po = [0 for i in range(10**5+1)]
ans = 0
for i in range(N):
    po[a[i]] += 1
for i in range(10**5-1,-1,-1):
    po[i] += po[i+1]
ll = 0
rr = 10**5 * 2

while True:
    mid = (ll+rr)//2
    if mid == ll:
        break
    co = 0
    for i in range(N):
        ui = a[i]
        if mid > ui + 10**5:
            continue
        elif ui >= mid:
            co += N
        else:
            co += po[mid-ui]
    
    if co < M:
        rr = mid-1
        if (ll+rr)//2 == ll:
            mid = rr
            co = 0
            for i in range(N):
                ui = a[i]
                if mid > ui + 10**5:
                    continue
                elif ui >= mid:
                    co += N
                else:
                    co += po[mid-ui]
                    
            break
    else:
        ll = mid
        if (ll+rr)//2 == ll:
            mid = ll
            break


a.sort(reverse = True)
dp = [0]

ans -= mid * (co - M)

for i in range(N):
    dp.append(dp[-1]+a[i])

for i in range(N):
    pl = a[i]
    if pl >= mid:
        ans += pl*N + dp[-1]
        
    elif pl + 10**5 < mid:
        continue
    else:
        ans += pl*po[mid-pl] + dp[po[mid-pl]]
print(ans)

Submission status: Wrong Answer

Solution code:
def examA():
    N = I()
    ans = 0
    print(ans)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    N, M = LI()
    A = LI()
    A.sort()
    ma = max(A)
    l = 0; r = ma*2+1
    while(r-l>1):
        now = (l+r)//2
        cnt = 0
        for a in A:
            need = now-a
            if need>ma:
                continue
            c = bisect.bisect_left(A,need)
            cnt += N-c
        if cnt>=M:
            l = now
        else:
            r = now
    base = l
    cnt = 0
    ans = 0
    S = [0]+A
    for i in range(N):
        S[i+1] += S[i]
    #print(S)
    for a in A:
        need = base - a
        c = bisect.bisect_left(A, need+1)
        ans += a*(N-c) + S[N]-S[c]
        cnt += (N-c)
    if cnt<M:
        ans += base*(M-cnt)
    print(ans)
    return

def examE2():
    # 参考 https://lumakernel.github.io/ecasdqina/math/FFT/NTT
    # https://atc001.contest.atcoder.jp/submissions/11365995
    # NTT_Primes: {1224736769, 3},{1053818881, 7},..{998244353, 3},..{167772161, 3}
    class fast_fourier_transform():
        def __init__(self, A, B, MOD=1224736769, pr=3):
            self.MOD = MOD
            self.pr = pr
            self.La = len(A);
            self.Lb = len(B)
            self.k = (self.La + self.Lb - 1).bit_length()
            self.M = 2 ** self.k
            self.W = [0] * (self.M // 2)
            self.Y = [0] * (self.M // 2)

            self.A = [0] * self.M;
            self.B = [0] * self.M
            for i in range(self.La):
                self.A[i] = A[i]
            for i in range(self.Lb):
                self.B[i] = B[i]
            return

        def convolve(self):
            z = pow(self.pr, (self.MOD - 1) // self.M, self.MOD)
            x = pow(z, self.MOD - 2, self.MOD)
            j = self.M // 4
            while j > 0:
                self.W[j] = z
                z = z * z % self.MOD
                self.Y[j] = x
                x = x * x % self.MOD
                j //= 2
            self.genwy(0, self.M // 4, 1, 1)
            self.A = self.NTT(self.A)
            self.B = self.NTT(self.B)
            rep = [0] * self.M
            for i in range(self.M):
                rep[i] = (self.A[i] * self.B[i]) % self.MOD
            rep = self.NTT(rep, True)
            return rep

        def genwy(self, i, b, z, x):
            if b == 0:
                self.W[i] = z
                self.Y[i] = x
            else:
                self.genwy(i, b // 2, z, x)
                self.genwy(i + b, b // 2, z * self.W[b] % self.MOD, x * self.Y[b] % self.MOD)
            return

        def NTT(self, F, inverse=False):
            if not inverse:
                u = 0;
                v = 1
            else:
                u = 1;
                v = 0
            U = [1, 2 ** (self.k - 1)]
            while (U[1] > 0):
                jh = 0
                while (jh < U[u]):
                    if not inverse:
                        wj = self.W[jh]
                    else:
                        wj = self.Y[jh]
                    j = jh * U[v] * 2
                    je = j + U[v]
                    while (j < je):
                        if not inverse:
                            ajv = wj * F[j + U[v]] % self.MOD
                            F[j + U[v]] = (F[j] + self.MOD - ajv) % self.MOD
                            F[j] = (F[j] + ajv) % self.MOD
                        else:
                            ajv = (F[j] + self.MOD - F[j + U[v]]) % self.MOD
                            F[j] = (F[j] + F[j + U[v]]) % self.MOD
                            F[j + U[v]] = wj * ajv % self.MOD
                        j += 1
                    jh += 1
                U[0] *= 2
                U[1] //= 2
            if inverse:
                invk = pow(self.M, self.MOD - 2, self.MOD)
                return [F[i] * invk % self.MOD for i in range(self.La + self.Lb - 1)]
            return F

    N, M = LI()
    A = LI()
    B = [0]*(max(A))
    for a in A:
        B[a-1] += 1
    F = fast_fourier_transform(B,B)
    C = [0] + F.convolve()
    #print(C)
    ans = 0
    for i in range(len(C))[::-1]:
        c = C[i]
        if M>c:
            ans += c*(i+1)
            M -= c
        else:
            ans += M*(i+1)
            break
    print(ans)
    return

def examF():
    N = I()
    V = [[]for _ in range(N)]
    for _ in range(N-1):
        a, b = LI()
        a -= 1; b -= 1
        V[a].append(b)
        V[b].append(a)

    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examE2()

"""

"""

Submission status: Wrong Answer

Solution code:
def examA():
    N = I()
    ans = 0
    print(ans)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    N, M = LI()
    A = LI()
    A.sort()
    ma = max(A)
    l = 0; r = ma*2+1
    while(r-l>1):
        now = (l+r)//2
        cnt = 0
        for a in A:
            need = now-a
            if need>ma:
                continue
            c = bisect.bisect_left(A,need)
            cnt += N-c
        if cnt>=M:
            l = now
        else:
            r = now
    base = l
    cnt = 0
    ans = 0
    S = [0]+A
    for i in range(N):
        S[i+1] += S[i]
    #print(S)
    for a in A:
        need = base - a
        c = bisect.bisect_left(A, need+1)
        ans += a*(N-c) + S[N]-S[c]
        cnt += (N-c)
    if cnt<M:
        ans += base*(M-cnt)
    print(ans)
    return

def examE2():
    # 参考 https://lumakernel.github.io/ecasdqina/math/FFT/NTT
    # https://atc001.contest.atcoder.jp/submissions/11365995
    # NTT_Primes: {1224736769, 3},{1053818881, 7},..{998244353, 3},..{167772161, 3}
    class fast_fourier_transform():
        def __init__(self, A, B, MOD=998244353, pr=3):
            self.MOD = MOD
            self.pr = pr
            self.La = len(A);
            self.Lb = len(B)
            self.k = (self.La + self.Lb - 1).bit_length()
            self.M = 2 ** self.k
            self.W = [0] * (self.M // 2)
            self.Y = [0] * (self.M // 2)

            self.A = [0] * self.M;
            self.B = [0] * self.M
            for i in range(self.La):
                self.A[i] = A[i]
            for i in range(self.Lb):
                self.B[i] = B[i]
            return

        def convolve(self):
            z = pow(self.pr, (self.MOD - 1) // self.M, self.MOD)
            x = pow(z, self.MOD - 2, self.MOD)
            j = self.M // 4
            while j > 0:
                self.W[j] = z
                z = z * z % self.MOD
                self.Y[j] = x
                x = x * x % self.MOD
                j //= 2
            self.genwy(0, self.M // 4, 1, 1)
            self.A = self.NTT(self.A)
            self.B = self.NTT(self.B)
            rep = [0] * self.M
            for i in range(self.M):
                rep[i] = (self.A[i] * self.B[i]) % self.MOD
            rep = self.NTT(rep, True)
            return rep

        def genwy(self, i, b, z, x):
            if b == 0:
                self.W[i] = z
                self.Y[i] = x
            else:
                self.genwy(i, b // 2, z, x)
                self.genwy(i + b, b // 2, z * self.W[b] % self.MOD, x * self.Y[b] % self.MOD)
            return

        def NTT(self, F, inverse=False):
            if not inverse:
                u = 0;
                v = 1
            else:
                u = 1;
                v = 0
            U = [1, 2 ** (self.k - 1)]
            while (U[1] > 0):
                jh = 0
                while (jh < U[u]):
                    if not inverse:
                        wj = self.W[jh]
                    else:
                        wj = self.Y[jh]
                    j = jh * U[v] * 2
                    je = j + U[v]
                    while (j < je):
                        if not inverse:
                            ajv = wj * F[j + U[v]] % self.MOD
                            F[j + U[v]] = (F[j] + self.MOD - ajv) % self.MOD
                            F[j] = (F[j] + ajv) % self.MOD
                        else:
                            ajv = (F[j] + self.MOD - F[j + U[v]]) % self.MOD
                            F[j] = (F[j] + F[j + U[v]]) % self.MOD
                            F[j + U[v]] = wj * ajv % self.MOD
                        j += 1
                    jh += 1
                U[0] *= 2
                U[1] //= 2
            if inverse:
                invk = pow(self.M, self.MOD - 2, self.MOD)
                return [F[i] * invk % self.MOD for i in range(self.La + self.Lb - 1)]
            return F

    N, M = LI()
    A = LI()
    B = [0]*(max(A))
    for a in A:
        B[a-1] += 1
    F = fast_fourier_transform(B,B)
    C = [0] + F.convolve()
    #print(C)
    ans = 0
    for i in range(len(C))[::-1]:
        c = C[i]
        if M>c:
            ans += c*(i+1)
            M -= c
        else:
            ans += M*(i+1)
            break
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examE2()

"""

"""

Submission status: Wrong Answer

Solution code:
class FFT():
    def __init__(self, n, p, w):
        # pは素数で, wは1のn乗根(mod p)
        # 例:(n,p,w)=(4,5,2),(131072,1483210753,18),(262144,347078657,13)
        self.n = n
        self.p = p
        self.w = w
        self.rn = pow(n, p-2, p)
        self.rw = pow(w, p-2, p)

    def base(self, A, n, w):
        if n == 1:
            return A
        p = self.p
        for i in range(n-len(A)):
            A.append(0)
        F0 = self.base(A[0::2], n//2, pow(w, 2, p))
        F1 = self.base(A[1::2], n//2, pow(w, 2, p))
        x = 1
        F = []
        for i in range(n):
            f = (F0[i % (n//2)] + x * F1[i % (n//2)]) % p
            x = (x * w) % p
            F.append(f)
        return F

    def fft(self, A):
        # 順変換
        return self.base(A, self.n, self.w)

    def ift(self, A):
        # 逆変換
        F = self.base(A, self.n, self.rw)
        return [(f * self.rn) % self.p for f in F]

    def conv(self, A, B):
        # AとBの畳み込み
        nA, nB = len(A), len(B)
        nC = nA + nB - 1
        FA = self.fft(A)
        FB = self.fft(B)
        FC = [FA[i]*FB[i] for i in range(self.n)]
        C = self.ift(FC)
        return C[:nC]


_, m = map(int, input().split())
*A, = map(int, input().split())
n, p, w = 262144,2662072321,21
C = [0] * n
for a in A:
    C[a] += 1
C = FFT(n, p, w).conv(C, C)
PC = []
for p, c in enumerate(C):
    PC.append((p, c))
PC = PC[:2*max(A)+1][::-1]
cnt = 0
power = 0
for p, c in PC:
    if cnt + c > m:
        break
    cnt += c
    power += p*c
power += (m-cnt)*p
print(power)

Submission status: Wrong Answer

Solution code:
def main():
	n,m = map(int, input().split())
	a = list(map(int,input().split()))
	a.sort(reverse=True)
	
	ans = [ 0 for _ in range(m)]
	for i in range(n):
		for j in range(i,n):
			handshake = a[i] + a[j]
			if handshake < min(ans):
				break
			else:
				ans.sort()
				if i == j:
					ans[0] = handshake
				else:
					ans[0:2] = [handshake, handshake]
	print(sum(ans))

if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
import bisect


def cumsum(A):
    # 累積和
    S = [0]
    x = 0
    for a in A:
        x += a
        S.append(x)
    return S


def f(A, x):
    # A[i]+A[j]>=xとなる(i,j)の個数
    cnt = 0
    for a in A:
        cnt += len(A)-bisect.bisect_left(A, x-a)
    return cnt


def g(A, x):
    # A[i]+A[j]>=xとなるA[i]+A[j]の総和
    n = len(A)
    S = cumsum(A)
    sm = 0
    for a in A:
        cnt = bisect.bisect_left(A, x-a)
        sm += (n-cnt)*a+S[n]-S[cnt]
    return sm


def h(A, m):
    # A[i]+A[j]のm番目を求める
    left, right = 2*min(A), 2*max(A)
    while right-left > 1:
        mid = (left+right)//2
        if f(A, mid) >= m:
            left = mid
        else:
            right = mid
    return left


n, m = map(int, input().split())
*A, = map(int, input().split())
x = h(A, m)
k = f(A, x)
s = g(A, x)
ans = s-(k-m)*x
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = np.array(input().split(),np.int64)
    a = np.sort(a)
    cum = np.zeros(N+1,dtype=int)
    cum[1:] = np.cumsum(a)
    
    l,r = -1,10**5+5
    while r-l > 1:
        mid = (l+r)//2
        ab_mid = (N-np.searchsorted(a,mid-a,side="left")).sum()
        if ab_mid >= M:
            l = mid
        else:
            r = mid

    pos_rev = np.searchsorted(a,r-a,side="left")
    count = (N-pos_rev).sum()
    ans = (cum[-1]-cum[pos_rev]).sum()
    ans += (a*(N-pos_rev)).sum()
    ans += (M-count)*l
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = np.array(input().split(),np.int64)
    a = np.sort(a)
    cum = np.zeros(N+1,dtype=int)
    cum[1:] = np.cumsum(a)
    
    l,r = -1,10**5+5
    while r-l > 1:
        mid = (l+r)//2
        ab_mid = np.sum(N-np.searchsorted(a,mid-a,side="left"))
        if ab_mid >= M:
            l = mid
        else:
            r = mid

    pos_rev = np.searchsorted(a,r-a,side="left")
    count = np.sum(N-pos_rev)
    ans = np.sum(cum[-1]-cum[pos_rev])
    ans += np.sum(a*(N-pos_rev))
    ans += (M-count)*l
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = np.array(input().split(),np.int64)
    a = np.sort(a)
    cum = np.zeros(N+1,dtype=int)
    cum[1:] = np.cumsum(a)
    
    l,r = -1,10**5+5
    while r-l > 1:
        mid = (l+r)//2
        ab_mid = np.sum(N-np.searchsorted(a,mid-a))
        if ab_mid >= M:
            l = mid
        else:
            r = mid

    pos_rev = np.searchsorted(a,r-a)
    count = np.sum(N-pos_rev)
    ans = np.sum(cum[-1]-cum[pos_rev])
    ans += np.sum(a*(N-pos_rev))
    ans += (M-count)*l
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = list(map(int,input().split()))
    a = np.sort(a)
    cum = np.zeros(N+1,dtype=int)
    cum[1:] = np.cumsum(a)
    
    l,r = -1,10**5+5
    while r-l > 1:
        mid = (l+r)//2
        ab_mid = np.sum(N-np.searchsorted(a,mid-a))
        if ab_mid >= M:
            l = mid
        else:
            r = mid

    pos_rev = np.searchsorted(a,r-a)
    count = np.sum(N-pos_rev)
    ans = np.sum(cum[-1]-cum[pos_rev])
    ans += np.sum(a*(N-pos_rev))
    ans += (M-count)*l
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = list(map(int,input().split()))
    a = np.sort(a)
    cum = np.zeros(N+1,dtype=int)
    cum[1:] = np.cumsum(a)
    
    def power(x,y):
        pos = np.searchsorted(a,x-y)
        count = np.sum(N-pos)
        if count >= M:
            return True
        else:
            return False
    
    l,r = -1,10**5+5
    while r-l > 1:
        mid = (l+r)//2
        if power(mid,a):
            l = mid
        else:
            r = mid

    pos_rev = np.searchsorted(a,r-a)
    count = np.sum(N-pos_rev)
    ans = np.sum(cum[-1]-cum[pos_rev])
    ans += np.sum(a*(N-pos_rev))
    ans += (M-count)*l
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = sorted(list(map(int,input().split())))
    b = [0]+a
    a = np.array(a)
    cum = np.cumsum(b)
    
    def power(x,y):
        pos = np.searchsorted(a,x-y)
        count = np.sum(N-pos)
        if count >= M:
            return True
        else:
            return False
    
    l,r = -1,10**5+5
    while r-l > 1:
        mid = (l+r)//2
        if power(mid,a):
            l = mid
        else:
            r = mid

    def solve(x):
        ans = 0
        pos_rev = np.searchsorted(a,x-a)
        pos = N-pos_rev
        count = np.sum(pos)
        ans = np.sum(a*pos+cum[-1]-cum[pos_rev])
        return ans+(M-count)*l
        
    print(solve(r))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = sorted(list(map(int,input().split())))
    b = [0]+a
    a = np.array(a)
    cum = np.cumsum(b)
    
    def power(x,y):
        pos = np.searchsorted(a,x-y)
        count = np.sum(N-pos)
        if count >= M:
            return True
        else:
            return False
    
    l,r = 0,10**5+1
    while r-l > 1:
        mid = (l+r)//2
        if power(mid,a):
            l = mid
        else:
            r = mid

    def solve(x):
        ans = 0
        pos_rev = np.searchsorted(a,x-a)
        pos = N-pos_rev
        count = np.sum(pos)
        ans = np.sum(a*pos+cum[-1]-cum[pos_rev])
        return ans+(M-count)*(x-1)
        
    print(solve(r))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import numpy as np

def main():
    N,M = map(int,input().split())
    a = sorted(list(map(int,input().split())))
    b = [0]+a
    a = np.array(a)
    cum = np.cumsum(b)
    
    def power(x,y):
        pos = np.searchsorted(a,x-y)
        count = np.sum(N-pos)
        if count >= M:
            return True
        else:
            return False
    
    l,r = 0,10**5+1
    while r-l > 1:
        mid = (l+r)//2
        if power(mid,a):
            l = mid
        else:
            r = mid

    def solve(x,y):
        ans = 0
        pos_rev = np.searchsorted(a,x-y)
        pos = N-pos_rev
        count = np.sum(pos)
        ans = np.sum(a*pos+cum[-1]-cum[-pos-1])
        return ans-(x-1)*(count-M)
        
    print(solve(r,a))

if __name__ == "__main__":
    main()