jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
#![allow(unused_imports)]

use std::cmp;
use std::cmp::{max, min, Ordering};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::stdin;
use std::ops::*;
use std::process::exit;
use std::str::FromStr;

pub const MOD: usize = 1000000007;

fn main() {
    let (sx, sy, tx, ty): (i32, i32, i32, i32) = input_four();
    let dx = tx - sx;
    let dy = ty - sy;

    let mut ans = String::new();
    add(&mut ans, &'R', dx);
    add(&mut ans, &'U', dy);
    add(&mut ans, &'L', dx);
    add(&mut ans, &'D', dy+1);
    add(&mut ans, &'R', dx+1);
    add(&mut ans, &'U', dy+1);
    add(&mut ans, &'L', 1);
    add(&mut ans, &'U', 1);
    add(&mut ans, &'L', dx+1);
    add(&mut ans, &'D', dy+1);
    add(&mut ans, &'R', 1);

    println!("{}", ans);
    // dbg!(ans.len());
}

fn add(s: &mut String, c: &char, n: i32) {
    for i in 0..n {
        s.push(*c);
    }
}

pub fn input<T: FromStr>() -> T {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim().parse().ok().unwrap()
}

pub fn input_vec<T: FromStr>() -> Vec<T> {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|x| x.parse().ok().unwrap())
        .collect::<Vec<_>>()
}

pub fn input_lines<T: FromStr>(l: usize) -> Vec<T> {
    let mut res = Vec::new();
    for _i in 0..l {
        res.push(input());
    }
    res
}

pub fn input_lines_two<T: FromStr, U: FromStr>(l: usize) -> Vec<(T, U)> {
    let mut res = Vec::new();
    for _i in 0..l {
        res.push(input_two());
    }
    res
}

pub fn input_lines_three<T: FromStr, U: FromStr, V: FromStr>(l: usize) -> Vec<(T, U, V)> {
    let mut res = Vec::new();
    for _i in 0..l {
        res.push(input_three());
    }
    res
}

pub fn input_two<T: FromStr, U: FromStr>() -> (T, U) {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let s: Vec<&str> = buf.split_whitespace().collect();
    (
        s[0].parse::<T>().ok().unwrap(),
        s[1].parse::<U>().ok().unwrap(),
    )
}

pub fn input_three<T: FromStr, U: FromStr, V: FromStr>() -> (T, U, V) {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let s: Vec<&str> = buf.split_whitespace().collect();
    (
        s[0].parse::<T>().ok().unwrap(),
        s[1].parse::<U>().ok().unwrap(),
        s[2].parse::<V>().ok().unwrap(),
    )
}

pub fn input_four<T: FromStr, U: FromStr, V: FromStr, W: FromStr>() -> (T, U, V, W) {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let s: Vec<&str> = buf.split_whitespace().collect();
    (
        s[0].parse().ok().unwrap(),
        s[1].parse().ok().unwrap(),
        s[2].parse().ok().unwrap(),
        s[3].parse().ok().unwrap(),
    )
}
//  [rust]
use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

pub fn read_n<T: FromStr>(n: usize) -> Vec<T> {
    read_n_logic::<T>(n, vec![])
}

pub fn read_n_logic<T: FromStr>(n: usize, mut a: Vec<T>) -> Vec<T> {
    match n {
        0 => a,
        _ => {
            a.push(read::<T>());
            read_n_logic(n - 1, a)
        }
    }
}
use std::cmp::{max, min};
use std::collections::HashSet;

fn main() {
    let sx: i64 = read();
    let sy: i64 = read();
    let tx: i64 = read();
    let ty: i64 = read();

    let mut ans: String = String::new();
    let xdist = tx - sx;
    let ydist = ty - sy;

    for _ in 0..xdist {
        ans += "R"
    }

    for _ in sy..ty {
        ans += "U"
    }

    for _ in sx..tx {
        ans += "L"
    }
    for _ in sy..ty {
        ans += "D"
    }
    ans += "D";

    for _ in sx..tx + 1 {
        ans += "R"
    }

    for _ in 0..ydist + 1 {
        ans += "U"
    }
    ans += "LU";
    for _ in 0..xdist + 1 {
        ans += "L"
    }

    for _ in 0..ydist + 1 {
        ans += "D"
    }
    ans += "R";
    println!("{}", ans);
}
//  [rust]
use std::io::*;
use std::str::FromStr;

//https://qiita.com/tubo28/items/e6076e9040da57368845
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let sx: i32 = read();
    let sy: i32 = read();
    let tx: i32 = read();
    let ty: i32 = read();

    //右からsへ
    let mut ans:String = "".to_string();
    for _i in 0..(tx - sx) {
        ans += "R";
    }
    for _i in 0..(ty - sy) {
        ans += "U";
    }

    //左からtへ
    for _i in 0..(tx - sx) {
        ans += "L";
    }
    for _i in 0..(ty - sy) {
        ans += "D";
    }

    //左からsへ
    ans += "L";
    for _i in 0..(ty - sy + 1) {
        ans += "U";
    }
    for _i in 0..(tx - sx + 1) {
        ans += "R";
    }
    ans += "D";
    
    //右からtへ
    ans += "R";
    for _i in 0..(ty - sy + 1) {
        ans += "D";
    }
    for _i in 0..(tx - sx + 1) {
        ans += "L";
    }
    ans += "U";

    println!("{}", ans);

}
//  [rust]
use proconio::input;

fn main() {
    input! {
        sx: i32,
        sy: i32,
        tx: i32,
        ty: i32,
    }

    // 行き
    (0..(ty - sy)).for_each(|_| print!("U"));
    (0..(tx - sx)).for_each(|_| print!("R"));
    // 帰り
    print!("U");
    (0..(tx - sx + 1)).for_each(|_| print!("L"));
    (0..(ty + 1 - sy)).for_each(|_| print!("D"));
    print!("R");

    // 行き
    print!("D");
    (0..(ty - sy + 1)).for_each(|_| print!("R"));
    (0..(tx + 1 - sx)).for_each(|_| print!("U"));
    print!("L");
    // 帰り
    (0..(tx - sx)).for_each(|_| print!("D"));
    (0..(ty - sy)).for_each(|_| print!("L"));

    println!("");
}
//  [rust]
use proconio::input;

