jiahuimbzuai/CoQuIR huggingface dataset:
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	N, M := nextInt(), nextInt()
	As := nextInts(N)

	BCs := make([][]int, M)
	for i := 0; i < M; i++ {
		BCs[i] = nextInts(2)
	}

	sort.Ints(As)
	sort.Sort(BCS(BCs))

	i := 0
	for j := 0; j < M; j++ {
		B, C := BCs[j][0], BCs[j][1]
		if C <= As[i] {
			break
		}
		for B > 0 && i < len(As) && C > As[i] {
			As[i] = C
			B--
			i++
		}
	}

	fmt.Println(Sum(As...))
}

type BCS [][]int

func (bcs BCS) Len() int {
	return len(bcs)
}

func (bcs BCS) Less(i, j int) bool {
	return bcs[i][1] > bcs[j][1]
}

func (bcs BCS) Swap(i, j int) {
	bcs[i], bcs[j] = bcs[j], bcs[i]
}

func Sum(slice ...int) int {
	sum := 0
	for _, v := range slice {
		sum += v
	}
	return sum
}

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Buffer(make([]byte, 256), 1e9)
	sc.Split(bufio.ScanWords)
}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	N, M := nextInt(), nextInt()
	As := nextInts(N)

	BCs := make([][]int, M)
	for i := 0; i < M; i++ {
		BCs[i] = nextInts(2)
	}

	sort.Sort(sort.IntSlice(As))
	sort.Slice(BCs, func(i, j int) bool {
		return BCs[i][1] > BCs[j][1]
	})

	i := 0
	for j := 0; j < M; j++ {
		B, C := BCs[j][0], BCs[j][1]
		if C <= As[i] {
			break
		}
		for B > 0 && i < len(As) && C > As[i] {
			As[i] = C
			B--
			i++
		}
	}

	fmt.Println(Sum(As...))
}

func Sum(slice ...int) int {
	sum := 0
	for _, v := range slice {
		sum += v
	}
	return sum
}

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Buffer(make([]byte, 256), 1e9)
	sc.Split(bufio.ScanWords)
}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}
//  [ruby]
n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i).sort
h = m.times.map{ gets.split.map(&:to_i) }
i = 0
h.sort_by{|u, v| -v}.each do |x, y|
  break if a[i] >= y

  x.times do
    a[i] = y
    i += 1
    break if i >= n
    break if a[i] >= y
  end
  break if i >= n
end


puts a.sum
//  [ruby]
n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
h = []
m.times do
  h << gets.split.map(&:to_i)
end
i = 0
h.sort_by{|u, v| -v}.each do |x, y|
  break if a[i] >= y
  x.times do
    a[i] = y
    i += 1
    break if i >= n
    break if a[i] >= y
  end
  break if i >= n
end
puts a.inject(:+)
//  [ruby]
_  = gets.to_s.split.map(&:to_i)
a  = gets.to_s.split.map(&:to_i).sort
bcs = $<.read.split.map(&:to_i).each_slice(2).sort_by{|b,c| c}

ans = 0

b, c = bcs.pop
a.each do |k|
  
  if b && k < c
    ans += c
    b -= 1
    b,c = bcs.pop if b == 0
  else
    ans += k
  end
end

puts ans
//  [ruby]
n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
a.sort!
total = a.sum
h = Hash.new(0)
a.each { h[_1] += 1 }
d = []
x = Hash.new(0)
m.times do
  b, c = gets.chomp.split.map(&:to_i)
  x[c] += b
end
x.sort{|k1,k2| k1[1]<=>k2[1]}.each do |k, v|
  v.times { d << k }
  break if d.size > n
end
d.sort!.reverse!
[d.size, n].min.times do |i|
  break if a[i] > d[i]

  total = total + d[i] - a[i]
end

puts total
//  [ruby]
n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
a.sort!
total = a.sum
h = Hash.new(0)
a.each { h[_1] += 1 }
d = []
m.times do
  b, c = gets.chomp.split.map(&:to_i)
  b.times { d << c }
end
d.sort!.reverse!
[d.size, n].min.times do |i|
  break if a[i] > d[i]

  total = total + d[i] - a[i]
end

puts total
//  [ruby]
n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
a.sort!
total = a.sum
h = Hash.new(0)
a.each do |_a|
  h[_a] += 1
end
x = Hash.new(0)
m.times do
  b, c = gets.chomp.split.map(&:to_i)
  x[c] += b
end
b = []
x = x.sort {|k1,k2| k1[1] <=> k2[1]}
x.each do |k, v|
  c = [n-b.size, v].min
  c.times{b << k}
  break if b.size >= n
end
b.sort!.reverse!
b.each_with_index do |c, i|
  break if a[i] >= c

  total = total + c - a[i]
end

puts total
//  [rust]
use proconio::{input, fastout};
use std::collections::BTreeMap;

#[fastout]
fn main() {
    input! {
        n: usize, m: usize,
        mut arr: [usize; n],
        rep: [(usize, usize); m],
    }

    arr.sort();

    let mut bset: BTreeMap<usize, usize> = BTreeMap::new();
    for &(b, c) in &rep {
        if bset.contains_key(&c) {
            let bb = bset.get_mut(&c).unwrap();
            *bb += b;
        } else {
            bset.insert(c, b);
        }
    }

    let mut cursor: usize = 0;
    for (&c, &b) in bset.iter().rev() {
        let m = std::cmp::min(n, b+cursor);
        if arr[m-1] >= c {
            for i in cursor..m {
                if arr[i] >= c { break; }
                arr[i] = c;
            }
            break;
        } else {
            for i in cursor..b+cursor { arr[i] = c; }
            cursor = m;
        }
    }

    println!("{}", arr.iter().sum::<usize>() );
}
//  [rust]
use proconio::{input, fastout};
use std::collections::BTreeMap;

