jiahuimbzuai/CoQuIR huggingface dataset:
//  [cpp]
#include <bits/stdc++.h>
  
using namespace std;
  
template<class T> void ckmin(T &a, T b) { a = min(a, b); }
template<class T> void ckmax(T &a, T b) { a = max(a, b); }
  
#define pb push_back
#define mp make_pair
#define cotu cout
#define itn int
#define Red ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define F first
#define S second
#define sz(x) (int)x.size()
#define all(x) (x).begin(), (x).end()
#define rep(i, n) for(int i = 0; i < n; ++i)
#define repr(i,n) for(int i = n - 1; i >= 0; --i)
#define Rep(i, a, n) for(int i = (a); i <=(n); ++i)
#define repst(i, n) for(auto it = n.begin(); it != n.end(); ++it)
#define Repr(i, a, n) for(int i = (n); i >= (a); --i)
#define setp(x) fixed << setprecision(x)
#define ordered_set tree<int , null_type,less<int >, rb_tree_tag,tree_order_statistics_node_update> 
  
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds; 
  
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
  
const int inf = int(1e9);
const int mod = inf + 7;
const int N = 1e6 + 555; // TL MB
const double PI = acos(-1.0);
void mul(ll &x, ll y){
	x *= y;
	if(x >= mod) x %= mod;
}
 
void add(ll &x, ll y){
	x += y;
	if(x >= mod) x -= mod;
	if(x < 0) x += mod;
}
ll bp(ll a, ll n){
	ll r = 1;
	while(n){
		if(n & 1) mul(r, a);
		mul(a, a);
		n >>= 1;
	}
 
}
vector<vector<int> > u(3001, vector<int> (3001));

int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
char dz[] = {'U', 'D', 'R', 'L'};
string bfs(int x, int y, int px, int py){
	vector<vector<pii> > path(3001, vector<pii> (3001));
	vector<vector<int> > curu = u;
	queue<pii> q;
	q.push({x, y});
	curu[x][y] = 1;
	curu[px][py] = 0;
	while(!q.empty()){
		pii u = q.front();
		q.pop();
		rep(i, 4){
			int qx = u.F + dx[i], qy = u.S + dy[i];
			if(qx >= 0 && qx <= 3000 && qy >= 0 && qy <= 3000 && !curu[qx][qy]) {
				curu[qx][qy] = 1;
				q.push({qx, qy});
				path[qx][qy] = {u.F, u.S};
			}
		}
	}
	// return "1";
	string ans = "";
	while(mp(px, py) != mp(x, y)){
		u[px][py] = 1;
		int cx = px - path[px][py].F;
		int cy = py - path[px][py].S;
		rep(i, 4) if(cx == dx[i] && cy == dy[i]) ans += dz[i];
		tie(px, py) = path[px][py];
	}
	reverse(all(ans));
	return ans;
}
void solve()
{
	int x1, y1, x2, y2;
	cin >> x1 >> y1 >> x2 >> y2;
	x1 += 1500, y1 += 1500, x2 += 1500, y2 += 1500;
	string ans1 = bfs(x1, y1, x2, y2);
	string ans2 = bfs(x2, y2, x1, y1); 
	string ans3 = bfs(x1, y1, x2, y2);
	string ans4 = bfs(x2, y2, x1, y1);
	cout << ans1 << ans2 << ans3 << ans4;
}	 

 
int main()
{
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
    Red;
  	int T = 1;
  	// cin >> T;
  	for(int i = 1; i <= T; ++i){
  		solve();
  	}
  	return 0;

}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

int main(void){

    int sx, sy, tx, ty;

    scanf("%d%d%d%d", &sx, &sy, &tx, &ty);

    for(int i = 0; i < tx - sx; i++){
        printf("R");
    }
    for(int i = 0; i < ty - sy; i++){
        printf("U");
    }
    for(int i = 0; i < tx - sx; i++){
        printf("L");
    }
    for(int i = 0; i < ty - sy; i++){
        printf("D");
    }
    printf("D");
    for(int i = 0; i < tx - sx + 1; i++){
        printf("R");
    }
    for(int i = 0; i < ty - sy + 1; i++){
        printf("U");
    }
    printf("LU");
    for(int i = 0; i < tx - sx + 1; i++){
        printf("L");
    }
    for(int i = 0; i < ty - sy + 1; i++){
        printf("D");
    }
    printf("R\n");

    return 0;
}
//  [c]
i;
p(a,b){for(i=0;i++<b;)putchar(a);}