fn main() {
    input! {
        sx: i32,
        sy: i32,
        tx: i32,
        ty: i32,
    }

    let start = [(sx, sy + 1), (tx, ty + 1), (sx, sy - 1), (tx, ty - 1)];
    let goal  = [(tx - 1, ty), (sx - 1, sy), (tx + 1, ty), (sx + 1, sy)];

    for i in 0..4 {
        // 進行方向の+-を制御する、行きは+1, 帰りは-1
        let m = if i == 2 || i == 0 { 1 } else { -1 };

        match i {
            0..=1 => print!("U"),
            2..=3 => print!("D"),
            _ => unreachable!(),
        }


        let y = goal[i].1 - start[i].1;
        let x = goal[i].0 - start[i].0;

        for _ in 0..x.abs() {
            if m > 0 { print!("R"); } else { print!("L"); }
        }
        for _ in 0..y.abs() {
            if m > 0 { print!("U"); } else { print!("D"); }
        }

        match i {
            0..=1 => print!("R"),
            2..=3 => print!("L"),
            _ => unreachable!(),
        }
    }
    println!("");
}
//  [swift]
let input = readLine()!.characters.split(" ").map{Int(String($0))!}
let (sx, sy, tx, ty) = (input[0], input[1], input[2], input[3])
let (dx, dy) = (tx-sx, ty-sy)
print("D", terminator: "")
(0...dx).forEach{_ in print("R", terminator: "")}
(0...dy).forEach{_ in print("U", terminator: "")}
(0...dx).forEach{_ in print("L", terminator: "")}
(0..<dy).forEach{_ in print("D", terminator: "")}
print("L", terminator: "")
(0...dy).forEach{_ in print("U", terminator: "")}
(0...dx).forEach{_ in print("R", terminator: "")}
(0...dy).forEach{_ in print("D", terminator: "")}
(0..<dx).forEach{_ in print("L", terminator: "")}
//  [swift]
// Back and Forth

func main() {
    let values = readLine()!.split(separator: " ").map{Int($0)!}
    let sx = values[0]
    let sy = values[1]
    let tx = values[2]
    let ty = values[3]

    let dx = tx - sx
    let dy = ty - sy
    var s = ""

    // 最初のゴールまで
    s += String(repeating: "R", count: dx)
    s += String(repeating: "U", count: dy)

    // 戻ってくる
    s += String(repeating: "L", count: dx)
    s += String(repeating: "D", count: dy)

    // 別ルートでゴールへ
    s += "D"
    s += String(repeating: "R", count: dx+1)
    s += String(repeating: "U", count: dy+1)
    s += "L"

    // 別ルートで戻ってくる
    s += "U"
    s += String(repeating: "L", count: dx+1)
    s += String(repeating: "D", count: dy+1)
    s += "R"

    print(s)
}

main()
//  [swift]
// Back and Forth

func main() {
    let values = readLine()!.split(separator: " ").map{Int($0)!}
    let sx = values[0]
    let sy = values[1]
    let tx = values[2]
    let ty = values[3]

    let dx = tx - sx
    let dy = ty - sy
    var s = ""

    // 最初のゴールまで
    s += String(repeating: "R", count: dx)
    s += String(repeating: "U", count: dy)

    // 戻ってくる
    s += String(repeating: "L", count: dx)
    s += String(repeating: "D", count: dx)

    // 別ルートでゴールへ
    s += "D"
    s += String(repeating: "R", count: dx+1)
    s += String(repeating: "U", count: dy+1)
    s += "L"

    // 別ルートで戻ってくる
    s += "U"
    s += String(repeating: "L", count: dx+1)
    s += String(repeating: "D", count: dy+1)
    s += "R"

    print(s)
}

main()
//  [swift]
import Foundation

let a = readLine()!
let b = a.components(separatedBy: " ")

let sx = Int(b[0])!
let sy = Int(b[1])!
let tx = Int(b[2])!
let ty = Int(b[3])! //ok


for i in 0..<ty-sy{
    
    print("U", terminator:"")

}


for i in 0..<tx-sx{
    
    print("R", terminator:"")

}


for i in 0..<ty-sy{
    
    print("D", terminator:"")

}


for i in 0..<tx-sx+1{
    
    print("L", terminator:"")

}


for i in 0..<ty-sy+1{
    
    print("U", terminator:"")

}


for i in 0..<tx-sx+1{
    
    print("R", terminator:"")

}


print("D",terminator:"")
print("R",terminator:"")


for i in 0..<ty-sy+1{
    
    print("D", terminator:"")

}

for i in 0..<tx-sx+1{
    
    print("L", terminator:"")

}


print("U")
//  [typescript]
const stdin = require("fs").readFileSync("/dev/stdin", "utf8");
const [sx, sy, tx, ty] = stdin.split(" ").map(Number);
const diff = (x1, x2) => x2 - x1;
const dx = diff(sx, tx);
const dy = diff(sy, ty);
let result = "U".repeat(dy) + "R".repeat(dx);
result += "D".repeat(dy) + "L".repeat(dx);
result += "L".repeat(1) + "U".repeat(dy + 1) + "R".repeat(dx + 1) + "D".repeat(1);
result += "R".repeat(1) + "D".repeat(dy + 1) + "L".repeat(dx + 1) + "U".repeat(1);
console.log(result);
//  [typescript]
import { readFileSync } from 'fs'

const main = () => readFileSync('/dev/stdin', 'utf8').slice(0, -1)

const [k, s] = main()
  .split(' ')
  .map(x => +x)
