Problem:


Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6



Sample input:
4
2 2 1 3


Sample output:
7

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
#A=[1,1,1,1,1,1,1]
#N=7
A.sort(reverse=True)
L=[]
dis=[A[0]]
L.append(A[0])
L.append(A[0])
#print(L)
num=0
for i in range(1,len(A)):
    ind=dis.index(max(dis))
    num+=dis.pop(ind)
    #L.insert(ind+1,A[i])
   
    dis.append(A[i])
    dis.append(A[i])
print(num)
#print(L)
#print(dis)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
ans = 0
tmp = 0
for i in range(N):
    if i == 0:
        continue
    elif i == 1:
        ans += A.pop(0)
    elif i % 2 == 0:
        tmp = A.pop(0)
        ans += tmp
    else:
        ans += tmp
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
a_set = sorted(set(a), key=a.index)

maxval = a[0]
cc = {maxval: 1}

ans = 0
idx = 0

for i in range(1, n):
    if a[i] in cc:
        cc[a[i]] += 2
    else:
        cc[a[i]] = 2
    cc[maxval] -= 1
    ans += maxval
    if cc[maxval] == 0:
        idx += 1
        maxval = a_set[idx]
    # print(cc)

print(ans)

Submission status: Time Limit Exceeded

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

N = int(input())

A = list(map(int, input().split()))

A_sort = sorted(A, reverse=True)
sum_num = A_sort.pop(0)

i = 2
while i + 2 <= N:
    sum_num += A_sort.pop(0) * 2
    i += 2

if i + 1 <= N:
    sum_num += A_sort.pop(0)

print(sum_num)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import namedtuple

class Inst:
  def __init__(self, value, next=None):
    self.value = value
    if next is None:
      self.next = self
    else:
      self.next = next
    
#Inst = namedtuple('Inst', ('value', 'next'))

length = int(sys.stdin.readline())

array = sorted([int(i) for i in sys.stdin.readline().split()], reverse=True)

root = Inst(value=array[0], next=None)

def iterate_all(root):
  yield root
  cur = root.next
  while cur != root:
    yield cur
    cur = cur.next

total_score = 0
for i, this in enumerate(array[1:]):
  best_node = root
  best_score = 0
  for node in iterate_all(root):
    score = min(node.value, node.next.value)
    if score > best_score:
      best_node = node
      best_score = score
  total_score += best_score
  
  best_node.next = Inst(value=this, next=best_node.next)

print(total_score)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

conf_max = 0
for p in itertools.permutations(A):
    conf = 0
    for i in range(1, N):
        conf += min(p[i-1], p[0])
    if conf_max < conf:
        conf_max = conf

print(conf_max)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
#A=[1,1,1,1,1,1,1]
#N=7
A.sort(reverse=True)
L=[]
dis=[A[0]]
L.append(A[0])
L.append(A[0])
#print(L)
num=0
for i in range(1,len(A)):
    ind=dis.index(max(dis))
    num+=dis.pop(ind)
    #L.insert(ind+1,A[i])
   
    dis[ind:ind]=[A[i],A[i]]
print(num)
#print(L)
#print(dis)

Submission status: Time Limit Exceeded

Solution code:
def MergeSort(num_list):
  n = len(num_list)
  
  if len(num_list) == 1:
    return num_list
  
  #1. 整列されていないリストを２つのサブリストに分割する
  mid = int(round(n/2))
  
  left = num_list[:mid]
  right = num_list[mid:]
  

  
  #2. 分割したリスト（サブリスト）を整列する。サブリストもマージソートを使って整列させる。（再帰関数）
  l = MergeSort(left)
  r = MergeSort(right)
  
  #3. 2つのサブリストをマージして１つの整列済みリストにする
  return Merge(l,r)
  
# 整列済みリストA、Bを使って、整列済みリストCを作成する
def Merge(A,B):
  C = []
#   print("A",A)
#   print("B",B)
  
  # 1. AとBの先頭の数字を比較し、小さい方をCに追加し追加した値はリストから削除する
  # 2. 手順1をどちらか一方のリストが空になるまで繰り返す。
  while (len(A) > 0) and (len(B) > 0):
    if A[0] < B[0]:
      C.append(A[0])
      del A[0]
    else:
      C.append(B[0])
      del B[0]
  
  # 3. 残った要素をCの末尾に追加する
  if len(A) > 0:
    C.extend(A)
  else:
    C.extend(B)
 