int main(void){

    int x,y,u,v;
    scanf("%d%d%d%d",&u,&v,&x,&y);
    
    x-=u;
    y-=v;
    //85:U 82:R 68:D 76:L
    p(85,y);
    p(82,x+1);
    p(68,y+1);
    p(76,x+1);
    p(85,1);
    p(76,1);
    p(85,y+1);
    p(82,x+1);
    p(68,y+1);
    p(76,x);
    
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int gcd(int x, int y){int r;while((r=x%y)!=0)x=y,y=r;return y;}

int main(void){

    int sx,sy;
    int tx,ty;
    int x,y;
    scanf("%d %d %d %d",&sx,&sy,&tx,&ty);
    
    x=tx-sx;
    y=ty-sy;
    
    for(int i=0;i<y;i++){
        printf("U");
    }
    for(int i=0;i<x;i++){
        printf("R");
    }
    for(int i=0;i<y;i++){
        printf("D");
    }
    for(int i=0;i<x;i++){
        printf("L");
    }
    
    printf("L");
    for(int i=0;i<y+1;i++){
        printf("U");
    }
    for(int i=0;i<x+1;i++){
        printf("R");
    }
    printf("DR");
    for(int i=0;i<y+1;i++){
        printf("D");
    }
    for(int i=0;i<x+1;i++){
        printf("L");
    }
    printf("U");
    printf("\n");
}
//  [javascript]
function main(lines) {
  const [sx, sy, tx, ty] = splitN(lines[0]);

  let s = '', cx = sx, cy = sy;
  const passed = [];
  moveTo(tx, ty);
  moveTo(sx, sy);
  moveTo(tx, ty);
  moveTo(sx, sy);

  function moveTo(x, y) {
    // console.log(cx, cy);
    while (cx != x || cy != y) {
      while (cy != y) {
        if (cy < y) {
          if (!isPassed(cx, cy+1)) {
            cy++;
            s += 'U';
          } else {
            cx--;
            s += 'L';
          }
        } else {
          if (!isPassed(cx, cy-1)) {
            cy--;
            s += 'D';
          } else {
            cx++;
            s += 'R';
          }
        }
        passed.push(cx+'_'+cy);
        // console.log(cx, cy);
      }
      while (cx != x) {
        if (cx < x) {
          if (!isPassed(cx+1, cy)) {
            cx++;
            s += 'R';
          } else {
            cy++;
            s += 'U';
          }
        } else {
          if (!isPassed(cx-1, cy)) {
            cx--;
            s += 'L';
          } else {
            cy--;
            s += 'D';
          }
        }
        passed.push(cx+'_'+cy);
        // console.log(cx, cy);
      }
    }
  }

  function isPassed(x, y) {
    if ((x === sx && y === sy) || (x === tx && y === ty)) return false;
    return passed.includes(x+'_'+y);
  }

  return s;
}


const ans = main( require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n") );
console.log( ans );

function splitN(s) {
  return s.split(' ').map(Number);
}
//  [javascript]
function main(input){
    input = input.split(' ')
    sx = parseInt(input[0], 10); sy = parseInt(input[1], 10)
    gx = parseInt(input[2], 10); gy = parseInt(input[3], 10)

    ans = ""
    for(var i = 0; i < (gy - sy); i++) ans = ans + 'U';
    for(var i = 0; i < (gx - sx); i++) ans = ans + 'R';
    for(var i = 0; i < (gy - sy); i++) ans = ans + 'D';
    for(var i = 0; i < (gx - sx) + 1; i++) ans = ans + 'L';
    for(var i = 0; i < (gy - sy) + 1; i++) ans = ans + 'U';
    for(var i = 0; i < (gx - sx) + 1; i++) ans = ans + 'R';
    ans = ans + 'D'; ans = ans + 'R'
    for(var i = 0; i < (gy - sy) + 1; i++) ans = ans + 'D';
    for(var i = 0; i < (gx - sx) + 1; i++) ans = ans + 'L';
    ans = ans + 'U'
    console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
	var numbers = chunk.toString().split(' ');
	var sx = parseInt(numbers[0]);
	var sy = parseInt(numbers[1]);
	var tx = parseInt(numbers[2]);
	var ty = parseInt(numbers[3]);
	
	var A = tx - sx;
	var B = ty - sy;

	function concatN (c, N) {
		var ret = "";
		for (var i=0; i < N; i++)
		    ret = ret + c;
		return ret;
	}
	
	var ans = concatN("R", A);
	ans = ans + concatN("U",B);
	
	ans = ans + concatN("L",A);
	ans = ans + concatN("D",B);
	
	ans = ans + "D" + concatN("R",A+1);
	ans = ans + concatN("U",B+1) + "L";
	
	ans = ans + "U" + concatN("L",A+1);
	ans = ans + concatN("D",B+1) + "R";
	
	console.log(ans);
	
	process.exit();
});
//  [go]
package main;

import "fmt"

func bfs(field [][]bool, sx, sy, tx, ty int) string {
	var vec = [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}

	x := make([]int, 0)
	y := make([]int, 0)

	x = append(x, sx)
	y = append(y, sy)

	checked := make([][]int, 1000 * 2 + 3)
	GETA := 1001

	for i := 0; i <= 1000 * 2 + 2; i++ {
		checked[i] = make([]int, 1000 * 2 + 3)
		for j := 0; j < len(field[i]); j++ {
			if field[i][j] {
				checked[i][j] = 6
			}
		}

	}
	checked[sy + GETA][sx + GETA] = 5
	checked[ty + GETA][tx + GETA] = 0

	func() {
		for i := 0; i < len(x); i++ {
			for k, v := range vec {
				nx := x[i] + v[0]
				ny := y[i] + v[1]
				if !(-GETA <= nx && nx <= GETA && -GETA <= ny &&ny <= GETA) {
					continue
				}
				if checked[ny + GETA][nx + GETA] > 0 {
					continue
				}

				checked[ny + GETA][nx + GETA] = k + 1
				if ny == ty && nx == tx {
					return
				}
				x = append(x, nx)
				y = append(y, ny)
			}
		}
	}()
	cx := tx
	cy := ty
	ans := ""
	for {
		k := checked[cy + GETA][cx + GETA]

		if k == 1 {
			ans += "R"
			cx += -1
		} else if k == 2 {
			ans += "L"
			cx += +1
		} else if k == 3 {
			ans += "U"
			cy += -1
		} else if k == 4 {
			ans += "D"
			cy += 1
		} else if k == 5 {
			break
		} else {
			panic(k)
		}
		field[cy + GETA][cx + GETA] = true
	}
	return ans
}

func main() {
	var sx, sy, tx, ty int
	fmt.Scan(&sx, &sy, &tx, &ty)
	field := make([][]bool, 1000 * 2 + 3)
	for i := 0; i < len(field); i++ {
		field[i] = make([]bool, 1000 * 2 + 3)
	}
	ans := ""
	ans += bfs(field, sx, sy, tx, ty)
	ans += bfs(field, tx, ty, sx, sy)
	ans += bfs(field, sx, sy, tx, ty)
	ans += bfs(field, tx, ty, sx, sy)

	fmt.Println(ans)

}
//  [go]
package main

import "fmt"

func main() {
	var sx, sy, tx, ty int
	fmt.Scan(&sx, &sy, &tx, &ty)
	tx -= sx
	ty -= sy
	sx = 0
	sy = 0
	for ; sx != tx; sx++ {
		fmt.Print("R")
	}
	for ; sy != ty; sy++ {
		fmt.Print("U")
	}
	for ; sx != 0; sx-- {
		fmt.Print("L")
	}
	for ; sy != 0; sy-- {
		fmt.Print("D")
	}
	fmt.Print("D")
	sy--
	for ; sx != tx+1; sx++ {
		fmt.Print("R")
	}
	for ; sy != ty; sy++ {
		fmt.Print("U")
	}
	fmt.Print("LU")
	sx--
	sy++
	for ; sx != -1; sx-- {
		fmt.Print("L")
	}
	for ; sy != 0; sy-- {
		fmt.Print("D")
	}
	fmt.Print("R")
	fmt.Println()
}
//  [go]
package main

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

var sx, sy, tx, ty int

func main() {
	fsc := NewFastScanner()
	sx, sy, tx, ty = fsc.NextInt(), fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
	diffx := tx - sx
	diffy := ty - sy
	for i := 0; i < diffx; i++ {
		fmt.Print("R")
	}
	for i := 0; i < diffy; i++ {
		fmt.Print("U")
	}

	for i := 0; i < diffx; i++ {
		fmt.Print("L")
	}
	for i := 0; i < diffy; i++ {
		fmt.Print("D")
	}
	fmt.Print("D")
	for i := 0; i < diffx+1; i++ {
		fmt.Print("R")
	}
	for i := 0; i < diffy+1; i++ {
		fmt.Print("U")
	}
	fmt.Print("L")

	fmt.Print("U")
	for i := 0; i < diffx+1; i++ {
		fmt.Print("L")
	}
	for i := 0; i < diffy+1; i++ {
		fmt.Print("D")
	}
	fmt.Print("R")
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1024)
	return &FastScanner{r: rdr}
}
func (s *FastScanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *FastScanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *FastScanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *FastScanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *FastScanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *FastScanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}
//  [ruby]
sx, sy, tx, ty = gets.split.map(&:to_i)