let cnt = 0
for (let i = 0; i <= k; i++) {
  for (let j = 0; j <= k; j++) {
    if (0 <= s - i - j && s - i - j <= k) cnt++
  }
}
console.log(cnt)
//  [python]
def main():
    import sys
    input = sys.stdin.readline
    n,m = map(int,input().split())
    A = list(map(int,input().split()))
    BC = [list(map(int,input().split())) for _ in range(m)]

    BC = sorted(BC,key=lambda x:(x[1]),reverse=True)
    append_list = []
    for b,c in BC:
        if len(append_list)>=n:
            break
        append_list+=[c]*b
    A+=append_list
    A.sort(reverse=True)
    print(sum(A[:n]))

if __name__=='__main__':
    main()
//  [python]
from collections import Counter
N,M = map(int,input().split())
A = Counter(list(map(int,input().split())))
for i in range(M):
    b,c = map(int,input().split())
    if c in A.keys():
        A[c] += b
    else:
        A[c] = b
A = sorted(A.items(),reverse=True)
check = N
ans = 0
for i in A:
    if i[1]<check:
        check -= i[1]
        ans += (i[0] * i[1])
    else:
        ans += i[1] * check
        check = 0
print(ans)
//  [python]
from collections import Counter
N,M = map(int,input().split())
A = Counter(list(map(int,input().split())))
for i in range(M):
    b,c = map(int,input().split())
    if c in A:
        A[c] += b
    else:
        A[c] = b
A = sorted(Counter(A).items(),reverse=True)
check = N
ans = 0
for i in A:
    if i[1]<check:
        check -= i[1]
        ans += (i[0] * i[1])
    else:
        ans += i[1] * check
print(ans)
//  [python]
from collections import Counter
N,M = map(int,input().split())
A = Counter(list(map(int,input().split())))
for i in range(M):
    b,c = map(int,input().split())
    if c in A.keys():
        A[c] += b
    else:
        A[c] = b
A = sorted(A.items(),reverse=True)
check = N
ans = 0
for i in A:
    if i[1]<check:
        check -= i[1]
        ans += (i[0] * i[1])
    else:
        ans += i[1] * check
print(ans)
//  [java]
import java.io.*;
import java.util.*;
import static java.lang.System.out;

public class Main {
    static MyReader in = new MyReader();

    public static void main(String[] args) {
        int N = in.i();
        int M = in.i();
        long[] d = new long[N + M];
        for (int i = 0; i < N; i++) {
            d[i] = (in.l() << 17) + 1;
        }
        for (int i = N; i < d.length; i++) {
            d[i] = in.i() + (in.l() << 17);
        }
        Arrays.sort(d);
        long ans = 0;
        for (int i = N + M - 1, j = N - 1; i >= 0 && j >= 0; i--) {
            long b = d[i] & (1 << 17) - 1;
            long c = d[i] >> 17;
            b = Math.min(j + 1, b);
            ans += b * c;
            j -= b;
        }
        out.println(ans);
    }
}

class MyReader extends BufferedReader {
    char[] cbuf = new char[1024];
    int head = 0;
    int tail = 0;

    MyReader() {
        super(new InputStreamReader(System.in));
    }

    char next() {
        if (head == tail) {
            try {
                tail = read(cbuf, 0, cbuf.length);
            } catch (IOException e) {}
            head = 0;
        }
        return cbuf[head++];
    }

    void back() {
        head--;
    }

    boolean minus() {
        boolean minus;
        while (true) {
            char c = next();
            if (c != ' ' && c != '\n' && c != '\r') {
                if (!(minus = c == '-')) back();
                return minus;
            }
        }
    }

    void skip() {
        while (true) {
            char c = next();
            if (c != ' ' && c != '\n' && c != '\r') {
                back();
                break;
            }
        }
    }

    char[] s(final int N) {
        skip();
        char[] s = new char[N];
        for (int i = 0; i < s.length; i++) {
            s[i] = next();
        }
        return s;
    }

    String s() {
        try {
            return readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    int i() {
        boolean minus = minus();
        int n = 0;
        while (true) {
            int k = next() - '0';
            if (k < 0 || 9 < k) break;
            n = 10 * n + k;
        }
        return minus ? -n : n;
    }

    int[] ii(final int N) {
        int[] a = new int[N];
        for (int j = 0; j < a.length; j++) a[j] = i();
        return a;
    }

    long l() {
        boolean minus = minus();
        long n = 0;
        while (true) {
            int k = next() - '0';
            if (k < 0 || 9 < k) break;
            n = 10 * n + k;
        }
        return minus ? -n : n;
    }
}
//  [java]
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner scanner  = new Scanner(System.in);
		scanner.nextInt();
		final var m = scanner.nextInt();
		scanner.nextLine();
		final String line = scanner.nextLine();

		var str = Arrays.asList(line.split(" "));
		LinkedList<Integer> a = new LinkedList<Integer>();
		a = str.stream()
				.map(Integer::parseInt)
				.collect(Collectors.toCollection(LinkedList::new));
		Collections.sort(a);
		Collections.reverse(a);
		Map<Integer,Integer> map = new HashMap<Integer, Integer>();
		for(var aa = 0; aa < a.size(); aa++) {
			map.put(a.get(aa), aa);
		}
		for(var i = 0; i < m; i++) {
			var b = scanner.nextInt();
			var c = scanner.nextInt();
			var cnt = 0;
			int size = a.size();
			int start = (map.containsKey(c))? map.get(c) : 0;
			for (var aa = start; aa < size; aa++) {
				if(cnt == b) break;
				int current = a.get(aa);
				if(current < c) {
					a.add(aa, c);
					a.remove(size);
					cnt++;
				}
			}

		}
		var sum = 0l;
		for (var aa : a){
			sum += aa;
		}
		System.out.println(sum);
		scanner.close();
	}

}
//  [java]
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner scanner  = new Scanner(System.in);
//		final var n = scanner.nextInt();
		scanner.nextInt();
		final var m = scanner.nextInt();
		scanner.nextLine();
		final String line = scanner.nextLine();

		var str = Arrays.asList(line.split(" "));
//		str.stream().forEach(r -> System.out.println(r));
		LinkedList<Integer> a = new LinkedList<Integer>();
		a = str.stream()
				.map(Integer::parseInt)
				.collect(Collectors.toCollection(LinkedList::new));