#   print("C",C)
  return C

n = int(input())
array =list(map(int, input().split()))

list = MergeSort(array)

ans = 0
if n % 2 == 0:
  for i in range(n//2):
    ans += 2* list[-i-1]
  ans -= list[-1]
else:
  for i in range((n-1)//2):
   ans += 2*list[-i-1]
  ans += list[-(n-1)//2-1]
  ans -= list[-1]
print(ans)

Submission status: Time Limit Exceeded

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

ans = 0
A.sort(reverse=True)
#print(A)
for i in range(1,N):
    if i == 1:
        ans += A.pop(0)
        continue
    if i % 2 == 0:
        ans += A[0]
    else:
        ans += A.pop(0)
#print(A)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
if __name__ == '__main__':
    n = int(input().strip())
    A = list(map(int, input().strip().split()))
    A.sort(reverse=True)
    score = 0
    if not len(A) < 2:
        min_max_list = [0] * n
        min_max_dict = {A[1]: 2}
        max_value = A[1]
        score = A[0]
        value_list = [A[1]]
        for num, a in enumerate(A[2:]):
            score += max_value
            min_max_dict[max_value] -= 1
            if a in min_max_dict:
                min_max_dict[a] += 2
            else:
                min_max_dict[a] = 2
                value_list.append(a)
            if min_max_dict[max_value] == 0:
                del(value_list[0])
                max_value = value_list[0]
    print(score)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
from collections import defaultdict
from heapq import heappop, heappush
import itertools
import random
from collections import deque
from decimal import *
import queue

input = sys.stdin.readline

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

class Queue:
    def __init__(self, queue = None):
        if type(queue) is type([]):
            self.queue = queue
        else:
            self.queue = []

    def enqueue(self, e):
        self.queue.append(e)
        return self.queue

    def dequeue(self):
        try:
            qEl = self.queue[0]
            del self.queue[0]
            return qEl
        except IndexError:
            return None


def main():
	N = inputInt()
	A = inputList()

	A.sort()
	A = A[::-1]
	ans = 0
	maxs = 0
	cnt = 0
	fst = True

	ansans = []
	pgt = Queue()
	for i,val in enumerate(A):
		if i == 0:
			pgt.enqueue(val)
		else:
			tmp = pgt.dequeue()
			ansans.append(tmp)

			pgt.enqueue(val)

			if tmp == val:
				pgt.enqueue(val)
			else:
				pgt.enqueue(val)

	#print(ansans)
	print(sum(ansans))


#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

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

A.sort()
A.reverse()

list = []
ans = 0
list.append(A[0])
for i in range(1, len(A)):
        ans += list[0]
        list.pop(0)
        list.append(A[i])
        list.append(A[i])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import copy
N = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
b = []
for i in range(len(a)):
    b.append(0)

ans = 0
second = 0
for i in range(len(a)):
    c = []
    for co2 in b:
        c.append(copy.copy(co2))
    c.sort(reverse=True)
    for j in range(len(c)):
        if(c[0] > c[j]):
            second = c[j]
            break
    if(i == 1):
        second = c[0]
    b[i] = a[i]
    if(i == 0):
        for all in range(len(a)):
            b[all] = a[i]
    if(i != 1):
        if(b[i] < second):
            for k in range(b.index(second), len(b)-1):
                b[k+1] = b[k]
            b[b.index(second)] = 0
            b[b.index(second)-1] = a[i]
    ans += second
    #print(b, end=' ')
    #print(ans, end=' ')
    #print(second)

print(ans)

Submission status: Time Limit Exceeded

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

A.sort()
A.reverse()

list = []
ans = 0
for i in range(len(A)):
    if i == 0:
        list.append(A[i])
    elif list:
        ans += list[0]
        list.pop(0)
        list.append(A[i])
        list.append(A[i])

print(ans)

Submission status: Time Limit Exceeded

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

l=[]
n=A.pop()
n2=A.pop()
sum=n
comfort={n2:[[n,n2],[n2,n]]}

while A:
  max=sorted(comfort.keys())[-1]
  if comfort.get(max)==None:print(0)
  n=comfort[max].pop()
  if comfort[max]==[]:del comfort[max]
  sum+=max
  n2=A.pop()
  if comfort.get(min(n[0],n2))==None:comfort[min(n[0],n2)]=[]
  if comfort.get(min(n[1],n2))==None:comfort[min(n[1],n2)]=[]
  comfort[min(n[0],n2)].append([n[0],n2])
  comfort[min(n[1],n2)].append([n[1],n2])
print(sum)

Submission status: Time Limit Exceeded

Solution code:
n= int(input())
As= list(map(int, input().split()))
As.sort(reverse=True)

def best_seat(ar):
	if len(ar)==0:
		return 0
	else:
		ar.append(ar[0])
		max_=0
		for i in range(len(ar)-1):
			test= min(ar[i],ar[i+1])
			if test>max_:
				max_=test
				ans= i+1
		ar.pop(-1)
		return ans

def com_value(ar):
	if len(ar)==0:
		return 0
	else:
		ar.append(ar[0])
		max_=0
		for i in range(len(ar)-1):
			test= min(ar[i],ar[i+1])
			if test>max_:
				max_=test
				ans= i+1
		ar.pop(-1)
		return max_

table=[]

ans=0
for num in As:
	ans+= com_value(table)
	table.insert(best_seat(table), num)
	
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

length = int(sys.stdin.readline())

array = sorted([int(i) for i in sys.stdin.readline().split()], reverse=True)

array = list(array)

added = array[0:1]
to_add = array[1:]

score = 0
while to_add:
  inst = to_add.pop(0)
  scores = [min(added[i-1], added[i]) for i in range(len(added))]
  index = max(range(len(scores)), key=lambda i: scores[i])
  max_score = scores[index]
  score += max_score
  added.insert(index, inst)

print(score)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = sorted(list(map(int,input().split())), reverse=True)
c = [a[0]]
ans = 0
for i in range(n-1):
    max_c = c[0] + c[len(c)-1]
    good_position = 0
    good_c = min(c[0],c[len(c)-1])
    for j in range(len(c)-1):
        if c[j]+c[j+1]>max_c:
            max_c = c[j]+c[j+1]
            good_position = j+1
            good_c = min(c[j],c[j+1])
    c.insert(good_position, a[i+1])
    ans = ans + good_c
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
B = []
for i in range(N):
    a = A.pop(0)
    B.append(a)
    B.append(a)
ans = 0
B.pop()
for i in range(N-1):
    a = B.pop()
    ans += a
print(ans)

Submission status: Time Limit Exceeded

Solution code:
if __name__ == '__main__':
    n = int(input().strip())
    A = list(map(int, input().strip().split()))
    A.sort(reverse=True)
    score = 0
    if not len(A) < 2:
        min_max_list = [0] * n
        min_max_dict = {A[1]: 2}
        max_value = A[1]
        score = A[0]
        for num, a in enumerate(A[2:]):
            score += max_value
            min_max_dict[max_value] -= 1
            if a in min_max_dict:
                min_max_dict[a] += 2
            else:
                min_max_dict[a] = 2
            if min_max_dict[max_value] == 0:
                del(min_max_dict[max_value])
                max_value = max(min_max_dict.keys())
    print(score)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
l=[]
i=0
ans=0
while a:
    i+=1
    m=a.pop(0)
    if i==1:
        l.append(m)
    elif i==2:
        l.append(m)
        ans+=l[0]
    else:
        mx=[0,0]
        for j in range(len(l)):
            if j < len(l)-1:
                b=min(l[j],l[j+1])
                if mx[0]<b:
                    mx[0]=b
                    mx[1]=j+1
            else:
                b=min(l[j],l[0])
                if mx[0]<b:
                    mx[0]=b
                    mx[1]=j+1
        l.insert(mx[1],m)
        ans+=mx[0]
print(ans)

Submission status: Time Limit Exceeded

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


def find_index(l):
    x = []
    length = len(l)-1
    for i in range(length):
        x.append(min(l[i], l[i+1]))
    max_value = max(x)
    return [x.index(max_value) + 1, max_value]


ans = 0
a.sort(reverse=True)
l = [a[0], a[0]]
x = []
length = len(l)-1
for i in range(length):
    x.append(min(l[i], l[i+1]))

for i in a[1:]:
    index_value = find_index(l)
    l.insert(index_value[0], i)
    ans += index_value[1]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    input()  # n
    friendliness = [int(x) for x in input().split()]
    friendliness.sort()
    friendliness = deque(friendliness)
    edges = deque()
    popped = friendliness.pop()
    edges.append(popped)
    ans = 0
    while friendliness:
        ans += edges.pop()
        popped = friendliness.pop()
        edges.append(popped)
        edges.append(popped)
        edges = deque(sorted(edges))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
num_people = int(input())
friendly = input()

friend = [int(n) for n in friendly.split()]
friend.sort(reverse = True) 

confort = 0

circle = [friend[0]]


temp_mini = 0
insert = 0

for i in range(1, num_people):
  for j in range(len(circle)):
    temp = [circle[j-1], circle[j]]
    mini = min(temp)
    if mini > temp_mini:
      temp_mini = mini
      insert = j
    
  confort += mini
  circle.insert(j, friend[i])


print(confort)

Submission status: Time Limit Exceeded

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


def find_index(l):
    x = []
    for i in range(len(l)-1):
        x.append(min(l[i], l[i+1]))
    return [x.index(max(x)) + 1, max(x)]


ans = 0
a.sort(reverse=True)
l = [a[0], a[0]]
x = []
for i in range(len(l)-1):
    x.append(min(l[i], l[i+1]))

for i in a[1:]:
    index_value = find_index(l)
    l.insert(index_value[0], i)
    ans += index_value[1]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A= list(map(int,input().split()))
A.sort(reverse=True)
top = A[0]
if N == 2:
  B=[top]
else:
  B=[top]

c=0
  
for i in range(1,N):
  if i == 1:
    ma = top
    tekito=1
  else:
    ma = min(B[0],B[1])
  mai = 1
  for j in range(1,len(B)):
    if j == len(B)-1:
      tekito = 0
    else:
      tekito = j+1
    #print(tekito)
    koho = min(B[j],B[tekito])
    if ma > koho:
      ma =koho
      mai = tekito
  c+= ma
  B.insert(tekito, A[i])
      
#c=0
#d= len(B)
#for i in range(d):
#  if i == 1:
#    continue
#  if i != d-1:
#    c+= min(B[i-1],B[i+1])
#  else:
#    c+= min(B[i-1],B[0])
#print(B)
print(c)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

length = int(sys.stdin.readline())

array = np.array([int(i) for i in sys.stdin.readline().split()], dtype=np.int32)

array[::-1].sort()

array = list(array)

added = array[0:1]
to_add = array[1:]

score = 0
while to_add:
  inst = to_add.pop(0)
  scores = [min(added[i-1], added[i]) for i in range(len(added))]
  index = np.argmax(scores)
  max_score = scores[index]
  score += max_score
  added.insert(index, inst)

print(score)

Submission status: Time Limit Exceeded

Solution code:
a = int(input())
b = list(map(int,input().split()))
c = []

ans = 0    

b = sorted(b, reverse=True)
c.append(b.pop(0))
ans += c[0]
c.append(b.pop(0))
nmax = 0
maxindex = 0
if a > 2:
    ans += c[1]
    c.append(b.pop(0))
    if a > 3:
        for i in range(a - 3):
            nmax = 0
            maxindex = 0
            for j in range(len(c)):
                if j + 1 == len(c):
                    s = min(c[j], c[0])
                else:
                    s = min(c[j], c[j + 1])
                if nmax < s:
                    nmax = s
                    maxindex = j + 1
            ans += nmax
            c.insert(maxindex, b.pop(0))
print(str(ans))

Submission status: Time Limit Exceeded

Solution code:
import itertools

N = int(input())
A = []
A_keys = range(1, N + 1)
A_val = list(map(int, input().split()))
A_dic = dict(zip(A_keys, A_val))
A_sorted = sorted(A_dic.items(), key=lambda x:x[1], reverse=True)
len_A = len(A_sorted)
for i in range(len_A):
  A += [A_sorted[i][1]]
  
circle = [A[0], A[1]]
comf = A[0]

for i in range(2, len_A):
  cmi = [i for i, v in enumerate(circle) if v == max(circle)]
  if len(cmi) != 1:
    comf += circle[cmi[0]]
    circle[cmi[1]:cmi[1]] = [A[i]]
  else:
    if circle[cmi[0] - 1] > circle[cmi[0] + 1]:
      comf += circle[cmi[0] - 1]
      circle[cmi[0]:cmi[0]] = [A[i]]
    else:
      comf += circle[cmi[0] + 1]
      circle[(cmi[0]+1):(cmi[0]+1)] = [A[i]]
print(comf)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
#A=[1,1,1,1,1,1,1]
#N=7
A.sort(reverse=True)
L=[]
dis=[A[0]]
L.append(A[0])
L.append(A[0])
#print(L)
num=0
for i in range(1,len(A)):
    ind=dis.index(max(dis))
    num+=dis[ind]
    #L.insert(ind+1,A[i])
    del dis[ind]
    dis[ind:ind]=[A[i],A[i]]
print(num)
#print(L)
#print(dis)

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8

import sys
import math
import time
#import numpy as np
import collections
from collections import deque
from collections import Counter
import queue
import copy
import bisect
import heapq
import itertools


#sys.setrecursionlimit(10**7)
#N, Q = map(int, input().split())
#G = [list(input()) for i in range(H)]
#INF = V * 10001
#A = [int(i) for i in input().split()]
#AB = [list(map(int, input().split())) for _ in range(K)]

N = int(input())
A = [int(i) for i in input().split()]
temp = []
temp.append(1)
A.sort(reverse=True)
M = []
M.append(A[0])
ans = 0
Mima = 0
Tima = 0
a = 1
Count = []
Count.append(1)
count = 0

for i in range(1,N):
  if(count == 0):
    pass
  elif(sum(Count[:count])>=Count[count]):
    a = 2
  Count[count]+= 1
  if(A[i]!=M[Mima]):
    M.append(A[i])
    temp.append(2)
    Tima += 1
    temp[Mima] -= 1
    count += 1
    Count.append(1)
  else:
    temp[Tima] += a
  
  ans += M[Mima]

  if(temp[Mima]==0):
    Mima += 1



print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

A.sort(reverse=True)

C = [A[0], A[0]]
q = deque([1])

answer = 0

for i in range(1, N):
    a = A[i]
    insertPoint = q.popleft()
    C.insert(insertPoint, a)
    answer += min(C[insertPoint-1], C[insertPoint+1])
    for i in range(len(q)):
        if insertPoint < q[i]:
            q[i] += 1
    q.append(insertPoint)
    q.append(insertPoint+1)

print(answer)

Submission status: Time Limit Exceeded

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

import numpy as np

result = 0
args = np.argsort(A)
coms = []
for arg in reversed(args):
    com = A[arg]
    if len(coms)==0:
        coms.append(com)
    elif len(coms)==1:
        coms.append(com)
        result+=coms[0]
    else:
        current=-1
        insert_arg = None
        for tmp in range(len(coms)):
            min_ = min(coms[tmp-1], coms[tmp])
            if current<min_:
                insert_arg = tmp
                current=min_
            if current==min_ or current<min_:
                break
        result+=current
        tmp = coms[insert_arg:]
        coms[:insert_arg-1].append(A[arg])
        coms += tmp
print(result)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse = True)
Sum = 0
for i in range(len(A)):
    if i == 0:
        pass
    elif i == 1:
        Sum += A.pop(0)
    else:
        if i % 2 == 0:
            Sum += A[0]
        else:
            Sum += A.pop(0)
print(Sum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = sorted(list(map(int,input().split())), reverse=True)#降順
kukan = []
ans = 0
kukan.append(A.pop(0))#降順リスト
for i in range(N-1):
    ans += kukan.pop(0)#区間の最大値を取り出す
    kukan.extend([A[i],A[i]])
print(ans)

Submission status: Time Limit Exceeded

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

total = 0
L = [A[N-1]]
cnt = 1
cnt1 = 1
for i in range( N - 2, -1, -1 ):
  a = L[0]
  L = L[1:]
  total += a
  L.append( A[ i ] )
  L.append( A[ i ] )
  cnt += 2
  cnt1 += 1
  if cnt > N:
    break

print( total + sum(L[ :N-cnt1 ]) )

Submission status: Time Limit Exceeded

Solution code:

import sys, io, os, re
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from pprint import pprint
from math import sin, cos, pi, radians, sqrt, floor, ceil
from copy import copy, deepcopy
from collections import deque
from fractions import gcd
from functools import reduce
from itertools import groupby
from heapq import heapify, heappush, heappop

# sys.setrecursionlimit(5000)

n1 = lambda: int(sys.stdin.readline().strip())
nn = lambda: list(map(int, sys.stdin.readline().strip().split()))
f1 = lambda: float(sys.stdin.readline().strip())
fn = lambda: list(map(float, sys.stdin.readline().strip().split()))
s1 = lambda: sys.stdin.readline().strip()
sn = lambda: list(sys.stdin.readline().strip().split())
nl = lambda n: [n1() for _ in range(n)]
fl = lambda n: [f1() for _ in range(n)]
sl = lambda n: [s1() for _ in range(n)]
nm = lambda n: [nn() for _ in range(n)]
fm = lambda n: [fn() for _ in range(n)]
sm = lambda n: [sn() for _ in range(n)]

def array1(n, d=0): return [d] * n
def array2(n, m, d=0): return [[d] * m for x in range(n)]
def array3(n, m, l, d=0): return [[[d] * l for y in xrange(m)] for x in xrange(n)]
def linc(A, d=1): return map(lambda x: x + d, A)
def ldec(A, d=1): return map(lambda x: x - d, A)

N = n1()
A = nn()

A.sort(reverse=True)

tbl = [A[0], A[1]]
cft = A[0]

for i in range(2, N):
    c = 0
    d = -1
    for j in range(0, len(tbl)):
        tmp = min(tbl[(j)%len(tbl)], tbl[(j+1)%len(tbl)])
        if tmp > c:
            c = tmp
            d = j

    cft += c
    tbl = tbl[:d+1] + [A[i]] + tbl[d+1:]
    #print(tbl, c, cft)

print(cft)

Submission status: Time Limit Exceeded

Solution code:
import copy
number = int(input())
a = [number]
circle = []
a = list(map(int,input().split()))

newlist = sorted(a, reverse=True)

max = 0
for i in range(0,number):
    if i == 0:
        circle.append(newlist[0])
    elif i == 1 :
        circle.append(newlist[1])
        max += circle[0]
    else :
        index = 0
        max_tmp = 0
        for l in range(0, len(circle) ):
            calu = 0
            circle_tmp = copy.deepcopy(circle)
            circle_tmp.insert(l,circle[i - 1])
            a = 0
            b = 0
            if l - 1 > -1 :
                a = circle_tmp[l -1]
            else :
                a = circle_tmp[len(circle_tmp) -1]

            if l + 1 < len(circle_tmp) :
                b = circle_tmp[l + 1]
            else :
                b = circle_tmp[0]

            if a < b:
                calu = a
            else:
                calu = b

            if max_tmp < calu:
                index = l
                max_tmp = calu

            if l == len(circle) -1 :
                circle.insert(l, newlist[i])
                max += max_tmp

print(max)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input().split()
A = []
for s in S:
    A.append(int(s))
A.sort(reverse=True)

result = 0

B = []
for i in range(N):
    flag = True
    if i == 0:
        B.append(A[i])
    elif i == 1:
        result += B[0]
        B.append(A[i])
    else:
        temp = []
        for j in range(len(B)-1):
            temp.append(min(B[j],B[j+1]))
        temp.append(min(B[0],B[-1]))
        select = max(temp)
        result+=select
        for j in range(len(B)-1):
            if select == min(B[j], B[j+1]):
                B.insert(j+1, A[i])
                flag = False
                break
        if flag:
            B.append(A[i])
        
print(result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a_list = list(map(int,input().split()))
output = 3
import itertools

for jun in itertools.permutations(range(n),n):
  arr = []
  outi = 0
  for o,i in enumerate(jun):
    if o == 0:
      arr.append(i)
    else:
      outi += min(a_list[arr[0]],a_list[arr[-1]])
      arr.append(i)
  if output < outi:
    output = outi
    
print(output)

Submission status: Time Limit Exceeded

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

def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid = len(arr) // 2
    # ここで分割を行う
    left = arr[:mid]
    right = arr[mid:]

    # 再帰的に分割を行う
    left = merge_sort(left)
    right = merge_sort(right)

    # returnが返ってきたら、結合を行い、結合したものを次に渡す
    return merge(left, right)


def merge(left, right):
    merged = []
    l_i, r_i = 0, 0

    # ソート済み配列をマージするため、それぞれ左から見ていくだけで良い
    while l_i < len(left) and r_i < len(right):
        # ここで=をつけることで安定性を保っている
        if left[l_i] <= right[r_i]:
            merged.append(left[l_i])
            l_i += 1
        else:
            merged.append(right[r_i])
            r_i += 1

    # 上のwhile文のどちらかがFalseになった場合終了するため、あまりをextendする
    if l_i < len(left):
        merged.extend(left[l_i:])
    if r_i < len(right):
        merged.extend(right[r_i:])
    return merged

b=merge_sort(a)
b.reverse()
c=[]
hap=0
for i in range(n):
    q=b.pop(0)
    if len(c)==0:
        c.append(q)
        hap+=0
    elif len(c)==1:
        c.append(q)
        hap+=c[0]
    else:
        m=len(c)
        ma=0
        mp=0
        mpl=0
        for j in range(m):
            if c[j-1]>=c[j]:
                ms=c[j]
                mp=j
            elif c[j]>c[j-1]:
                ms=c[j-1]
                mp=j-1

            if ma<=ms:
                ma=ms
                mpl=mp
        
        c.insert(mpl,q)
        hap+=ma

print(hap)

Submission status: Time Limit Exceeded

Solution code:
import queue
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)

confort_score = 0
l = []
q = []#queue.Queue()

for a in A:
    if l == []:
        l.append(a)
        #q.put(0)
        q=[0]
    else:
        idx = q[0]#q.get()
        q=q[1:]
        q=[j if j < idx else j + 1 for j in q]
        q.append(idx)
        q.append(idx+1)
        #q.put(idx)
        #q.put(idx+1)
        if idx!=(len(l)-1):
            confort_score += min(l[idx],l[idx+1])
        else:
            confort_score += min(l[0],l[idx])
        l.insert(idx, a)

print(confort_score)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p_list = list(map(int, input().split(" ")))
p_list.sort(reverse = True)
a_list=[]
a=0
for i in range(n-1):
  if i == 0:
    a=p_list[i]
    a_list.append(p_list[i])
  elif i == 1:
    a += p_list[i]
    a_list.append(p_list[i])
  else:
    for x in range(i-1):
      x_list =[]
      if a_list[x-1] <= a_list[x+1]:
        x_list.append(a_list[x-1])
      else:
        x_list.append(a_list[x+1])
    a += max(x_list)
    a_list.insert(x_list.index(max(x_list)),p_list[i])
print(a)

Submission status: Time Limit Exceeded

Solution code:
if __name__ == '__main__':
    n = int(input().strip())
    A = list(map(int, input().strip().split()))
    A.sort(reverse=True)
    score = 0
    if not len(A) < 2:
        min_max_list = [A[1], A[1]]
        score = A[0]
        for a in A[2:]:
            arg_max_index = min_max_list.index(max(min_max_list))
            score += min_max_list[arg_max_index]
            min_max_list[arg_max_index] = a
            min_max_list.insert(arg_max_index, a)
    print(score)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
#A=[1,1,1,1,1,1,1]
#N=7
A.sort(reverse=True)
L=[]
dis=[A[0]]
L.append(A[0])
L.append(A[0])
#print(L)
num=0
for i in range(1,len(A)):
    ind=dis.index(max(dis))
    num+=dis[ind]
    L.insert(ind+1,A[i])
    del dis[ind]
    dis[ind:ind]=[A[i],A[i]]
print(num)
#print(L)
#print(dis)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
data = list(map(int, input().split()))
data.sort(reverse=True)

ans = 0
q = []
for d in data:
    if q == []:
        q.append(d)
        ans += 0
        continue

    if len(q) == 1:
        q.append(d)
        ans += q[0]
        continue

    # qの探索から挿入
    max_point = -1
    max_score = -1
    for i in range(len(q) - 1):
        if min(q[i], q[i+1]) > max_point:
            max_point = i + 1
            max_score = min(q[i], q[i+1])
    
    q = q[:max_point] + [d] + q[max_point:]
    ans += max_score
    # print(q)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    input()  # n
    friendliness = [int(x) for x in input().split()]
    friendliness.sort()
    friendliness = deque(friendliness)
    edges = []
    popped1 = friendliness.pop()
    popped2 = friendliness.pop()
    edges.append((popped1, popped2))
    edges.append((popped2, popped1))
    ans = popped1
    while friendliness:
        popped = friendliness.pop()
        tmp_data = (-1, -1)  # max_comfort, edge_index
        for i, edge in enumerate(edges):
            x = min(edge)
            if x > tmp_data[0]:
                tmp_data = (x, i)
        ans += tmp_data[0]
        edge_tmp = edges[tmp_data[1]]
        edges[tmp_data[1]] = (edge_tmp[0], popped)
        edges.append((popped, edge_tmp[1]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

total = 0
L = [A[N-1]]
for i in range( N - 2, -1, -1 ):
  a = L[0]
  L = L[1:]
  total += a
  L.append( A[ i ] )
  L.append( A[ i ] )

print( total )