M = Hash.new {|h,k| h[k] = {}}
D = [['U', 0, 1], ['D', 0, -1], ['R', 1, 0], ['L', -1, 0]]

def walk(x, y, tx, ty)
  return '' if x == tx && y == ty 
  M[x][y] = true
  nx = D.map{|v| [v[0], x + v[1], y + v[2]]}.reject{|v| M[v[1]][v[2]]}
  w = nx.sort{|a, b| (a[1] - tx) ** 2 + (a[2] - ty) ** 2 <=> (b[1] - tx) ** 2 + (b[2] - ty) ** 2}.first
  w[0] + walk(w[1], w[2], tx, ty)
end

all = ""
all << walk(sx, sy, tx, ty)
M[sx][sy] = false
all << walk(tx, ty, sx, sy)
M[tx][ty] = false
all << walk(sx, sy, tx, ty)
M[sx][sy] = false
all << walk(tx, ty, sx, sy)

puts all
//  [ruby]
sx, sy, tx, ty = gets.split.map(&:to_i)

dx = tx - sx
dy = ty - sy

puts "R" * dx + "U" * dy + "L" * dx + "D" * dy +
     "D" + "R" * (dx + 1) + "U" * (dy + 1) + "L" + 
     "U" + "L" * (dx + 1) + "D" * (dy + 1) + "R"
//  [ruby]
sx,sy,tx,ty = gets.split.map(&:to_i)
path1 = "U"*(ty - sy) + "R"*(tx - sx)
path2 = "D"*(ty - sy) + "L"*(tx - sx)
path3 = "L" + "U"*(ty - sy + 1) + "R"*(tx - sx + 1) + "D"
path4 = "R" + "D"*(ty - sy + 1) + "L"*(tx - sx + 1) + "U"
puts path1+path2+path3+path4
//  [python]
N, M = map(int, input().split())

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

A.sort()
ans = sum(A)
P = [0]*M
for i in range(M):
  P[i] = list(map(int, input().split()))

P.sort(key=lambda x: x[1],reverse=True)

n = 0
import bisect

while len(A)>0 and n<M:
  ind = bisect.bisect_left(A,P[n][1])
  for _ in range(min(ind,P[n][0])):
    a = A.pop(0)
    ans += P[n][1]-a
  if ind <= P[n][0]:
    break
  n+=1

print(ans)
//  [python]
import numpy as np
import heapq

N, M = map(int, input().split())
A = np.fromiter(map(int, input().split()), np.int64)
B = np.empty(M, np.int)
C = np.empty(M, np.int)
for j in range(M):
	B[j], C[j] = map(int, input().split())

A = np.sort(A)

class Reps (object):
	def __init__(self, b, c):
		self.b = b
		self.c = c
	
	def __lt__(self, other):
		return self.c > other.c

Z = np.zeros(N, np.int)

heap = []
for j in range(M):
	heapq.heappush(heap, Reps(B[j], C[j]))

while heap:
	reps = heapq.heappop(heap)
	b, c = reps.b, reps.c
	i = np.searchsorted(A, c)
	b = min(b, i)
	if b == 0:
		break
	for h in range(i-b, i):
		heapq.heappush(heap, Reps(1, A[h]))
		A[h] = c

print(np.sum(A))
//  [python]
N, M = map(int, input().split())
listA = list(map(int, input().strip().split()))


class BCSet:
    B = 0
    C = 0


listBC = []

for i in range(0, M):
    B, C = map(int, input().split())
    new_BCSet = BCSet()
    new_BCSet.B = B
    new_BCSet.C = C
    listBC.append(new_BCSet)


def MurgeSort(left, right):
    if (right-left == 1):
        return
    mid = left + int((right - left) / 2)
    MurgeSort(left, mid)
    MurgeSort(mid, right)
    tmp = []
    for i in range(left, mid):
        tmp.append(listBC[i])
    for i in range(mid, right):
        tmp.append(listBC[mid + right - i - 1])
    iterator_left = 0
    iterator_right = right-left-1
    for i in range(left, right):
        if tmp[iterator_left].C <= tmp[iterator_right].C:
            listBC[i] = tmp[iterator_left]
            iterator_left += 1
        else:
            listBC[i] = tmp[iterator_right]
            iterator_right -= 1