//		long sum = a.stream()
//				.mapToInt(Integer::valueOf)
//				.sum();

//		a.stream().forEach(r -> System.out.println(r));
//		System.out.println();
		Collections.sort(a);
		Collections.reverse(a);
		for(var i = 0; i < m; i++) {
			var b = scanner.nextInt();
			var c = scanner.nextInt();
//			for(var j = 0; j < b; j++) {
//				if (a.get(j) <= c) break;
//				a.set(j, Math.max(a.get(j), c));
//			}
			var cnt = 0;
			int size = a.size();
			for (var aa = 0; aa < size; aa++) {
				if(cnt == b) break;
				int current = a.get(aa);
				if(current < c) {
					a.add(aa, c);
					a.remove(size);
					cnt++;
				}
			}
//			a.stream().forEach(r -> System.out.println(r));
//			System.out.println("-----" + i);

		}
//		System.out.println(sum);
//		a.stream().forEach(r -> System.out.println(r));
//		sum = Math.max(sum, a.stream().mapToInt(Integer::valueOf).sum());
		var sum = 0l;
		for (var aa : a){
			sum += aa;
		}
		System.out.println(sum);
		scanner.close();
	}

}
//  [java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner scanner  = new Scanner(System.in);
//		final var n = scanner.nextInt();
		scanner.nextInt();
		final var m = scanner.nextInt();
		scanner.nextLine();
		final String line = scanner.nextLine();

		var str = Arrays.asList(line.split(" "));
//		str.stream().forEach(r -> System.out.println(r));
		List<Integer> a = new ArrayList<Integer>();
		a = str.stream()
				.map(Integer::parseInt)
				.collect(Collectors.toList());
//		long sum = a.stream()
//				.mapToInt(Integer::valueOf)
//				.sum();

//		a.stream().forEach(r -> System.out.println(r));
//		System.out.println();
		for(var i = 0; i < m; i++) {
			Collections.sort(a);
			var b = scanner.nextInt();
			var c = scanner.nextInt();
			for(var j = 0; j < b; j++) {
				if (a.get(j) >= c) break;
				a.set(j, Math.max(a.get(j), c));
			}
//			a.stream().forEach(r -> System.out.println(r));
//			System.out.println("-----" + i);

		}
//		System.out.println(sum);
//		a.stream().forEach(r -> System.out.println(r));
//		sum = Math.max(sum, a.stream().mapToInt(Integer::valueOf).sum());
		var sum = 0l;
		for (var aa : a){
			sum += aa;
		}
		System.out.println(sum);
		scanner.close();
	}

}
//  [cpp]
#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#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;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int tmp[100001], tmp2[100001];
void pakuri_sort(int N, int A[]) {
	const int b = 8;
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}

void pakuripair_sort(int N, int A[], int B[]) {
	const int b = 8;
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) {
			tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
			tmp2[kazu[A[i] >> k * b & ((1 << b) - 1)]] = B[i];
		}
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) {
			A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
			B[kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp2[i];
		}
	}
}

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


	int N = getint(), M = getint();

	int A[100000];
	rep(i, N) A[i] = getint();
	pakuri_sort(N, A);

	int B[100000], C[100000];
	rep(i, M) {
		B[i] = getint();
		C[i] = getint();
	}
	pakuripair_sort(M, C, B);

	ll kotae = 0;
	int kazu = 0;
	for (int i = M - 1; i >= 0; i--) {
		int makkusu = min(B[i], N - kazu);
		rep(j, makkusu) kotae += max(A[kazu++], C[i]);
	}

	for (int i = kazu; i < N; i++) kotae += A[i];

	printf("%lld", kotae);

	Would you please return 0;
}
//  [cpp]
//#include<bits/stdc++.h>
#include<cstdio>
#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 Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

void pakuri_sort(int N, int A[]) {
	const int b = 8;
	int tmp[100001];
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}