#[fastout]
fn main() {
    input! {
        n: usize, m: usize,
        mut arr: [usize; n],
        rep: [(usize, usize); m],
    }

    arr.sort();

    let mut bset: BTreeMap<usize, usize> = BTreeMap::new();
    for &(b, c) in &rep {
        if bset.contains_key(&c) {
            let bb = bset.get_mut(&c).unwrap();
            *bb += b;
        } else {
            bset.insert(c, b);
        }
    }

    let mut cursor: usize = 0;
    for (&c, &b) in bset.iter().rev() {
        if arr[b+cursor-1] >= c {
            for i in cursor..b+cursor {
                if arr[i] >= c { break; }
                arr[i] = c;
            }
            break;
        } else {
            for i in cursor..b+cursor { arr[i] = c; }
            cursor = b+cursor;
        }
    }

    println!("{}", arr.iter().sum::<usize>() );
}
//  [swift]
let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let M = input[1]

let A = readLine()!.split(separator: " ").map { Int($0)! }.sorted()
var B: [[Int]] = []

for i in 0..<M {
  B.append(readLine()!.split(separator: " ").map { Int($0)! })
}

B = B.sorted { $0[1] > $1[1] }

var j = 0
var sum = 0

for i in 0..<A.count {
  if j < B.count && B[j][0] == 0 {
    j += 1
  }
  if j >= B.count || B[j][1] <= A[i] {
    sum += A[i]
  } else {
    B[j][0] -= 1
    sum += B[j][1]
  }
}
print(sum)
//  [swift]
import Foundation

let args = readLine()!.split(separator: " ")
let N = Int(args[0])!
let M = Int(args[1])!

var minA = Int.max
var maxA = 0
var values: [Int: Int] = [:]

readLine()!.split(separator: " ").forEach {
    let a = Int($0)!
    values[a] = 1 + (values[a] ?? 0)
    minA = min(minA, a)
    maxA = max(maxA, a)
}

for _ in 1 ... M { // j
    let args = readLine()!.split(separator: " ")
    var b = Int(args[0])!
    let c = Int(args[1])!
    while b > 0 {
        let a = minA
        if a < c {
            let count = min(values[a]!, b)
            values[a]! -= count
            values[c] = count + (values[c] ?? 0)
            if values[a] == 0 {
                values[a] = nil
            }
            while values[minA] == nil {
                minA += 1
            }
            b -= count
        } else {
            b = 0
        }
    }
    maxA = max(maxA, c)
}

let answer = values.reduce(0, { $0 + $1.key * $1.value })

print(answer)
//  [swift]
import Foundation

let args = readLine()!.split(separator: " ")
let N = Int(args[0])!
let M = Int(args[1])!
var A = readLine()!.split(separator: " ").map { Int($0)! }

A.sort()
for _ in 1 ... M { // j
    let args = readLine()!.split(separator: " ")
    let B = Int(args[0])!
    let C = Int(args[1])!
    var replace = 0
    for b in 0 ..< B {
        if C < A[b] { break }
        replace += 1
    }
    if 0 < replace {
        A.removeFirst(replace)
        var n = 0
        while n < N {
            if C <= A[n] { break }
            n += 1
        }
        for _ in 0 ..< replace {
            A.insert(C, at: n)
        }
    }
}
let answer = A.reduce(0, { $0 + $1 })

print(answer)
//  [swift]
let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let M = input[1]

let A = readLine()!.split(separator: " ").map { Int($0)! }
var B: [[Int]] = []

for i in 0..<M {
  B.append(readLine()!.split(separator: " ").map { Int($0)! })
}

B = B.sorted { $0[1] > $1[1] }

var j = 0
var sum = 0

for i in 0..<A.count {
  if j < B.count && B[j][0] == 0 {
    j += 1
  }
  if j >= B.count || B[j][1] <= A[i] {
    sum += A[i]
  } else {
    B[j][0] -= 1
    sum += B[j][1]
  }
}
print(sum)
//  [typescript]
const log = console.log;

const createScanFunctions = (input: string) => {
  const str = input.trim();
  const len = str.length;
  let index = 0;

  const scan = () => {
    const startIndex = index;

    while (index < len) {
      const char = str[index];

      if (char === " " || char === "\n")
        return str.substring(startIndex, index++);

      index++;
    }

    return str.substr(startIndex);
  };

  const scanInt = () => parseInt(scan());

  return { scan, scanInt };
};

const scanIntArray = (scanIntFunction: () => number, length: number) => {
  const array = new Array<number>(length);
  for (let i = 0; i < length; i++) array[i] = scanIntFunction();

  return array;
};

// ----

const sumReducer = (accumulator: number, currentValue: number) =>
  accumulator + currentValue;
const sum = (numbers: number[]) => numbers.reduce(sumReducer, 0);

// ----