def AMurgeSort(left, right):
    if (right-left == 1):
        return
    mid = left + int((right - left) / 2)
    AMurgeSort(left, mid)
    AMurgeSort(mid, right)
    tmp = []
    for i in range(left, mid):
        tmp.append(listA[i])
    for i in range(mid, right):
        tmp.append(listA[mid + right - i - 1])
    iterator_left = 0
    iterator_right = right-left-1
    for i in range(left, right):
        if tmp[iterator_left] <= tmp[iterator_right]:
            listA[i] = tmp[iterator_left]
            iterator_left += 1
        else:
            listA[i] = tmp[iterator_right]
            iterator_right -= 1


MurgeSort(0, M)
AMurgeSort(0, N)

sum = 0
card_total = 0
cpoint = 0
iadjuster = 0

for i in range(0, N):
    if listA[N - i - 1+iadjuster] >= listBC[M - cpoint - 1].C or cpoint >= M:
        card_total += 1
        sum += listA[N - i - 1+iadjuster]
        if card_total == N:
            break
    else:
        if card_total + listBC[M - cpoint - 1].B > N:
            sum += (listBC[M - cpoint - 1].B-(card_total +
                                              listBC[M - cpoint - 1].B - N)) * listBC[M - cpoint - 1].C
            break
        else:
            card_total += listBC[M - cpoint - 1].B
            sum += listBC[M - cpoint - 1].B * listBC[M - cpoint - 1].C
            cpoint += 1
            iadjuster += 1


print("{}".format(sum))
//  [java]

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();
		List<Long> list = new ArrayList<>();
		for(int i = 0; i < N; i++) {
			list.add(sc.nextLong());
		}
		Collections.sort(list);
		List<Pair> con = new ArrayList<>();
		for(int i = 0; i < M; i++) {
			int b = sc.nextInt();
			long c = sc.nextLong();
			con.add(new Pair(c, b));
		}
		con.sort(Comparator.comparing(Pair::getValue).reversed());
		long ans = 0;
		boolean end = false;
		for(Pair pair : con) {
			long value = pair.getValue();
			int sum = pair.getSum();
			while(sum > 0) {
				long first = list.get(0);
				list.remove(0);
				if(value > first) {
					ans += value;
				} else {
					ans += first;
					end = true;
				}
				if(list.isEmpty()) {
					end = true;
					break;
				}
				sum--;
			}
			if(end) {
				break;
			}
		}
		for(Long j : list) {
			ans += j;
		}
		System.out.println(ans);
	}

}

class Pair {
	private long value;
	private int sum;

	protected Pair(long value, int sum) {
		super();
		this.value = value;
		this.sum = sum;
	}

	public long getValue() {
		return value;
	}

	public void setValue(long value) {
		this.value = value;
	}

	public int getSum() {
		return sum;
	}

	public void setSum(int sum) {
		this.sum = sum;
	}

	@Override
	public String toString() {
		return "Pair [value=" + value + ", sum=" + sum + "]";
	}

}
//  [java]
import java.util.*;

public class Main {
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[]$) {
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        List<Integer> a = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            a.add(scanner.nextInt());
        }
        Collections.sort(a);

        int[][] bc = new int[m][2];
        for (int i = 0; i < m; i++) {
            bc[i][0] = scanner.nextInt();
            bc[i][1] = scanner.nextInt();
        }
        Arrays.sort(bc, Comparator.<int[]>comparingInt(ar -> ar[1]).reversed());

        long sum = 0;
        for (int[] array : bc) {
            for (int i = 0; i < array[0]; i++) {
                if (a.isEmpty() || a.get(0) >= array[1]) {
                    break;
                }
                a.remove(0);
                sum += array[1];
            }
        }

        for (int i : a) {
            sum += i;
        }

        System.out.println(sum);
    }
}
//  [cpp]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <queue>
#include <algorithm>

#include <bits/stdc++.h>
#include <cmath>
#include <limits>

using namespace std;
typedef long long LL;
using Graph = vector<vector<int>>;

static long long INF = (1LL<<62);

int lbound(vector<long long>&v, long long b){
	int s = 0, e = v.size() - 1;
	int l = v.size();
	int m;
	while(e - s > 1){
		m = (s + e) / 2;
		if(v[m] >= b){
			e = m;
		}
		else{
			s = m;
		}
	}
	if(v[max(s - 1, 0)] >= b) return max(s - 1, 0);
	else if(v[s] >= b) return s;
	else if(v[min(s + 1, l - 1)] >= b) return min(s + 1, l - 1);
	else return v.size();
}

long long N, M;
vector<long long> A, B, C;

int main(int argc, char* argv[]){
	cin.tie(0);
	ios::sync_with_stdio(false);

	cin >> N >> M;
	for(int i=0; i<N; i++){
		long long a;
		cin >> a;
		A.push_back(a);
	}
	sort(A.begin(), A.end());
	for(int i=0; i<M; i++){
		long long b, c;
		cin >> b >> c;
		B.push_back(b);
		C.push_back(c);
	}
	for(int i=0; i<M; i++){
		if(i<M-1 && B[i+1]==N && C[i+1]>=C[i]) continue;
		long long b = B[i];
		long long c = C[i];
		long long k = (long long)lbound(A, c);
		long long u = min(k, b);
		if(k > 0){
			for(int j = u; j <= k - 1; j++){
				A[j - u] = A[j];
			}
			for(int j = k - u; j <= k - 1; j++){
				A[j] = c;
			}
		}
	}
	long long ans = 0;
	for(int i=0; i<N; i++){
		ans += A[i];
	}
	printf("%lld\n", ans);
	return 0;
}
//  [cpp]
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#define rep(i, n) for(int i = 0; i < n; ++i)
typedef long long ll;
typedef pair<int, int > S; 


bool comp(S lhs, S rhs) {
	return lhs.first > rhs.first;
}

int main()
{
	int n,m;cin >> n >> m;
	vector<int> A(n);
	rep(i, n)cin>>A[i];
	vector<pair<int , int>> BC(m);
	rep(i, m)
	{
		int b, c; cin >> b >> c;
		BC[i] = make_pair(c, b);
	}

	sort(A.begin(),A.end());
	sort(BC.begin(),BC.end(),comp);

	//rep(i,BC.size())cout<<BC[i].first;
	
	
	rep(i,A.size())
	{
		if(A[i]<BC[0].first)
		{
			A[i]=BC[0].first;
			BC[0].second--;
		}
		else break;

		//cout<<BC[0].second<<endl;
		if(BC[0].second==0)
		{
			BC.erase(BC.begin());
		}
		if(BC.size()==0)break;
	}

	ll sum=0;
	rep(i,A.size())sum+=A[i];
	cout<<sum<<endl;
	return 0;
}
//  [cpp]
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <math.h>