void pakuripair_sort(int N, int A[], int B[]) {
	const int b = 8;
	int tmp[100001], tmp2[100001];
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) {
			tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
			tmp2[kazu[A[i] >> k * b & ((1 << b) - 1)]] = B[i];
		}
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) {
			A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
			B[kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp2[i];
		}
	}
}

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


	int N = getint(), M = getint();

	int A[100000];
	rep(i, N) A[i] = getint();
	pakuri_sort(N, A);

	int B[100000],C[100000];
	rep(i, M) {
		B[i] = getint();
		C[i] = getint();
	}
	pakuripair_sort(M, C, B);

	ll kotae = 0;
	int kazu = 0;
	for (int i = M - 1; i >= 0; i--) {
		rep(j, B[i]) {
			if (kazu >= N) break;
			kotae += max(A[kazu], C[i]);
			kazu++;
		}
	}

	for (int i = kazu; i < N; i++) kotae += A[i];

	printf("%lld", kotae);

	Would you please return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve()
{
    int n, m; cin >> n >> m;
    vector<ll> v(n);
    ll ans = 0;
    for (int i = 0; i < n; ++i) {
        cin >> v[i];
        ans += v[i];
    }
    sort(v.begin(), v.end());
    map<ll, ll, greater<ll>> vals;
    for (int i = 0; i < m; ++i) {
        ll b, c; cin >> b >> c;
        vals[c] += b;
    }
    int i = 0;
    for (auto it = vals.begin(); it != vals.end(); ++it) {
        ll val = it->first;
        ll count = it->second;
        while (v[i] < val && count-- > 0) {
            ans += val - v[i++];
        }
    }
    cout << ans << '\n';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve()
{
    int n, m; cin >> n >> m;
    vector<ll> v(n);
    ll ans = 0;
    for (int i = 0; i < n; ++i) {
        cin >> v[i];
        ans += v[i];
    }
    sort(v.begin(), v.end());
    map<ll, ll, greater<ll>> vals;
    for (int i = 0; i < m; ++i) {
        int b, c; cin >> b >> c;
        vals[c] += b;
    }
    int i = 0;
    for (auto it = vals.begin(); it != vals.end(); ++it) {
        int val = it->first;
        int count = it->second;
        while (v[i] < val && count-- > 0) {
            ans += val - v[i++];
        }
    }
    cout << ans << '\n';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve()
{
    int n, m; cin >> n >> m;
    priority_queue<ll, vector<ll>, greater<ll>> q;
    for (int i = 0; i < n; ++i) {
        ll val; cin >> val;
        q.push(val);
    }
    for (int i = 0; i < m; ++i) {
        int b, c; cin >> b >> c;
        while (b-- > 0 && q.top() < c) {
            q.pop();
            q.push(c);
        }
    }
    ll ans = 0;
    while (!q.empty()) {
        ans += q.top();
        q.pop();
    }
    cout << ans << '\n';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}
//  [c]
// AtCoder ABC127: D - Integer Cards
// 2019.9.8 bal4u

#include <stdio.h>
#include <stdlib.h>

typedef long long ll;

//// 高速入力
#if 1
int getchar_unlocked(void);
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif

int in() {   // 非負整数の入力
	int n = 0, c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

typedef struct { int b, c; } T;
T t[100005];
int N, M;
int A[100005];

// a[i]>=key という条件を満たす最小のi
int lower_bound(int x) {
  int m, l = 0, r = N;
  while (l+1 < r) {
    m = (l+r) >> 1;
    if (A[m] < x) l = m; else r = m;
  }
  return A[l] < x? r: l;
}

int cmp_a(const void *u, const void *v) { return *(int *)u - *(int *)v; }
int cmp_t(const void *u, const void *v) {
	int t;
	if (t = ((T *)v)->c - ((T *)u)->c) return t;
	return ((T *)v)->b - ((T *)u)->b;
}

inline static ll sum(int l, int r) { ll s = 0; while (l < r) s += A[l++]; return s; }

int main()
{
	int i, w, pos; ll ans;
	
	N = in(), M = in();
	for (i = 0; i < N; i++) A[i] = in();
	qsort(A, N, sizeof(int), cmp_a);
	for (i = 0; i < M; i++) t[i].b = in(), t[i].c = in();
	qsort(t, M, sizeof(T), cmp_t);
	
	w = 0;
	for (i = 0; i < M && w < N; i++) {
		pos = lower_bound(t[i].c) - w;
		if (pos <= 0) break;
		if (t[i].b > pos) t[i].b = pos;
		w += t[i].b;
	}
	
	ans = 0, pos = 0;
	while (--i >= 0) ans += (ll)t[i].b * t[i].c, pos += t[i].b;
	ans += sum(pos, N);
	printf("%lld\n", ans);
	return 0;
}
//  [c]
#include <stdio.h>

void quicksort(int array[], int left, int right) {
    int l = left;
    int r = right;
    int pivot = array[(left + right) / 2]; // 中央からピボットを選択
    int buf;

    while (1) {
        while (array[l] < pivot) l++;
        while (array[r] > pivot) r--;

        if (l > r) break;

        // pivotより小さい値を左、大きい値を右に入れ替え
        buf = array[l];
        array[l] = array[r];
        array[r] = buf;

        l++, r--;
    };

    // pivotより小さい領域と大きい領域をそれぞれ再帰的にソート
    if (left < r)  quicksort(array, left, r);
    if (l < right) quicksort(array, l, right);
}

void quicksort2(int array[],int array2[], int left, int right) {
    int l = left;
    int r = right;
    int pivot = array[(left + right) / 2]; // 中央からピボットを選択
    int buf;

    while (1) {
        while (array[l] < pivot) l++;
        while (array[r] > pivot) r--;

        if (l > r) break;

        // pivotより小さい値を左、大きい値を右に入れ替え
        buf = array[l];
        array[l] = array[r];
        array[r] = buf;
        buf = array2[l];
        array2[l] = array2[r];
        array2[r] = buf;

        l++, r--;
    };

    // pivotより小さい領域と大きい領域をそれぞれ再帰的にソート
    if (left < r)  quicksort2(array,array2, left, r);
    if (l < right) quicksort2(array,array2, l, right);
}


int main(){
  int n,m;
  scanf("%d %d",&n,&m);
  int a[100000],b[100000],c[100000];
  for(int i=0;i<n;i++){
    scanf("%d",&a[i]);
  }
  for(int i=0;i<m;i++){
    scanf("%d %d",&b[i],&c[i]);
  }
  quicksort(a,0,n-1);
  quicksort2(c,b,0,m-1);
  int i=0;
  for(int j=m-1;j>=0;j--){
    for(int k=0;k<b[j];k++) {
      if(a[i]>c[j]) break;
      if(i>=n)goto res;
      a[i++]=c[j];
    }
  }
  long long sum=0;
  res:

  for(int j=0;j<n;j++) sum += a[j];
  printf("%lld",sum);
  return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
typedef long long LL;
typedef long double Lf;
#define Rep(i,a,n)for(int i=(int)(a);i<(int)(n);i++)
#define rep(i,n)Rep(i,0,n)
#define Ma(x,y) ((x)>(y)?(x):(y))
#define mi(x,y) ((x)<(y)?(x):(y))
#define N 11//提出時確認
#define MOD 1000000007
int acs(const void* a, const void* b) { return *(int*)a - *(int*)b; } //1,2,3,4
int des(const void* a, const void* b) { return *(int*)b - *(int*)a; } 
int cmp_char(const void* a, const void* b) { return *(char*)a - *(char*)b; } //a,b,c,d
int cmp_str(const void* a, const void* b) { return strcmp(*(const char**)a, *(const char**)b); } //aaa,aab
//temmie_のsnippet

typedef struct BC { int b; int c; }BC;
int cmp_BC(const void* a, const void* b) { return ((BC*)b)->c - ((BC*)a)->c; }//BCのcの大きい方から

int main() {
	int n,m,x=0,a[N]; LL ans=0; BC q[N];
	scanf("%d%d",&n,&m);
	rep(i,n)scanf("%d",a+i);
	rep(i,m)scanf("%d%d",&q[i].b,&q[i].c);

	qsort(a,n,sizeof(int),acs);//aは小さい方から
	qsort(q,m,sizeof(BC),cmp_BC);//cは大きい方から

	rep(i,m)rep(j,q[i].b){if(q[i].c<=a[x])break;a[x++]=q[i].c;}//書換
	rep(i,n)ans+=(LL)a[i];
	printf("%lld",ans);
	return 0;
}
//  [c]
#include<stdio.h>

int main(void){
    int n,m,b,c,tmp,i,j,s,t,x;
    int changeN;
    long long sam = 0;
    scanf("%d %d",&n,&m);
    int a[n-1];

    for(i = 0; i <= n - 1;i++){
        scanf("%d",&a[i]);
    }
    
    for(i = 1; i <= m; i++){
        quick_sort(a, 0, n-1);
        
        scanf("%d %d",&b,&c);
        for(changeN = 0, j= 0; changeN < b && j <= n -1; j++){
            if(a[j] < c){
                a[j] = c;
                changeN ++;
            }
        }
    }

    for(i =0;i <= n -1; i++){
        sam = sam + a[i];
    }
    printf("%lld\n",sam);
}

void swap (int *x, int *y) {
  int temp;    // 値を一時保存する変数

  temp = *x;
  *x = *y;
  *y = temp;
}

int partition (int array[], int left, int right) {
  int i, j, pivot;
  i = left;
  j = right + 1;
  pivot = left;   // 先頭要素をpivotとする

  do {
    do { i++; } while (array[i] < array[pivot]);
    do { j--; } while (array[pivot] < array[j]);
    // pivotより小さいものを左へ、大きいものを右へ
    if (i < j) { swap(&array[i], &array[j]); }
  } while (i < j);

  swap(&array[pivot], &array[j]);   //pivotを更新

  return j;
}

/* クイックソート */
void quick_sort (int array[], int left, int right) {
  int pivot;

  if (left < right) {
    pivot = partition(array, left, right);
    quick_sort(array, left, pivot-1);   // pivotを境に再帰的にクイックソート
    quick_sort(array, pivot+1, right);
  }
}
//  [c]
#include<stdio.h>

int main(void){
    int n,m,b,c,tmp,i,j,s,t,x;
    int changeN;
    long long sam = 0;
    scanf("%d %d",&n,&m);
    int a[n-1];

    for(i = 0; i <= n - 1;i++){
        scanf("%d",&a[i]);
    }
    
    for(i = 1; i <= m; i++){
        for (s=0; s<= n - 1; ++s) {
            for (t=s+1; t<= n -1; ++t) {
                if (a[s] > a[t]) {
                tmp =  a[s];
                a[s] = a[t];
                a[t] = tmp;
                }
            }
        }
        scanf("%d %d",&b,&c);
        for(changeN = 0, j= 0; changeN < b && j <= n -1; j++){
            if(a[j] < c){
                a[j] = c;
                changeN ++;
            }
        }
    }

    for(i =0;i <= n -1; i++){
        sam = sam + a[i];
    }
    printf("%lld\n",sam);
}
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    tmp0 = input[0].split(" ");
    N = Number(tmp0[0]);
    M = Number(tmp0[1]);
    A = input[1].split(" ").map(str => parseInt(str,10));
    // console.log(A)
    A = A.sort((a, b) => a-b)
    // console.log(A)

    BCdict=[]
    for(var i=1; i<=M;i++){
        tmp = input[i+1].split(" ")
        // tmp[0] // Bi
        // tmp[1] // Ci
        obj = {"value": Number(tmp[1]), "count": Number(tmp[0])}
        BCdict.push(obj)
    }
    // console.log(BCdict)
    BCdict = BCdict.sort((a,b) => b.value - a.value)
    // console.log(BCdict)

    // BCarray = []
    // for(var i=0; i < BCdict.length; i++)
    // {
    //     BCarray = BCarray.concat(Array.apply(null, Array(BCdict[i].count)).map(function(){return BCdict[i].value}))
    // }
    // // console.log(BCarray)

    // for(var i=0; i < BCarray.length; i++)
    // {
    //     if(BCarray[i] > A[i]){
    //         A[i] = BCarray[i]
    //     }else{
    //         break
    //     }
    // }

    dictIndex = 0
    dictCount = 0    
    for(var i=0; i < A.length; i++)
    {
        var value = BCdict[dictIndex].value
        if(value > A[i])
        {
            A[i] = value
            dictCount++
            if(dictCount == BCdict[dictIndex].count){
                dictIndex++
                dictCount=0
                if(dictIndex == BCdict.length){
                    break
                }
            }
        }else{
            break
        }
    }

    
    var ans=0
    for(var i=0; i < A.length; i++)
    {
        ans += A[i]
    }
    console.log(ans)
  }
  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//   Main("3 2\n5 1 4\n2 3\n1 5\n");
//  [javascript]
"use strict";
function I(t,i){this._s=t.split("\n"),this._c=0,this._l=0,this._f=i||Number}I.prototype.a=function(t){var i=this._s[this._l];if(i){var s=i.trim().split(" "),h=s[this._c];return this._c++,s.length===this._c&&(this._c=0,this._l++),t?t(h):this._f(h)}},I.prototype.l=function(t){var i=this._s[this._l];if(i)return this._c=0,this._l++,i.split(" ").map(t||this._f)},module.exports=I;

function main(input) {
  var o = new I(input);

  var n = o.a();
  var m = o.a();
  var a = o.l();

  var arr = [];
  for (var i = 0; i < m; i++) {
    var b = o.a();
    var c = o.a();
    arr.push({b, c});
  }

  a.sort((a, b) => a - b);
  arr.sort((a, b) => a.c - b.c);

  var ans = [];
  while (ans.length < n) {
    var lastA = a[a.length - 1];
    var lastB = 0;
    if (arr.length > 0) {
      lastB = arr[arr.length - 1].c;
    }
    if (lastA >= lastB) {
      // console.log("A", {lastA})
      ans.push(lastA);
      a.pop();
    } else {
      // console.log("B", arr[arr.length - 1]);
      for (var j = 0; j < arr[arr.length - 1].b; j++) {
        ans.push(lastB);
      }
      arr.pop();
    }
  }

  console.log(ans.slice(0, n).reduce((acc, cur) => acc + cur));
}


main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
module.exports=function(r){var t={};function n(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return r[e].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=r,n.c=t,n.d=function(r,t,e){n.o(r,t)||Object.defineProperty(r,t,{enumerable:!0,get:e})},n.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},n.t=function(r,t){if(1&t&&(r=n(r)),8&t)return r;if(4&t&&"object"==typeof r&&r&&r.__esModule)return r;var e=Object.create(null);if(n.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:r}),2&t&&"string"!=typeof r)for(var o in r)n.d(e,o,function(t){return r[t]}.bind(null,o));return e},n.n=function(r){var t=r&&r.__esModule?function(){return r.default}:function(){return r};return n.d(t,"a",t),t},n.o=function(r,t){return Object.prototype.hasOwnProperty.call(r,t)},n.p="",n(n.s=0)}([function(r,t,n){n(1)(n(2).readFileSync("/dev/stdin","UTF-8").split("\n"))},function(r,t){function n(r,t){return function(r){if(Array.isArray(r))return r}(r)||function(r,t){var n=[],e=!0,o=!1,u=void 0;try{for(var i,f=r[Symbol.iterator]();!(e=(i=f.next()).done)&&(n.push(i.value),!t||n.length!==t);e=!0);}catch(r){o=!0,u=r}finally{try{e||null==f.return||f.return()}finally{if(o)throw u}}return n}(r,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}r.exports=function(r){for(var t=n(r[0].split(" ").map(function(r){return Number(r)}),2),e=t[0],o=t[1],u=r[1].split(" ").map(function(r){return Number(r)}),i=[],f=0;f<o;f++){var c=n(r[f+2].split(" ").map(function(r){return Number(r)}),2),l=c[0],a=c[1];i.push({b:l,c:a})}i.sort(function(r,t){return t.c-r.c}),u.sort(function(r,t){return r-t});for(var s=0,p=0;p<o&&!(s>=e||u[s]>=i[p].c);p++)for(lastb=i[p].b;lastb>0&&s<e&&!(u[s]>=i[p].c);)u[s]=i[p].c,s++,lastb--;for(var d=0,b=0;b<e;b++)d+=u[b];console.log(d)}},function(r,t){r.exports=require("fs")}]);
//  [javascript]
"use strict";
    
class PriorityQueue {
  constructor() {
    this.heap = [];
  }

  push(item) {
    let heap = this.heap;
    let i = heap.length++;
    let j;

    while(i) {
      j = Math.floor((i - 1) / 2);
      if(heap[j] <= item) break;
      heap[i] = heap[j]
      i = j;
    }

    heap[i] = item;
  }

  pop() {
    let heap = this.heap;
    let top = heap[0];
    let popped = heap.pop();

    let i = 0;
    let k = Math.floor(heap.length / 2);
    let j;

    while(i < k) {
      j = (i * 2) + 1;
      if(heap[j+1] < heap[j]) ++j;

      if(popped <= heap[j]) break;

      heap[i] = heap[j];

      i = j;
    }

    if(heap.length) {
      heap[i] = popped;
    }

    return top;
  }

  size() {
    return this.heap.length;
  }

  top() {
    return this.heap[0];
  }
}

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);
    
    const A = arg[1].split(" ").map(n=>parseInt(n));
    const B = arg.slice(2, M + 2).map(n=>n.split(" ").map(l=>parseInt(l)));
    
    let pq = new PriorityQueue();
    
    for(let i=0; i<N; i++) {
        pq.push(A[i]);
    }
    
    // console.log(pq.heap)
    
    for(let i=0; i<M; i++) {
        let target = B[i][0];
        let num = B[i][1];
        
        let temp = pq.top();
        
        for(let j=0; j<target; j++) {
            if(num > temp) {
                pq.pop();
                pq.push(num);
            } else {
                break;
            }
        }
    }
    
    console.log(pq.heap.reduce((m,n)=>m+n));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
"use strict";
    
class PriorityQueue {
  constructor() {
    this.heap = [];
  }

  push(item) {
    let heap = this.heap;
    let i = heap.length++;
    let j;

    while(i) {
      j = Math.floor((i - 1) / 2);
      if(heap[j] <= item) break;
      heap[i] = heap[j]
      i = j;
    }

    heap[i] = item;
  }

  pop() {
    let heap = this.heap;
    let top = heap[0];
    let popped = heap.pop();

    let i = 0;
    let k = Math.floor(heap.length / 2);
    let j;

    while(i < k) {
      j = (i * 2) + 1;
      if(heap[j+1] < heap[j]) ++j;

      if(popped <= heap[j]) break;

      heap[i] = heap[j];

      i = j;
    }

    if(heap.length) {
      heap[i] = popped;
    }

    return top;
  }

  size() {
    return this.heap.length;
  }

  top() {
    return this.heap[0];
  }
}

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);
    
    const A = arg[1].split(" ").map(n=>parseInt(n));
    const B = arg.slice(2, M + 2).map(n=>n.split(" ").map(l=>parseInt(l)));
    
    let pq = new PriorityQueue();
    
    for(let i=0; i<N; i++) {
        pq.push(A[i]);
    }
    
    // console.log(pq.heap)
    
    for(let i=0; i<M; i++) {
        let target = B[i][0];
        let num = B[i][1];
        
        let temp = pq.top();
        
        for(let j=0; j<target; j++) {
            if(num > temp) {
                pq.pop();
                pq.push(num);
            }
        }
    }
    
    console.log(pq.heap.reduce((m,n)=>m+n));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

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