function Main(input: string): void {
  const { scanInt } = createScanFunctions(input);

  const n = scanInt();
  const m = scanInt();
  const a = scanIntArray(scanInt, n).sort((a, b) => a - b);

  const operations = new Array<number[]>(m);
  for (let i = 0; i < m; i++) operations[i] = [scanInt(), scanInt()]; // [b, c]
  operations.sort((opA, opB) => opB[1] - opA[1]);

  let aIndex = 0;

  for (let opIndex = 0; opIndex < m; opIndex++) {
    const [b, c] = operations[opIndex];
    let stop = false;

    for (let i = 0; i < b; i++) {
      if (a[aIndex] >= c) {
        stop = true;
        break;
      }

      a[aIndex++] = c;

      if (aIndex >= n) {
        stop = true;
        break;
      }
    }

    if (stop) break;
  }

  log(sum(a));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
import { readFileSync } from 'fs'

function main(input: string) {
  const [header, cards, ...lines] = input.split('\n').map(v => v.split(' ').map(Number))

  cards.sort((a, b) => a - b)
  lines.sort(([, a], [, b]) => b - a)

  let currentIndex = 0
  let currentCount = 0

  const getNextEnchant = (): number => {
    const value = lines[currentIndex]

    if (value == null) return 0

    const [maxCount, v] = value

    if (currentCount < maxCount) {
      ++currentCount
      return v
    }

    ++currentIndex
    currentCount = 0
    return getNextEnchant()
  }


  for (let i = 0, len = cards.length; i < len; ++i) {
    const enchant = getNextEnchant()
    if (enchant <= cards[i]) break

    cards[i] = enchant
  }

  const result = cards.reduce((sum, v) => sum + v, 0)

  console.log(result)
}

main(readFileSync('/dev/stdin', 'utf8').trim())
//  [typescript]
function main(input) {
  input = input.trim().split("\n");
  const [n, m] = input[0].split(" ").map(a => Number(a));
  const as = input[1].split(" ").map(a => Number(a));
  const bcs = input.slice(2).map(a => a.split(" ").map(b => Number(b)));
  as.sort((a, b) => a-b);
  bcs.sort((a, b) => b[1]-a[1]);
  const ds = [];
  for (let i = 0; i < m; i++) {
    if (n <= ds.length) break;
    const [b, c] = bcs[i];
    ds.push(...Array(b).fill(c));
  }
  let result = 0;
  for (let i = 0; i < n; i++) {
    const a = as[i];
    const d = ds[i];
    result += d ? Math.max(a, d) : a;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
function main(input) {
  input = input.trim().split("\n");
  const [n, m] = input[0].split(" ").map(a => Number(a));
  const as = input[1].split(" ").map(a => Number(a));
  const bcs = input.slice(2).map(a => a.split(" ").map(b => Number(b)));
  as.sort((a, b) => a-b);
  const ds = [];
  for (let i = 0; i < m; i++) {
    if (n <= ds.length) break;
    const [b, c] = bcs[i];
    ds.push(...Array(b).fill(c));
  }
  ds.sort((a, b) => b-a);
  let result = 0;
  for (let i = 0; i < n; i++) {
    const a = as[i];
    const d = ds[i];
    result += d ? Math.max(a, d) : a;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
function main(input) {
  input = input.trim().split("\n");
  const [n, m] = input[0].split(" ").map(a => Number(a));
  const as = input[1].split(" ").map(a => Number(a));
  const bcs = input.slice(2).map(a => a.split(" ").map(b => Number(b)));
  as.sort((a, b) => a-b);
  const ds = [];
  for (let i = 0; i < m; i++) {
    const [b, c] = bcs[i];
    ds.push(...Array(b).fill(c));
  }
  ds.sort((a, b) => b-a);
  let result = 0;
  for (let i = 0; i < n; i++) {
    const a = as[i];
    const d = ds[i];
    result += d ? Math.max(a, d) : a;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
const log = console.log;

const createScanFunctions = (input: string) => {
  const str = input.trim();
  const len = str.length;
  let index = 0;

  const scan = () => {
    const startIndex = index;

    while (index < len) {
      const char = str[index];

      if (char === " " || char === "\n")
        return str.substring(startIndex, index++);

      index++;
    }

    return str.substr(startIndex);
  };

  const scanInt = () => parseInt(scan());

  return { scan, scanInt };
};

const scanIntArray = (scanIntFunction: () => number, length: number) => {
  const array = new Array<number>(length);
  for (let i = 0; i < length; i++) array[i] = scanIntFunction();

  return array;
};

// ----

const createDigitArray = (v: number, capacity: number, base = 10) => {
  const array = new Array(capacity).fill(0);
  let i = 0;

  while (v > 0) {
    array[i] = v % base;
    v = (v / base) | 0;
    i += 1;
  }

  return array;
};

const addDigitArrays = (src: number[], dest: number[]) => {
  const len = dest.length - 1;

  for (let i = 0; i < len; i++) dest[i] += src[i];
};

const fixDigitArray = (array: number[], base = 10) => {
  const len = array.length - 1;

  for (let i = 0; i < len; i++) {
    array[i + 1] += (array[i] / base) | 0;
    array[i] = array[i] % base;
  }
};

const digitArrayToString = (array: number[]) => {
  const len = array.length;

  let i = len - 1;
  let str = "";

  while (i >= 0) {
    if (str !== "" || array[i] !== 0) {
      str += array[i];
    }

    i--;
  }

  return str;
};

// ----

function Main(input: string): void {
  const { scanInt } = createScanFunctions(input);

  const n = scanInt();
  const m = scanInt();

  let a = scanIntArray(scanInt, n).sort((a, b) => a - b);
  const operations = new Array<number[]>(m);

  for (let i = 0; i < m; i++) operations[i] = [scanInt(), scanInt()];

  operations.sort((opA, opB) => opB[1] - opA[1]);

  let index = 0;

  for (let i = 0; i < m; i++) {
    const [b, c] = operations[i];
    let stop = false;

    for (let k = 0; k < b; k++) {
      if (a[index] >= c) {
        stop = true;
        break;
      }

      a[index++] = c;

      if (index >= n) {
        stop = true;
        break;
      }
    }

    if (stop) break;
  }

  const digitCount = 16;
  const digitBase = 65536;

  const reducer = (accumulator: number[], currentValue: number) => {
    addDigitArrays(
      createDigitArray(currentValue, digitCount, digitBase),
      accumulator
    );

    return accumulator;
  };

  const sumDigitArray = a.reduce(reducer, createDigitArray(0, digitCount));
  fixDigitArray(sumDigitArray, digitBase);

  log(digitArrayToString(sumDigitArray));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [python]
import sys 

def A():
  n = int(sys.stdin.readline().rstrip())
  charge = (n+999)//1000 * 1000 - n
  print(charge)


from collections import Counter
def B():
  n, *s = sys.stdin.read().split() 
  c = Counter(s)
  for v in 'AC, WA, TLE, RE'.split(', '):
    print(f'{v} x {c[v]}')


def C():
  h, w, k = map(int, sys.stdin.readline().split())
  c = [sys.stdin.readline().rstrip() for _ in range(h)]
  tot = 0
  for i in range(1<<h):
    for j in range(1<<w):
      cnt = 0
      for y in range(h):
        for x in range(w):
          if i>>y & 1 or j>>x & 1:
            continue 
          cnt += c[y][x] ==  '#'
      tot += cnt == k
  print(tot)


def D():
  n, *a = map(int, sys.stdin.read().split())
  a.sort(reverse=True)
  res = a[0] + sum(a[1:1+(n-2)//2])*2 + a[1+(n-2)//2]*(n & 1)
  print(res)


def E():
  pass


def F():
  pass

if __name__ == "__main__":
  # A() 
  # B()
  # C()
  D()
  E()
  F()
//  [python]
n = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
ans = A[0]
if n%2 == 0:
    ans += sum(A[1:n//2])*2
else:
    ans += sum(A[1:n//2])*2 + A[n//2]

print(ans)
//  [python]
N = int(input())
A = list(map(int, input().split()))

A.sort(reverse=True)
print(A[0] + sum(A[1:(N - 2) // 2 + 1]) * 2 + A[(N - 2) // 2 + 1] * (N % 2))
//  [python]
n = int(input())
a = sorted(map(int, input().split()), reverse=True)

ans, que = 0, [a[0]]
for i in enumerate(a[1:]):
    ans += que[i]
    que += [i, i]
print(ans)
//  [python]
n = int(input())

a = list(map(int, input().split()))
a.sort(reverse=True)

ans = a[0]

cnt = 1
i = 1
while cnt < n-1:
    cnt += 2
    ans += a[i] * 2
    i += 1

if cnt == n:
    ans -= a[i]

print(ans)
//  [python]
n = int(input())
p = list(map(int, input().split()))
p.sort()
s = sum(p)
s -= p[0]
print(s)
//  [java]
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        long ans = 0;
        for (int i = 0; i < a.length; i++) {
            a[i] = sc.nextInt();
        }
        Arrays.sort(a);
        for (int i = 1; i < n; i++) {
            ans += a[i];
        }
        System.out.println(ans);
    }
}
//  [java]
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Deque;
import java.util.ArrayDeque;

/**
 * Built using CHelper plug-in Actual solution is at the top
 */
public class Main {
    
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DChatInACircle solver = new DChatInACircle();
        solver.solve(1, in, out);
        out.close();
    }
    
    static class DChatInACircle {
        
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            // 入力
            int n = Integer.parseInt(in.next());
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = Integer.parseInt(in.next());
            }
            
            reverse(a);
            long ans = a[0];
            
            Deque<Integer> dq = new ArrayDeque<>();
            dq.offerLast(a[0]);
            dq.offerLast(a[1]);
//        debug(a);
            for (int i = 2; i < n; i++) {
//            debug(dq);
                ans += dq.pollFirst();
                for (int j = 0; j < 2; j++) {
                    dq.offerLast(a[i]);
                }
            }
            // 出力
            out.println(ans);
        }
        
        private void reverse(int[] array) {
            for (int i = 0; i < array.length / 2; i++) {
                swap(array, i, array.length - i - 1);
            }
        }
        
        private void swap(int[] array, int i, int j) {
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }
        
    }
}
//  [java]
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Deque;
import java.util.ArrayDeque;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DChatInACircle solver = new DChatInACircle();
        solver.solve(1, in, out);
        out.close();
    }

    static class DChatInACircle {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            // 入力
            int n = Integer.parseInt(in.next());
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = Integer.parseInt(in.next());
            }

            reverse(a);
            long ans = a[0];

            Deque<Integer> dq = new ArrayDeque<>();
            dq.offerLast(a[0]);
            dq.offerLast(a[1]);
            //debug(a);
            for (int i = 2; i < n; i++) {
                //debug(dq);
                ans += dq.pollFirst();
                dq.offerLast(a[0]);
                dq.offerLast(a[1]);
            }
            // 出力
            out.println(ans);
        }

        private void reverse(int[] array) {
            for (int i = 0; i < array.length / 2; i++) swap(array, i, array.length - i - 1);
        }

        private void swap(int[] array, int i, int j) {
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }

    }
}
//  [cpp]
#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	if ((tmp & ma0) ^ ma0) {
		int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
		tmp = tmp << dig & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += (72 - dig >> 3);
	}
	else {
		tmp = tmp & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += 8;
		if ((ct = *ci++) >= '0') {
			tmp = tmp * 10 + ct - '0';
			if (*ci++ == '0') {
				tmp = tmp * 10;
				ci++;
			}
		}
	}
	return tmp;
}

int A[200000];
int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();
	int saidai = 1;
	rep(i, N) {
		A[i] = getint();
		if (A[i] > saidai) saidai = A[i];
	}
	nth_element(A, A + N / 2, A + N);

	ll kotae = 0;
	for (int i = N / 2; i < N; i++) kotae += A[i];

	printf("%lld\n", kotae * 2 - saidai - N % 2 * A[N / 2]);

	Would you please return 0;
}
//  [cpp]
// Contest: AtCoder Beginner Contest 173 (https://atcoder.jp/contests/abc173)
// Problem: D: Chat in a Circle (https://atcoder.jp/contests/abc173/tasks/abc173_d)


// region boilerplate
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cmath>
#include <chrono>
#include <cstdint>
#include <deque>
#include <exception>
#include <forward_list>
#include <functional>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#if __cplusplus >= 201703L
#   include <optional>
#   include <string_view>
#   include <variant>
#endif

using namespace std;

#if __cplusplus >= 201703L
#   define all(a)      begin(a),end(a)
#   define sz(x)       ((int)size(x))
#else
#   define all(a)      (a).begin(),(a).end()
#   define sz(x)       ((int)(x).size())
#endif

#define rep(a, b)      for(int a = 0; a < (b); ++a)
#define reps(a, b, c)  for(int a = (b); a < (c); ++a)
#define trav(a, b)     for(auto& a : b)

using ll = long long;
using ld = long double;
using u64 = uint64_t;
using u32 = uint32_t;

using pi = pair<int, int>;
using pl = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using vvi = vector<vi>;
using vpi = vector<pi>;

#if __cplusplus >= 201703L
#   define MAYBE_UNUSED [[maybe_unused]]
#else
#   define MAYBE_UNUSED
#endif

MAYBE_UNUSED static constexpr int INF = (int)1e9 + 5;
MAYBE_UNUSED static constexpr ll INFL = (ll)1e18 + 5;
MAYBE_UNUSED static mt19937 rng((u32)chrono::duration_cast<chrono::nanoseconds>(chrono::high_resolution_clock::now().time_since_epoch()).count());
//endregion

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n; cin >> n;
    vi a(n);
    trav(ai, a) cin >> ai;
    sort(all(a));

    cout << accumulate(begin(a) + 1, end(a), 0ll) << '\n';

    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define maxn 200005
int main()
{
	int n;
	cin>>n;
	int a[maxn];
	long long sum=0;
	int ans=0x3f3f3f3f;
	for(int i=0;i<n;i++)
	{
	cin>>a[i];
	sum+=a[i];
	if(a[i]<ans)ans=a[i];	
	}
	sum-=ans;
	cout<<sum<<endl;
 }
//  [cpp]
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<queue>
using namespace std;

typedef long long ll;
typedef pair<int,int> pii;

int main(){
    int n;
    cin >> n;
    vector<int> v(n);
    for(int i = 0; i < n; i++)  cin >> v[i];
    sort(v.rbegin(), v.rend());
    priority_queue<pii> pq;
    pq.push({v[1], v[0]});
    pq.push({v[1], v[0]});
    ll ans = v[0];
    for(int i = 2; i < n; i++){
        pii p = pq.top();   pq.pop();
        ans += p.first;
        p.second = p.first;
        p.first = v[i];
        pq.push(p);
    }
    cout << ans << endl;
    return 0;
}
//  [c]
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#define getchar getchar_unlocked
#define putchar putchar_unlocked
int32_t nextint(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); bool s=false; if(c=='-'){s=true;c=getchar();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); int s=0; if(c=='-'){s=1;c=getchar();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }

void rsorta_d32(void *base, const int count, const int size, const int index){
	typedef int32_t rsort_t;
	rsort_t (*a)[size] = (rsort_t(*)[size])base;
	rsort_t (*b)[size] = (rsort_t(*)[size])malloc(count*size*sizeof(rsort_t));
	int c[0x100];
	for(int k=0; k<4; k++){
		memset(c, 0, sizeof(c)); for(int i=0; i<count; i++){ c[(a[i][index]>>(k<<3))&0xFF]++; } for(int i=1; i<0x100; i++) c[i]+=c[i-1]; for(int i=count-1; i>=0; i--){ int to=--c[(a[i][index]>>(k<<3))&0xFF]; for(int j=0; j<size; j++){ b[to][j]=a[i][j]; } }{rsort_t(*t)[size]=a; a=b; b=t;}
	}
	free(b);
}

int a[200000];
int main(void){
	int n=nextint();
	for(int i=0; i<n; i++){
		a[i]=nextint();
	}
	rsorta_d32(a, n, 1, 0);
	long ans=0;
	for(int i=1; i<n; i++){
		ans+=a[n-1-(i/2)];
	}
	printf("%ld\n", ans);
}
//  [c]
#pragma GCC optimize("Ofast")
#include<stdio.h>
#include<stdlib.h>
int comp(const void * a, const void * b)
{
    if(*(int*)a > *(int*)b) return -1;
    if(*(int*)a < *(int*)b) return 1;
    return 0;
}
int main(void)
{
    long n = 0;
    char c=getchar_unlocked();
    while(c<='9'&&c>='0') {n=(n<<1)+(n<<3)+c-'0'; c=getchar_unlocked();}
    int ary[200000];
    for(int i = 0;i < n;++i) {
        ary[i] = 0;
        c=getchar_unlocked();
        while(c<='9'&&c>='0') {ary[i]=(ary[i]<<1)+(ary[i]<<3)+c-'0'; c=getchar_unlocked();}
    }
    qsort(ary, n, 4, comp);
    long ans = 0;
    for(int i = 0;i < n;++i) {
        ans += ary[i/2];
    }
    printf("%ld", ans - ary[0]);
    return 0;
}
//  [c]
#include <stdio.h>

typedef struct {
	int key, id;
} data;

typedef struct {
	data obj[200001];
	int size;
} max_heap;

void push(data x, max_heap* h)
{
	int i = ++(h->size);
	data tmp;
	h->obj[i] = x;
	while (i > 1) {
		if (h->obj[i].key > h->obj[i>>1].key) {
			tmp = h->obj[i>>1];
			h->obj[i>>1] = h->obj[i];
			h->obj[i] = tmp;
			i >>= 1;
		} else break;
	}
}

data pop(max_heap* h)
{
	int i = 1, j = 2;
	data output = h->obj[1], tmp;
	h->obj[1] = h->obj[(h->size)--];
	while (j <= h->size) {
		if (j < h->size && h->obj[j^1].key > h->obj[j].key) j ^= 1;
		if (h->obj[j].key > h->obj[i].key) {
			tmp = h->obj[j];
			h->obj[j] = h->obj[i];
			h->obj[i] = tmp;
			i = j;
			j = i << 1;
		} else break;
	}
	return output;
}

int main()
{
	int i, N;
	data d;
	max_heap h;
	h.size = 0;
	scanf("%d", &N);
	for (i = 1; i <= N; i++) {
		scanf("%d", &(d.key));
		push(d, &h);
	}

	int count = 1;
	long long ans = pop(&h).key;
	while (count < N - 1) {
		d = pop(&h);
		if (count < N - 2) {
			ans += d.key * 2;
			count += 2;
		} else {
			ans += d.key;
			count++;
		}
	}
	
	printf("%lld\n", ans);
	fflush(stdout);
	return 0;
}
//  [c]
#include<iostream>
#include<algorithm>

using namespace  std;

int main(){
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	int ans = 0;
	sort(a+1,a+1+n);
	int ans = a[n];
	int res = n-1;
	for(int i=n-2/2;i>0;i--) ans += 2*a[res--];
	
	if(t % 2==1) ans += a[res];
	cout<<ans<<endl;
	return 0;
}
//  [c]
#include <stdio.h>

typedef struct {
	int key, id;
} data;

typedef struct {
	data obj[200001];
	int size;
} max_heap;

void push(data x, max_heap* h)
{
	int i = ++(h->size);
	data tmp;
	h->obj[i] = x;
	while (i > 1) {
		if (h->obj[i].key > h->obj[i>>1].key) {
			tmp = h->obj[i>>1];
			h->obj[i>>1] = h->obj[i];
			h->obj[i] = tmp;
			i >>= 1;
		} else break;
	}
}

data pop(max_heap* h)
{
	int i = 1, j = 2;
	data output = h->obj[1], tmp;
	h->obj[1] = h->obj[(h->size)--];
	while (j <= h->size) {
		if (j < h->size && h->obj[j^1].key > h->obj[j].key) j ^= 1;
		if (h->obj[j].key > h->obj[i].key) {
			tmp = h->obj[j];
			h->obj[j] = h->obj[i];
			h->obj[i] = tmp;
			i = j;
			j = i << 1;
		} else break;
	}
	return output;
}

int main()
{
	int i, N;
	data d;
	max_heap h;
	h.size = 0;
	scanf("%d", &N);
	for (i = 1; i <= N; i++) {
		scanf("%d", &(d.key));
		push(d, &h);
	}

	int count = 1;
	long long ans = pop(&h).key;
	while (count < N - 1) {
		d = pop(&h);
		if (count < N - 3) {
			ans += d.key * 2;
			count += 2;
		} else {
			ans += d.key;
			count++;
		}
	}
	
	printf("%lld\n", ans);
	fflush(stdout);
	return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
typedef long long LL;
#define rep(i,n) for(LL i=0; i<(LL)(n); i++)

//qsort
int compare_int(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}

//比較
int max(int a, int b){
	if (a>b) return a;
	else return b;
}

int min(int a,int b) {
	if(a>b) return b;
	else return a;
}


//main関数
int main(){
	int n;
	int a[200000];
	long long sum = 0;
	long long res = 0;
	scanf("%d", &n);
	for(int i = 0; i < n ; i++){
		scanf("%d", &a[i]);
		sum += a[i];
	}
	qsort(a, n, sizeof(int) , compare_int);
 	
 	printf("%lld" ,sum - a[0]);
	return 0;
}
//  [javascript]
const input = require("fs").readFileSync("/dev/stdin", "utf8")

;(input => {

    const lines = input.split('\n')
    const N = lines[0] - 0
    const A = lines[1].split(" ").map(Number)

    A.sort((a, b) => b - a)

    let com = 0
    for (let i = 1; i < N; i++) {
        com += A[Math.floor(i /  2)]
    }

    console.log(com)

})(input)
//  [javascript]
const main = (input) => {

  input = input.trim().split('\n')
  let n = parseInt(input[0], 10)
  const nums = input[1].split(' ').map(Number).sort((a, b) => b - a)

  let ans = 0
  for (let i=1; i<n; i++) ans += nums[Math.floor(i/2)]

  return console.log(ans)
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
const [n, as] = require('fs').readFileSync('/dev/stdin', 'utf8').split(/\n/)
const length = Number(n) - 1
const arr = as.split(/\s/).map(Number).sort((a, b) => b - a)

let count = 0
let result = 0
for (let i = 0; true; i++) {
  result += arr[i]
  count++
  if (count === length) {
    break
  }
  if (i !== 0) {
    result += arr[i]
    count++
  }
  if (count === length) {
    break
  }
}
console.log(result)
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var A = input[1].split(" ").map(i => parseInt(i));
  A.sort((a,b) => b-a);
  var ans =0;
  var P = new Array(1).fill(A[0]);
  for(var i = 1;i<N;i++){
    ans += P[P.length-1];
    P.pop();
    P.push(A[i]);
    P.push(A[i]);
    P.sort((a,b)=>a-b);
  }

  console.log('%s', ans);
  return ans;
}

function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var A = input[1].split(" ").map(i => parseInt(i));
  A.sort((a,b) => a-b);
  var ans =0;
  var P = new Array(1).fill(A[0]);
  for(var i = 1;i<N;i++){
    ans += P[P.length-1];
    P.pop();
    P.push(A[i]);
    P.push(A[i]);
    P.sort((a,b)=>a-b);
  }

  console.log('%s', ans);
  return ans;
}

function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var A = input[1].split(" ").map(i => parseInt(i));
  A.sort((a,b) => b-a);
  var ans =0;
  var P = new Array(1).fill(A[0]);
  for(var i = 1;i<N;i++){
    ans += P[0];
    P.shift();
    P.push(A[i]);
    P.push(A[i]);
    P.sort((a,b)=>b-a);
  }

  console.log('%s', ans);
  return ans;
}

function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
)

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

var (
	writer  *bufio.Writer
	scanner *bufio.Scanner
)

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func sstring() string {
	scanner.Scan()
	return scanner.Text()
}

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	n := sint64()
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	printf("%d\n", sol(a))
}

func sol(a []int64) int64 {
	if len(a) < 2 {
		return 0
	}
	sort.Slice(a, func(i, j int) bool {
		return a[i] < a[j]
	})
	ans := int64(0)
	count := 0
	p := len(a) - 1
	for count < len(a)-1 {
		ans += a[p]
		count++
		if count%2 == 1 {
			p--
		}
	}
	return ans
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	a, err := strconv.Atoi(sc.Text())
	if err != nil {
		fmt.Println(err)
	}
	return a
}
func scanFloat() float64 {
	sc.Scan()
	a, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		fmt.Println(err)
	}
	return a
}
func scanInt2() (int, int) {
	return scanInt(), scanInt()
}
func scanFloat2() (float64, float64) {
	return scanFloat(), scanFloat()
}
func scanText() string {
	sc.Scan()
	return sc.Text()
}
func scanSlice(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}
func main() {
	sc.Split(bufio.ScanWords)

	N := scanInt()
	Ai := scanSlice(N)

	sort.Ints(Ai)
	fmt.Println(Ai[1:N])

	ans := 0
	for _, v := range Ai[1:N] {
		ans += v
	}
	fmt.Println(ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()

	as := make([]int, n)
	for i := 0; i < n; i++ {
		as[i] = nextInt()
	}

	sort.Slice(as, func(i, j int) bool {
		return as[i] > as[j]
	})

	ans := 0
	max1 := 0
	max2 := 0
	for k, a := range as {
		ans = int(math.Min(float64(max1), float64(max2))) + ans
		if max1 > max2 {
			max1 = a
		} else {
			max2 = a
		}
		if k == 0 {
			max1, max2 = a, a
		}
	}
	fmt.Println(ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

func main() {
	N := ReadInt()
	A := ReadInts(N)
	sort.Ints(A)
	s := 0
	for _, ai := range A[1:] {
		s += ai
	}
	fmt.Println(s)
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}
//  [ruby]
n=gets.to_i
an=gets.split(' ').map(&:to_i)
an.sort!.reverse!
res=an[1...((n+1)/2)].sum+an[0...(n/2)].sum
p res
//  [ruby]
n = gets.to_i
a = gets.split.map!(&:to_i).sort!.reverse!

score = -a[0] + a.shift(n / 2).sum * 2 + (n.odd? ? a.shift : 0)
puts score
//  [ruby]
N = gets.to_i
A = gets.chomp.split.map(&:to_i).sort.reverse
ans = A[0]

(1..(N-2)/2).each do |i|
  ans += A[i]*2
end
if (N-2)%2 == 1
  ans += A[(N-2)/2+1]
end

puts ans
//  [ruby]
n = gets.to_i
arr = gets.split.map(&:to_i).sort_by{|i| -i}

count = n - 2
sum = arr[0]
(2..n).each do |i|
  if count == 0
    puts sum
    return
  elsif count == 1
    puts sum + arr[i]
    return
  end
  
  count -= 2
  sum += 2 * arr[i]
end
//  [ruby]
n = gets.to_i
arr = gets.split.map(&:to_i).sort_by{|i| -i}

count = n - 2
sum = arr[0]
(2..n).each do |i|
  if count == 0
    puts sum
    return
  elsif count == 1
    puts sum + arr[i]
    return
  end
  
  count -= 2
  sum += 2 * arr[-i]
end
//  [ruby]
n = gets.to_i
arr = gets.split.map(&:to_i).sort_by{|i| -i}

count = n - 1
sum = arr[-1]
(2..n).each do |i|
  if count == 0
    puts sum
    return
  elsif count == 1
    puts sum + arr[-i]
    return
  end
  
  count -= 2
  sum += 2 * arr[-i]
end
//  [rust]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}
// D
fn main() {
  let n: i32 = read();

  let s: String = read();
  let mut result: i64 = 0;
  let mut v: Vec<i32> = s.split(" ").map(|s| s.parse().unwrap()).collect();
  v.sort_by(|a, b| b.cmp(a));
  //println!("{:?}", v)
  let mut t = n - 1;
  for i in 0..n {
    let mut lim = 2;
    if i == 0 { lim = 1; }
    for _j in 0..lim {
      if t > 0 {
        result += v[i as usize] as i64;
        t-=1;
      }
    }
  }
  println!("{}", result);
  //println!("{}", calc_comfort(v));
}
//  [rust]
// https://atcoder.jp/contests/abc173/tasks/abc173_d

use proconio::input;

fn main() {
    input! {
        n: usize,
        mut a_s: [u64; n],
    }
    a_s.sort_unstable_by(|a, b| b.cmp(a));
    let mut sum: u64 = a_s[1..n / 2].iter().map(|&a| a * 2).sum();
    sum += a_s[0];
    if n % 2 != 0 {
        sum += a_s[n / 2];
    }
    println!("{}", sum);
}
//  [rust]
use std::io;
use std::io::prelude::*;
use std::io::BufReader;

fn main() {
    let mut lines = BufReader::new(io::stdin()).lines().into_iter();
    let line = lines.next().unwrap().unwrap();
    let n: usize = line.parse().unwrap();
    let m = n + 1 >> 1; // nを2で割って切り上げ
    let mut v: Vec<usize> = lines
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|x| x.parse().unwrap())
        .collect();
    v.sort_unstable_by(|a, b| b.cmp(a));
    let mut ans = v.iter().take(m).sum::<usize>() * 2 - v[0];
    ans -= v[m - 1] * (n & 1);
    println!("{}", ans);
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {
        n: usize,
        mut c: [usize; n],
    }

    c.sort();
    c.reverse();
    let mut edges = vec![0usize];

    let mut ans = 0;
    for i in 0..n {
        ans += match edges.pop() {
            Some(t) => t,
            None => 0,
        };
        if i == 0 {
            edges.push(c[i])
        } else {
            edges.push(c[i]);
            edges.push(c[i]);
        }
    }

    println!("{}", ans);
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {
        n: usize,
        mut c: [usize; n],
    }

    c.sort();
    c.reverse();

    let mut ans = 0;
    for i in 0..n {
        if i == 1 {
            ans += c[0];
        } else if i >= 2 {
            ans += c[i - 1];
        }
    }

    println!("{}", ans);
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {
        n: usize,
        mut c: [usize; n],
    }

    let mut max = 0;
    let mut max_2 = 0;
    for i in 0..n {
        if c[i] >= max {
            max_2 = max;
            max = c[i];
        } else if c[i] > max_2 {
            max_2 = c[i];
        }
    }

    let mut ans = 0;
    for i in 0..n {
        if i == 1 {
            ans += max;
        } else if i >= 2 {
            ans += max_2;
        }
    }

    println!("{}", ans);
}
//  [swift]
//
//  main.swift
//  TestSpace for AtCoder
//
//  Created by Koichi Okai on 2020/06/25.
//  Copyright © 2020 Koichi Okai. All rights reserved.
//

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let N = Int(readLine()!)!
    
    let a = readInts().sorted()
    
    let val = (1..<N).map { a[N-1 - $0/2] }.reduce(0) { $0 + $1 }

    print(val)
}

main()
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}

func readLines() -> [String] {
    return readLine()!.map { String($0) }
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}

///最大公約数を返す
func gcd(_ array: [Int]) -> Int {
    var value = array[0]
    if array.count > 1 {
        for i in 1..<array.count {
            value = gcd(value, array[i])
        }
    }
    return value
}

///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }
    
    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var aryA = readInts()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    aryA.sort(by: >)
    print(aryA)
    var value = aryA[0]
    var ans = 0
    for i in 1..<n {
        if i % 2 == 0 {
            value = aryA[i / 2]
        }
        print(value)
        ans += value
    }
    
    
    print(ans)
}
main()