using namespace std;
typedef pair<int, int> P;
#define mp make_pair
bool cmp(P a, P b){
  return a.first > b.first;
}

int main(){
  int n,m;
  vector<P> c;
  vector<int>  a;
  cin >> n >> m;
  int count = n;
  for(int i = 0; i < n; i ++){
    int t;
    cin >> t;
    a.push_back(t);
  }
  sort(a.begin(),a.end());

  for(int i = 0; i < m; i ++){
    int t1,t2;
    cin >> t1 >> t2;
    c.push_back ( mp(t2,t1) );
  }
  sort(c.begin(),c.end(),cmp);
  for(int i = 0 ; i < n; i++){
    if(c[0].second == 0) break;
    if(a[i] > c[0].first) break;
    else {
      a[i] = c[0].first;
      c[0].second --;
      if(c[0].second == 0){
        c.erase(c.begin());
      }
    }
  }
  long long sum = 0;
  for(int i=0;i<n;i++){
    //cout << a[i] << ' ';
    sum += a[i];
  }
  cout  << sum;
  return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define LL long long
#define INF 1<<31-1
#define LLINF 1<<63-1
#define MIN(x,y) ((x)<(y)?(x):(y))
#define MAX(x,y) ((x)<(y)?(y):(x))
#define MOD 1000000007
#define NUM 100001
void swap(int* x,int* y){
  int tmp=*x;*x=*y;*y=tmp;
}

typedef struct{int B;int C;}P;
int cmp(const void *x,const void *y){
  return *(int*)x-*(int*)y;
}
int Scmp(const void *x,const void *y){
  return ((P*)y)->C-((P*)x)->C;
}

int main() {
  int i,j,k=0,N,M;LL ans=0;
  scanf("%d%d",&N,&M);
  int A[N];P bc[M];
  for(i=0;i<N;i++)scanf("%d",&A[i]);
  for(i=0;i<M;i++)scanf("%d%d",&bc[i].B,&bc[i].C);
  qsort(A,N,4,cmp);qsort(bc,M,sizeof(P),Scmp);
  for(i=0;i<M;i++){
    if(A[k]>=bc[i].C)while(A[k]>=bc[i].C&&k<N)k++;
    if(k==N)break;
    for(j=0;j<bc[i].B;j++)if(A[k]<bc[i].C)A[k++]=bc[i].C;
  }
  for(i=0;i<N;i++)ans+=A[i];

  printf("%lld\n",ans);
	return 0;
}
//  [javascript]
function Main(input) {
    lines = input.split('\n')
    l = lines.shift().split(' ')
    n = l[0] * 1
    m = l[1] * 1
    cs = lines.shift().split(' ').sort(function (a, b) { return a - b })
    lines.pop()
    ls = lines.sort(function(a, b) { return b.split(' ')[1] - a.split(' ')[1] })
    idx = 0
    for (i = 0; i < ls.length; i++) {
        l = ls[i].split(' ')
        b = l[0] * 1
        c = l[1] * 1
        while (b--) {
            if (cs[idx] === undefined) break;
            if (cs[idx] < c) {
                cs[idx] = c
            } else {
                break;
            }
            idx++
        }
        if (cs[idx] === undefined) break;
    }
    ans = cs.reduce(function(a, c) { return a + c * 1}, 0)
    console.log(ans)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

!function () {
  function splitNum(line) {
    return (Array.isArray(line) ? line : line.split(/\s+/)).map(function (n) {
      return parseInt(n);
    });
  }

  function sortByKey(arr, keys) {
    if (!Array.isArray(keys)) keys = [keys];
    return arr.sort(function (a, b) {
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var k = _step.value;

          if ("string" == typeof k) {
            var d = a[k] - b[k];
            if (0 !== d) return d;
          } else {
            var _d = a[k[0]] - b[k[0]];

            var sig = "desc" === k[1] ? -1 : "asc" === k[1] ? 1 : Number(k[1]);
            if (0 !== _d) return _d * sig;
          }
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }

      return 0;
    });
  }

  !function (input) {
    var lines = input.split("\n");

    var _splitNum = splitNum(lines[0]),
        _splitNum2 = _slicedToArray(_splitNum, 2),
        N = _splitNum2[0],
        M = _splitNum2[1];

    var A = splitNum(lines[1]).slice(0, N);
    var bcs = lines.slice(2, M + 2).map(function (line) {
      var _splitNum3 = splitNum(line),
          _splitNum4 = _slicedToArray(_splitNum3, 2),
          B = _splitNum4[0],
          C = _splitNum4[1];

      return {
        B: B,
        C: C
      };
    });
    A.sort(function (a, b) {
      return a - b;
    });
    sortByKey(bcs, [["C", -1]]);
    var sum = 0;
    var index = 0,
        bci = 0;

    for (; index < N; index++) {
      var q = bcs[bci];
      if (null == q) break;
      if (!(q.B <= 0)) {
        if (A[index] < q.C) {
          sum += q.C;
          q.B--;
        } else break;
      } else {
        bci++;
        index--;
      }
    }

    for (; index < N; index++) {
      sum += A[index];
    }

    console.log(sum);
  }(require("fs").readFileSync("/dev/stdin", "utf8"));
}();
//  [go]
package main

import (
	"container/heap"
	"fmt"
	"sort"
)

type Heap struct {
	data []int
}

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

type Data struct {
	b, c int
}
type DataSlice struct {
	data []*Data
}

func (s DataSlice) Len() int           { return len(s.data) }
func (s DataSlice) Swap(i, j int)      { s.data[i], s.data[j] = s.data[j], s.data[i] }
func (s DataSlice) Less(i, j int) bool { return s.data[i].c > s.data[j].c }

func main() {
	n, m := oneInt(), oneInt()
	input := scanNums(n)

	dataSlice := &DataSlice{[]*Data{}}
	for i := 0; i < m; i++ {
		b, c := oneInt(), oneInt()
		dataSlice.data = append(dataSlice.data, &Data{b, c})
	}

	h := calc(input, dataSlice)

	sum := 0
	for _, v := range h.data {
		sum += v
	}
	fmt.Println(sum)

}

func calc(input []int, dataSlice *DataSlice) *Heap {
	h := &Heap{}
	heap.Init(h)
	for _, a := range input {
		heap.Push(h, a)
	}

	sort.Sort(dataSlice)
	for _, d := range dataSlice.data {
		for i := 0; i < d.b; i++ {
			if m, ok := heap.Pop(h).(int); ok {
				if m < d.c {
					heap.Push(h, d.c)
				} else {
					heap.Push(h, m)
					return h
				}
			}
		}
	}
	return h
}

func oneInt() int {
	var a int
	fmt.Scan(&a)
	return a
}

func scanNums(len int) (nums []int) {
	var num int
	for i := 0; i < len; i++ {
		fmt.Scan(&num)
		nums = append(nums, num)
	}
	return
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

type Heap struct {
	data []int
}

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

type Data struct {
	b, c int
}
type DataSlice struct {
	data []*Data
}

func (s DataSlice) Len() int           { return len(s.data) }
func (s DataSlice) Swap(i, j int)      { s.data[i], s.data[j] = s.data[j], s.data[i] }
func (s DataSlice) Less(i, j int) bool { return s.data[i].c > s.data[j].c }

func main() {
	n, m := oneInt(), oneInt()
	input := scanNums(n)

	dataSlice := &DataSlice{[]*Data{}}
	for i := 0; i < m; i++ {
		b, c := oneInt(), oneInt()
		dataSlice.data = append(dataSlice.data, &Data{b, c})
	}

	ans := calc(input, dataSlice, n)

	fmt.Println(ans)

}

func calc(input []int, dataSlice *DataSlice, n int) int {
	for _, a := range input {
		dataSlice.data = append(dataSlice.data, &Data{1, a})
	}

	sort.Sort(dataSlice)

	count := 0
	sum := 0
	for _, d := range dataSlice.data {
		for i := 0; i < d.b; i++ {
			if count == n {
				return sum
			}
			count++
			sum += d.c
		}
	}
	return sum
}

func oneInt() int {
	var a int
	fmt.Scan(&a)
	return a
}

func scanNums(len int) (nums []int) {
	var num int
	for i := 0; i < len; i++ {
		fmt.Scan(&num)
		nums = append(nums, num)
	}
	return
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}
//  [go]
package main

import (
    "fmt"
    "sort"
)

type As [][]int

func (a As) Len() int {
    return len(a)
}

func (a As) Swap(i, j int) {
    a[i], a[j] = a[j], a[i]
}

func (a As) Less(i, j int) bool {
    return a[i][0] > a[j][0]
}

func main() {
    var n, m int
    fmt.Scan(&n, &m)
    as := make(As, n+m)
    for i := 0; i < n; i++ {
        var a int
        fmt.Scan(&a)
        as[i] = []int{a, 1}
    }
    for i := 0; i < m; i++ {
        var b, c int
        fmt.Scan(&b, &c)
        as[n+i] = []int{c, b}
    }
    sort.Sort(as)
    var sum, cnt int
    for i := 0; i < len(as); i++ {
        wgt, num := as[i][0], as[i][1]
        if num >= n-cnt {
            sum += (n - cnt) * wgt
            break
        } else {
            sum += wgt * num
            cnt += num
        }
    }
    fmt.Println(sum)
}
//  [ruby]
class PriorityQueue
    def initialize(arr)
        @size = arr.size
        @array = arr
        @array.unshift(nil)
        h = (@size / 2) | 0
        h.downto(1) do |i|
            maxHeapify(i)
        end
    end
    def getArray
        return @array[1..@size]
    end
    def maxHeapify(i)
        left = 2 * i
        right = 2 * i + 1
        largest = 0
        if left <= @size && @array[left] > @array[i]
            largest = left
        else
            largest = i
        end
        if right <= @size && @array[right] > @array[largest]
            largest = right
        end
        if largest != i
            @array[i], @array[largest] = @array[largest], @array[i]
            maxHeapify(largest)
        end
    end
    def pop
        return -(1<<40) if @size < 1
        maxv = @array[1]
        @array[1] = @array[@size]
        @size -= 1
        maxHeapify(1)
        maxv
    end
    def push(e)
        @size += 1
        i = @size
        @array[i] = -(1<<40)
        return if e < @array[i]
        @array[i] = e
        while i > 1 && @array[i/2] < @array[i]
            @array[i], @array[i/2] = @array[i/2], @array[i]
            i = i / 2
        end
    end
end
 
n, m = gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split(" ").map{|n| n.to_i * (-1)}
pq = PriorityQueue.new(a)
arr = []
m.times do
    arr << gets.chomp.split(" ").map(&:to_i)
end
arr = arr.sort_by(&:last).reverse

arr.each do |i|
    b, c = i
    b.times do
        smallest = pq.pop
        if -smallest >= c then
            pq.push(smallest)
            break
        end
        pq.push(-c)
    end
end
 
a = pq.getArray
puts a.map{|n| n*(-1)}.inject(:+)
//  [ruby]
class PriorityQueue
  MIN = -(2 << 60)

  attr_reader :size

  def initialize(&block)
    @size = 0
    @heap = Array.new
    @get_key = block || :itself.to_proc
  end

  def empty?
    size == 0
  end

  def pop
    return nil if @size <= 0
    max = @heap[1]
    @heap[1] = @heap[@size]
    @size -= 1
    max_heapify(1)
    max
  end

  def push(x)
    @size += 1
    i = @size
    @heap[i] = x
    while i > 1 && @get_key.call(@heap[i / 2]) < @get_key.call(@heap[i])
      t = @heap[i / 2]
      @heap[i / 2] = @heap[i]
      @heap[i] = t
      i = i / 2
    end
  end

  def top
    return nil if @size <= 0
    @heap[1]
  end

  def to_a
    return [] if @size == 0
    @heap[1..@size]
  end

  private

  def max_heapify(i)
    l = 2 * i
    r = 2 * i + 1
    largest =
      l <= @size && @get_key.call(@heap[l]) > @get_key.call(@heap[i]) ? l : i
    largest = r \
      if r <= @size && @get_key.call(@heap[r]) > @get_key.call(@heap[largest])
    unless largest == i
      t = @heap[i]
      @heap[i] = @heap[largest]
      @heap[largest] = t
      max_heapify(largest)
    end
  end
end

N, M = gets.split.map(&:to_i)
a_list = gets.split.map(&:to_i)
bc_list = M.times.map { gets.split.map(&:to_i) }
sorted = bc_list.sort_by { |(_, c)| -c }
pq = PriorityQueue.new { |a| -a } # 小さい値を優先
a_list.each { |a| pq.push(a) }
sorted.each do |(b, c)|
  while b > 0
    break if pq.top >= c
    pq.pop
    pq.push(c)
    b -= 1
  end
end
ans = pq.to_a.reduce(&:+)
puts ans
//  [ruby]
class PriorityQueue
  MIN = -(2 << 60)

  attr_reader :size

  def initialize(&block)
    @size = 0
    @heap = Array.new
    @get_key = block || :itself.to_proc
  end

  def empty?
    size == 0
  end

  def pop
    return nil if @size <= 0
    max = @heap[1]
    @heap[1] = @heap[@size]
    @size -= 1
    max_heapify(1)
    max
  end

  def push(x)
    @size += 1
    i = @size
    @heap[i] = x
    while i > 1 && @get_key.call(@heap[i / 2]) < @get_key.call(@heap[i])
      t = @heap[i / 2]
      @heap[i / 2] = @heap[i]
      @heap[i] = t
      i = i / 2
    end
  end

  def top
    return nil if @size <= 0
    @heap[1]
  end

  def to_a
    return [] if @size == 0
    @heap[1..@size]
  end

  private

  def max_heapify(i)
    l = 2 * i
    r = 2 * i + 1
    largest =
      l <= @size && @get_key.call(@heap[l]) > @get_key.call(@heap[i]) ? l : i
    largest = r \
      if r <= @size && @get_key.call(@heap[r]) > @get_key.call(@heap[largest])
    unless largest == i
      t = @heap[i]
      @heap[i] = @heap[largest]
      @heap[largest] = t
      max_heapify(largest)
    end
  end
end

N, M = gets.split.map(&:to_i)
a_list = gets.split.map(&:to_i)
bc_list = M.times.map { gets.split.map(&:to_i) }
sorted = bc_list.sort_by { |(_, c)| -c }
pq = PriorityQueue.new { |a| -a } # 小さい値を優先
a_list.each { |a| pq.push(a) }
sorted.each do |(b, c)|
  while b > 0 && c > pq.top
    pq.pop
    pq.push(c)
    b -= 1
  end
end
ans = pq.to_a.reduce(&:+)
puts ans
//  [typescript]
import { readFileSync } from 'fs'

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

  const list = [
    ...cards.map(v => [1, v]),
    ...lines,
  ]

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

  let result = 0

  let j = 0, maxLength = cards.length
  for (const [count, value] of list) {
    for (let i = 0; i < count && j < maxLength; ++i, ++j) {
      result += value
    }
  }

  console.log(result)
}

main(readFileSync('/dev/stdin', 'utf8').trim())
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const [n, m] = stdin
  .split('\n')[0]
  .split(' ')
  .map(Number)
let a = stdin
  .split('\n')[1]
  .split(' ')
  .map(Number)

const [, , ..._bc] = stdin.trim().split('\n')
const bc = _bc.map(e => e.split(' ').map(Number))

const ans = _ => {
  let pool = a.map(e => [e, 1])

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

    pool.push([c, b])
  }

  pool.sort((a, b) => {
    return b[0] - a[0]
  })

  let i = 0
  let sum = 0
  let count = 0
  while (count < n) {
    const card = pool[i][0]
    sum += card
    count++
    pool[i][1]--
    if (pool[i][1] <= 0) {
      i++
    }
  }

  return sum
}