const (
	initialBufSize = 1e4
	maxBufSize     = 1e6 + 7
)

var buf []byte = make([]byte, maxBufSize)
var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(buf, maxBufSize)
}

type cards struct {
	B int
	C int
}

type SortByC []cards

func (a SortByC) Len() int           { return len(a) }
func (a SortByC) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a SortByC) Less(i, j int) bool { return a[i].C > a[j].C }

func main() {
	N, M := nextInt(), nextInt()
	An := make([]int, N)
	c := make([]cards, M)
	for i := 0; i < N; i++ {
		An[i] = nextInt()
	}
	for i := 0; i < M; i++ {
		c[i].B = nextInt()
		c[i].C = nextInt()
	}
	sort.Ints(An)
	sort.Sort(SortByC(c))
	var ans, index int
	for i := 0; i < N; i++ {
		if index == len(c) {
			ans += An[i]
		} else {
			ans += MaxOf(An[i], c[index].C)
			c[index].B--
			if c[index].B == 0 {
				index++
			}
		}
	}
	fmt.Println(ans)
}

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

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

func abs(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func pow(p, q int) int {
	res := p
	if q == 0 {
		return 1
	}
	for i := 0; i < q-1; i++ {
		res *= p
	}
	return res
}

func MinOf(vars ...int) int {
	min := vars[0]
	for _, i := range vars {
		if min > i {
			min = i
		}
	}
	return min
}

func MaxOf(vars ...int) int {
	max := vars[0]
	for _, i := range vars {
		if max < i {
			max = i
		}
	}
	return max
}

func gcdof2numbers(a int, b int) int {
	if b == 0 {
		return a
	}
	return gcdof2numbers(b, a%b)
}

func lcmof2numbers(a int, b int) int {
	return a / gcdof2numbers(a, b) * b
}

// マイナスの場合は考慮していない
func fuctorial(a int) int {
	if a == 1 || a == 0 {
		return 1
	} else {
		return fuctorial(a-1) * a
	}
}

func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}