console.log(ans())
//  [python]
N = input()
sum = 0
for i in range(N):
    l, r = map(int, raw_input().split())
    sum += r - l + 1
print sum
//  [python]
import sys
input = sys.stdin.readline

n = int(input())
sum = 0
for i in range(n):
    l, r = map(int, input().split())
    sum += r+1-l
print(sum)
//  [python]
#!/usr/bin/env python3
import sys


def solve(N: int, l: "List[int]", r: "List[int]"):
    ret = 0
    for i in range(N):
        ret += r[i] - l[i] + 1
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    l = [int()] * (N)  # type: "List[int]" 
    r = [int()] * (N)  # type: "List[int]" 
    for i in range(N):
        l[i] = int(next(tokens))
        r[i] = int(next(tokens))
    solve(N, l, r)

if __name__ == '__main__':
    main()
//  [python]
# -*- coding: utf-8 -*-

import os
import sys
import math
import numpy as np


N = int(input())
seat = np.array([list(map(int, input().split())) for i in range(N)])

print(np.sum(seat[:,1] - seat[:,0]+1))
//  [python]
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
gosa = 1.0 / 10**10
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    n = I()
    r = 0
    for _ in range(n):
        a,b = LI()
        r += b-a+1

    return r

print(main())
//  [python]
import numpy as np
hoge = input()
N = int(hoge)
data = np.zeros((N,2))
num = 0
for i in range(N):
    hoge = input()
    hoge = hoge.strip().split(" ")
    num += int(hoge[1])-int(hoge[0])+1