// 素因数分解したmapを返す
func primeFuctorize(n int) map[int]int {
	pf := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			pf[i]++
			n /= i
		}
	}
	if n != 1 {
		pf[n]++
	}
	return pf
}

// ここから拝借
// https://shoman.hatenablog.com/entry/2020/02/25/185456
// Stackは[]intのエイリアス
type Stack []int

// Push adds an element
func (s *Stack) Push(v int) {
	*s = append(*s, v)
}

// Pop removes the top element and return it
func (s *Stack) Pop() (int, error) {
	if s.Empty() {
		return 0, fmt.Errorf("stack is empty")
	}

	v := (*s)[len(*s)-1]
	*s = (*s)[:len(*s)-1]
	return v, nil
}

// Peek returns the top value
func (s *Stack) Peek() (int, error) {
	if s.Empty() {
		return 0, fmt.Errorf("stack is empty")
	}

	return (*s)[len(*s)-1], nil
}

// Size returns the length of stack
func (s *Stack) Size() int {
	return len(*s)
}

// Empty returns true when stack is empty
func (s *Stack) Empty() bool {
	return s.Size() == 0
}

// NewStack generates stack
func NewStack() *Stack {
	s := new(Stack)
	return s
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	iv, _ := strconv.Atoi(sc.Text())
	return iv
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n, m := scanInt(), scanInt()
	as := make([]int, n)
	sum := 0
	for i := range as {
		as[i] = scanInt()
		sum += as[i]
	}
	sort.Ints(as)

	type card struct{ n, s int }
	cs := make([]card, m)
	for i := range cs {
		cs[i].s, cs[i].n = scanInt(), scanInt()
	}
	sort.Slice(cs, func(i, j int) bool { return cs[i].n > cs[j].n })

	p := 0
lb:
	for _, v := range cs {
		for i := 0; i < v.s; i++ {
			if p >= len(as) || v.n < as[p] {
				break lb
			}
			sum += v.n - as[p]
			p++
		}
	}
	fmt.Println(sum)
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

const inf = 1 << 60

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

type pair struct {
	b, c int
}

type byC []pair

func (p byC) Len() int { return len(p) }

func (p byC) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

func (p byC) Less(i, j int) bool { return p[i].c > p[j].c }

func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	sc.Split(bufio.ScanWords)
	n, m := ri(), ri()

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

	sort.Ints(a)

	q := make([]pair, m) // クエリ
	for i := 0; i < m; i++ {
		q[i] = pair{b: ri(), c: ri()}
	}

	// c で降順にソート
	sort.Sort(byC(q))

	ans := 0
	j := 0 // 限界値は m-1
	for i := 0; i < n; i++ {
		if j < m && q[j].c > a[i] {
			ans += q[j].c
			q[j].b--
			if q[j].b == 0 {
				j++
			}
		} else {
			ans += a[i]
		}
	}
	fmt.Println(ans)
}
//  [go]
package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner((os.Stdin))

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

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