print(num)
//  [java]
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;

public class Main {

	static PrintWriter out;
	static InputReader ir;

	static void solve() {
		int n=ir.nextInt();
		int ret=0;
		for(int i=0;i<n;i++)
			ret-=ir.nextInt()-ir.nextInt()-1;
		out.println(ret);
	}

	public static void main(String[] args) throws Exception {
		ir = new InputReader(System.in);
		out = new PrintWriter(System.out);
		solve();
		out.flush();
	}

	static class InputReader {

		private InputStream in;
		private byte[] buffer = new byte[1024];
		private int curbuf;
		private int lenbuf;

		public InputReader(InputStream in) {
			this.in = in;
			this.curbuf = this.lenbuf = 0;
		}

		public boolean hasNextByte() {
			if (curbuf >= lenbuf) {
				curbuf = 0;
				try {
					lenbuf = in.read(buffer);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (lenbuf <= 0)
					return false;
			}
			return true;
		}

		private int readByte() {
			if (hasNextByte())
				return buffer[curbuf++];
			else
				return -1;
		}

		private boolean isSpaceChar(int c) {
			return !(c >= 33 && c <= 126);
		}

		private void skip() {
			while (hasNextByte() && isSpaceChar(buffer[curbuf]))
				curbuf++;
		}

		public boolean hasNext() {
			skip();
			return hasNextByte();
		}

		public String next() {
			if (!hasNext())
				throw new NoSuchElementException();
			StringBuilder sb = new StringBuilder();
			int b = readByte();
			while (!isSpaceChar(b)) {
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		public int nextInt() {
			if (!hasNext())
				throw new NoSuchElementException();
			int c = readByte();
			while (isSpaceChar(c))
				c = readByte();
			boolean minus = false;
			if (c == '-') {
				minus = true;
				c = readByte();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res = res * 10 + c - '0';
				c = readByte();
			} while (!isSpaceChar(c));
			return (minus) ? -res : res;
		}

		public long nextLong() {
			if (!hasNext())
				throw new NoSuchElementException();
			int c = readByte();
			while (isSpaceChar(c))
				c = readByte();
			boolean minus = false;
			if (c == '-') {
				minus = true;
				c = readByte();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res = res * 10 + c - '0';
				c = readByte();
			} while (!isSpaceChar(c));
			return (minus) ? -res : res;
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextLongArray(int n) {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public char[][] nextCharMap(int n, int m) {
			char[][] map = new char[n][m];
			for (int i = 0; i < n; i++)
				map[i] = next().toCharArray();
			return map;
		}
	}
}
//  [java]
import java.util.Scanner;

public class Main {

    Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        new Main().compute();
    }

    void compute() {
        int N=scanner.nextInt();
        int ans=0;
        for(int i=0;i<N;i++){
            ans+=-(scanner.nextInt()-scanner.nextInt()-1);
        }
        System.out.println(ans);
    }
}
//  [java]
import java.util.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        int result = IntStream.range(0, N).map(i ->{
            int l = sc.nextInt();
            int r = sc.nextInt();
            return r-l+1;
        }).sum();

        System.out.print(result);
    }
}
//  [java]
import java.io.*;
import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {
  public static void main(String[] args) {
    new Main().run();
  }

  private void run() {
    try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out)) {

      final int MAX = 100000;
      int n = Integer.parseInt(in.readLine());

      int[] table = new int[MAX+1];
      in.lines()
        .limit(n)
        .map(s -> s.split(" "))
        .map(a -> Arrays.stream(a).mapToInt(Integer::parseInt).toArray())
        .forEach(a -> IntStream.rangeClosed(a[0],a[1])
          .parallel()
          .forEach(i -> table[i] = 1)
        );

      final int ans = Arrays.stream(table).sum();
      System.out.println(ans);
    }
    catch(IOException e) {
      System.err.println(e);
    }
  }
}
//  [cpp]
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <regex>
#define REP(i,n) for(int i = 0; i < n; i++)
#define FOR(i,j,n) for(int i = j; i < n; i++)
#define RFOR(i,j,n) for(int i = j-1; i >= n; i--)
#define PREC(n) fixed << setprecision(n)
#define print_array(v) REP(__k, v.size()) { cout << v[__k]; if(__k != v.size()-1) cout << " "; else cout << endl; }
#define YesorNo(a) printf(a?"Yes\n":"No\n")
#define _LIBCPP_DEBUG 0
using namespace std;
int64_t MOD = 1000000007;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int n, res = 0;
  cin >> n;
  REP(i,n) {
    int a, b;
    cin >> a >> b;
    res += b-a;
  }
  cout << res + n << endl;
  return 0;
}
//templete by private_yusuke
//  [cpp]
#include <bits/stdc++.h>

#define REP(i, x) REPI(i, 0, x)
#define REPI(i, a, b) for (int i = int(a); i < int(b); ++i)
#define ALL(x) (x).begin(), (x).end()

typedef long long ll;
using namespace std;

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

  int N;
  cin >> N;
  ll ans = 0;
  REP(i, N) {
    int l, r;
    cin >> l >> r;
    ans += (r - l + 1);
  }

  cout << ans << endl;

  return 0;
}
//  [cpp]
#include <cstdio>
#include <bits/stdc++.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <cmath>
#include <functional>
#include <vector>
#include <stack>
#include <queue>
#include <map>
using ll = long long;
using namespace std;

void solve(){

}
int main (){
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n;
    int cnt;
    cin >> n;
    cnt = 0;
    for (int i=0;i<n;i++){
        int a,b;
        cin >> a>>b;
        int c = b-a+1;
        cnt += c;

    }
    cout << cnt;


    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
int main(){
  int n;
  cin>>n;
  vector<int> l(n);
  vector<int> r(n);
  for(int i=0;i<n;i++)
    cin>>l.at(i)>>r.at(i);
  int c=0;
  for(int x=1;x<=100000;x++){
    for(int i=0;i<n;i++){
      if(l.at(i)<=x&&x<=r.at(i)){
        c++;
        break;
      }
    }
  }
  cout<<c<<endl;
}
//  [cpp]
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <vector>

#define mod 1000000007

using namespace std;
using ll = long long;

void solve() {
    int sum = 0;
    int n;
    cin >> n;
    int l[n], r[n];
    for(int i = 0; i < n; i++){
        cin >> l[i] >> r[i];
        sum += r[i] - l[i] + 1;
    }
    cout << sum << endl;
}

int main() {
    solve();
    return 0;
}