func main() {
	sc.Split(bufio.ScanWords)
	N, M, A, CC := nextInt(), nextInt(), []int{}, []ChangeCard{}

	for i := 0; i < N; i++ {
		A = append(A, nextInt())
	}
	for i := 0; i < M; i++ {
		CC = append(CC, ChangeCard{nextInt(), nextInt()})
	}

	fmt.Printf("%d\n", ABC127D(A, CC))
}

// ABC127D ...
func ABC127D(A []int, CC []ChangeCard) (res int) {
	ih := &intSmallHeap{}
	heap.Init(ih)
	for i := 0; i < len(A); i++ {
		heap.Push(ih, A[i])
	}

	for i := 0; i < len(CC); i++ {
		for j := 0; j < CC[i].b; j++ {
			min := heap.Pop(ih).(int)
			if min < CC[i].c {
				heap.Push(ih, CC[i].c)
			} else {
				heap.Push(ih, min)
			}
		}
	}

	for ih.Len() > 0 {
		res += heap.Pop(ih).(int)
	}

	return
}

// ChangeCard ...
type ChangeCard struct {
	b int
	c int
}

type intSmallHeap []int

func (h intSmallHeap) Len() int           { return len(h) }
func (h intSmallHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h intSmallHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *intSmallHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *intSmallHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}