You play a computer game. In this game, you lead a party of $m$ heroes, and you have to clear a dungeon with $n$ monsters. Each monster is characterized by its power $a_i$. Each hero is characterized by his power $p_i$ and endurance $s_i$.

The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.

When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $k$ monsters, the hero fights with the monster $k + 1$). When the hero fights the monster, there are two possible outcomes:

  if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends;  otherwise, the monster is defeated. 

After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $i$-th hero cannot defeat more than $s_i$ monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.

Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 10^5$) — the number of test cases. Then the test cases follow.

The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of monsters in the dungeon.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the power of the $i$-th monster.

The third line contains one integer $m$ ($1 \le m \le 2 \cdot 10^5$) — the number of heroes in your party.

Then $m$ lines follow, each describing a hero. Each line contains two integers $p_i$ and $s_i$ ($1 \le p_i \le 10^9$, $1 \le s_i \le n$) — the power and the endurance of the $i$-th hero.

It is guaranteed that the sum of $n + m$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case print one integer — the minimum number of days you have to spend to defeat all of the monsters (or $-1$ if it is impossible).


-----Example-----
Input
2
6
2 3 11 14 1 8
2
3 2
100 1
5
3 5 100 2 3
2
30 5
90 1

Output
5
-1

Difficulty: interview

Starter code:

Solutions:
import sys
input = sys.stdin.readline
import bisect

t=int(input())

for testcases in range(t):
    n=int(input())
    A=list(map(int,input().split()))
    m=int(input())
    PS=[tuple(map(int,input().split())) for i in range(m)]

    PS.sort()
    K=[PS[-1]]

    for a,b in PS[::-1][1:]:
        if b<=K[-1][1]:
            continue
        else:
            K.append((a,b))

    K.reverse()

    ANS=1
    count=0
    countmax=n+1
    LEN=len(K)
    for a in A:
        x=bisect.bisect_left(K,(a,0))
        if x==LEN:
            print(-1)
            break
        elif K[x][1]>=count+1 and countmax>=count+1:
            count+=1
            countmax=min(countmax,K[x][1])
        else:
            ANS+=1
            count=1
            countmax=K[x][1]

        #print(a,count,countmax,ANS)
    else:
        print(ANS)
            
        
        


import sys
input = sys.stdin.readline
T = int(input())
Ans = []
for _ in range(T):
    N = int(input())  # モンスターの数
    A = list(map(int, input().split()))  # モンスターのパワー
    M = int(input())  # ヒーローの数
    PS = [list(map(int, input().split())) for _ in range(M)]  # パワーと耐久
    # モンスターのパワーがヒーローのパワーより大きいとヒーローの負け
    # S は 1 日に倒せるモンスターの数の上限

    # L[n] := n 体倒せるヒーローの最大パワー
    L = [0] * (N+1)
    for p, s in PS:
        L[s] = max(L[s], p)
    for i in range(N-1, -1, -1):
        L[i] = max(L[i], L[i+1])
    ans = 1
    cnt = 1
    ma = 0
    if L[1] < max(A):
        Ans.append(-1)
        continue
    for a in A:
        ma = max(ma, a)
        if L[cnt] < ma:
            cnt = 1
            ans += 1
            ma = a
        cnt += 1
    Ans.append(ans)

print("\n".join(map(str, Ans)))


3

import os
import sys


def main():
    T = read_int()
    for _ in range(T):
        N = read_int()
        A = read_ints()
        M = read_int()
        H = [tuple(read_ints()) for _ in range(M)]
        print(solve(N, A, M, H))


def solve(N, A, M, H):
    H.sort(key=lambda h: (h[1], -h[0]))
    spow = [0] * (N + 1)
    s0 = 0
    for p, s in H:
        if s0 == s:
            continue
        spow[s] = p
        s0 = s

    maxp = 0
    for d in range(N, -1, -1):
        maxp = max(maxp, spow[d])
        spow[d] = maxp

    ans = 0
    maxa = A[0]
    if A[0] > spow[1]:
        return -1
    start = 0
    for i, a in enumerate(A[1:]):
        if a > spow[1]:
            return -1
        i += 1
        days = i - start + 1
        maxa = max(maxa, a)
        if spow[days] < maxa:
            ans += 1
            maxa = a
            start = i
    return ans + 1


###############################################################################
# AUXILIARY FUNCTIONS

DEBUG = 'DEBUG' in os.environ


def inp():
    return sys.stdin.readline().rstrip()


def read_int():
    return int(inp())


def read_ints():
    return [int(e) for e in inp().split()]


def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)


def __starting_point():
    main()

__starting_point()

from sys import stdin
input = stdin.readline
q = int(input())
for rew in range(q):
	n = int(input())
	monster = list(map(int,input().split()))
	m = int(input())
	rycerz = [list(map(int,input().split())) for i in range(m)]
	rycerz.sort()
	rycerz.reverse()
	p = [a[0] for a in rycerz]
	s = [a[1] for a in rycerz]
	maxendu = [-1] * m
	maxendu[0] = s[0]
	if max(p) < max(monster):
		print(-1)
	else:
		for i in range(1, m):
			maxendu[i] = max(maxendu[i-1], s[i])
		days = 0
		poz = 0
		while True:
			if poz >= n:
				print(days)
				break
			best_potwor = -1
			kroki = 0
			while True:
				if poz + kroki >= n:
					break
				best_potwor = max(monster[poz + kroki], best_potwor)
				#tyle krokow robimy i taki best potwor
				l = 0
				pr = m - 1
				while abs(pr-l) > 0:
					sr = (l + pr + 1) // 2
					if p[sr] >= best_potwor:
						l = sr
					else:
						pr = sr - 1
				sr = (pr + l) // 2
				if maxendu[sr] >= kroki + 1:
					kroki += 1
				else:
					kroki -= 1
					break
			days += 1
			poz += kroki
			poz += 1

import sys
import bisect
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = 10**9

class RMQ:
    def __init__(self, a):
        self.n = len(a)
        self.size = 2**(self.n - 1).bit_length()
        self.data = [0] * (2*self.size-1)
        self.initialize(a)

    # Initialize data
    def initialize(self, a):
        for i in range(self.n):
            self.data[self.size + i - 1] = a[i]
        for i in range(self.size-2, -1, -1):
            self.data[i] = max(self.data[i*2 + 1], self.data[i*2 + 2])

    # Update ak as x
    def update(self, k, x):
        k += self.size - 1
        self.data[k] = x
        while k > 0:
            k = (k - 1) // 2
            self.data[k] = max(self.data[2*k+1], self.data[2*k+2])

    # max value in [l, r)
    def query(self, l, r):
        L = l + self.size; R = r + self.size
        s = 0
        while L < R:
            if R & 1:
                R -= 1
                s = max(s, self.data[R-1])
            if L & 1:
                s = max(s, self.data[L-1])
                L += 1
            L >>= 1; R >>= 1
        return s

t = int(input())
for i in range(t):
    n = int(input())
    a = [int(item) for item in input().split()]
    m = int(input())
    brave = []
    for j in range(m):
        pp, ss = [int(item) for item in input().split()]
        brave.append((pp, ss))
    brave.sort(reverse=True)
    p = []
    s = []
    for pp, ss in brave:
        p.append(pp)
        s.append(ss)
    s_rmq = RMQ(s)
    a_rmq = RMQ(a)
    p.reverse()
    s.reverse()
    max_step = max(s)
    days = 0
    curr = 0
    while curr < n:
        # Search step size
        l = 0; r = min(n - curr, max_step) + 1
        while r - l > 1:
            mid = (l + r) // 2
            max_monster = a_rmq.query(curr, curr+mid)
            index = m - bisect.bisect_left(p, max_monster)
            walkable = s_rmq.query(0, index)
            if walkable >= mid:
                l = mid
            else:
                r = mid
        if l == 0:
            days = -1
            break
        else:
            days += 1
            curr += l
    print(days)

import sys
for _ in range(int(input())):
    n = int(sys.stdin.readline())
    mons = list(map(int, sys.stdin.readline().split()))
    m = int(sys.stdin.readline())
    _heros = sorted((tuple(map(int, sys.stdin.readline().split())) for _ in range(m)), reverse=True)
    max_s = 0
    pows = []
    endu = []
    for i in range(m):
        if max_s >= _heros[i][1]:
            continue
        max_s = max(max_s, _heros[i][1])
        pows.append(_heros[i][0])
        endu.append(_heros[i][1])

    pows.append(0)
    endu.append(10**9)
    i = 0
    for ans in range(1, 10**9):
        hero_i = 0
        power = pows[0]
        mons_power = 0

        if power < mons[i]:
            print(-1)
            break
        for j in range(1, n-i+1):
            if endu[hero_i] < j:
                hero_i += 1
                power = pows[hero_i]

            mons_power = max(mons_power, mons[i])
            if power < mons_power:
                break
            i += 1
        else:
            print(ans)
            break


"""
NTC here
"""
from sys import stdin

def iin(): return int(stdin.readline())
 
 
def lin(): return list(map(int, stdin.readline().split()))


# range = xrange
# input = raw_input


def main():
    t=iin()
    while t:
        t-=1
        n=iin()
        a=lin()
        m=iin()
        h=[lin()[::-1] for i in range(m)]
        h.sort(reverse=True)
        a1=[[j,i] for i,j in enumerate(a)]
        a2=[-1]*n
        a1.sort()
        i=0
        j=0
        while j<n and i<m:
            if h[i][1]>=a1[j][0]:
                a2[a1[j][1]]=i
                j+=1
            else:
                i+=1
        if -1 in a2:
            print(-1)
        else:
            dp=[1]*n
            for i in range(1,n):
                ad=[0]
                ch=0
                if h[a2[i]][0]>dp[i-1]:
                    if h[a2[i]][1]>=h[a2[i-1]][1]:
                        ad.append(dp[i-1])
                        ch+=1
                if h[a2[i-1]][0]>dp[i-1]:
                    if h[a2[i-1]][1]>=h[a2[i]][1]:
                        ad.append(dp[i-1])
                        if ch==0:
                            a2[i]=a2[i-1]
                dp[i]+=max(ad)
            print(dp.count(1))
            # print(dp,a2,h)













main()
# try:
#     main()
# except Exception as e: print(e)


import sys
input = lambda: sys.stdin.readline().strip()
print = lambda s: sys.stdout.write(s)

t = int(input())
for i in range(t):
    n = int(input())
    ls1 = list(map(int, input().split()))
    m = int(input())
    ls2 = []
    for i in range(m):
        ls2.append(tuple(map(int, input().split())))
    if max(ls1)>max(i[0] for i in ls2):
        print('-1\n')
    else:
        temp = {}
        for i in range(1, n+1):
            temp[i] = 0
        for i in ls2:
            try:
                temp[i[1]] = max(temp[i[1]], i[0])
            except:
                temp[i[1]] = i[0]
        d = {}
        d[n] = temp[n]
        for k in range(n-1, 0, -1):
            d[k] = max(d[k+1], temp[k])
        i = 0
        cnt = 1
        ans = 1
        M = ls1[0]
        while True:
            if d[cnt]>=M:
                cnt+=1
                i+=1
                if i==n:
                    break
                M = max(M, ls1[i])
            else:
                ans+=1
                cnt = 1
                M = ls1[i]
        print(str(ans)+'\n')


import math
import sys
from bisect import bisect_right as bs
for _ in range(int(input())):
    n=int(sys.stdin.readline())
    a=list(map(int,sys.stdin.readline().split()))
    m=int(input())
    ma=-1
    h=[0]*(n+1)
    for i in range(m):
        x,y=list(map(int,sys.stdin.readline().split()))
        ma=max(ma,x)
        h[y]=max(h[y],x)
    
    for i in range(n-1,0,-1):
        h[i]=max(h[i+1],h[i])
    # print(h)    
    if ma<max(a):
        print(-1)
    else:
        ma=-1
        prev=0
        ans=1
        i=0
        while i<n:
            ma=max(a[i],ma)
            # print(ma,i,ans)
            if h[i-prev+1]<ma:
                prev=i
                ans+=1
                ma=-1
            else:
                i+=1
        print(ans)        


from collections import *
from bisect import bisect_left as bl
import sys
input = sys.stdin.readline
 
 
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def st():return input().rstrip('\n')
def val():return int(input())
def stli():return [int(i) for i in input().rstrip('\n')]
 
 
 
 
for _ in range(val()):
    n = val()
    a = li()
    # print(a)
    m = val()
    h = []
    visited = defaultdict(int)
    for i in range(m):
        x,y = li()
        visited[x] = max(visited[x],y)
    h = []
    for i in visited:
        h.append([i,visited[i]])
    h.sort(reverse = 1)
    endurance = {}
    m = len(h)
    currmax = -float('inf')
    for i in range(m):
        if h[i][1]>currmax:
            currmax = max(currmax,h[i][1])
            endurance[h[i][0]] = currmax
        
 
    power = sorted(list(endurance))
    # print(power,endurance)
    totdays = 0
    i = 0
    while i<n:
        ind = bl(power,a[i])
        if ind == len(power):
            totdays = -1
            break
 
        cou = 0
        while i<n:
            while ind<len(power) and  a[i]>power[ind]:
                ind+=1
            if ind == len(power):
                totdays = -1
                break
            if endurance[power[ind]] <= cou:
                break
            i+=1
            cou += 1

        if totdays == -1:break
        totdays += 1
    print(totdays)

from collections import *
from bisect import bisect_left as bl
import sys
input = sys.stdin.readline
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def val():return int(input())
 
for _ in range(val()):
    n = val();a = li();m = val();h = [];visited = defaultdict(int)
    for i in range(m):
        x,y = li()
        visited[x] = max(visited[x],y)
    
    endurance, currmax, h = {}, -float('inf'), sorted([[i,visited[i]] for i in visited],key = lambda x:x[0],reverse = 1)
    
    for i in range(len(h)):
        if h[i][1]>currmax:
            currmax = max(currmax,h[i][1])
            endurance[h[i][0]] = currmax
 
    power = sorted(list(endurance))

    totdays = i = 0
    while i<n:
        ind = bl(power,a[i])
        if ind == len(power):
            totdays = -1
            break
        cou = 0
        while i<n:
            while ind<len(power) and  a[i]>power[ind]:ind+=1
            if ind == len(power):
                totdays = -1;break
            if endurance[power[ind]] <= cou:break
            i+=1
            cou += 1
        if totdays == -1:break
        
        totdays += 1
    
    print(totdays)

import sys
input = sys.stdin.readline
T = int(input())
Ans = []
for _ in range(T):
    N = int(input()) 
    A = list(map(int, input().split()))
    M = int(input()) 
    PS = [list(map(int, input().split())) for _ in range(M)]
    L = [0] * (N+1)
    for p, s in PS:
        L[s] = max(L[s], p)
    for i in range(N-1, -1, -1):
        L[i] = max(L[i], L[i+1])
    ans = 1
    cnt = 1
    ma = 0
    if L[1] < max(A):
        Ans.append(-1)
        continue
    for a in A:
        ma = max(ma, a)
        if L[cnt] < ma:
            cnt = 1
            ans += 1
            ma = a
        cnt += 1
    Ans.append(ans)
 
print("\n".join(map(str, Ans)))

import sys
sin = sys.stdin
t = int(sin.readline())
for _ in range(t):
    n = int(sin.readline())
    monpows = [int(x) for x in sin.readline().split()]
    m = int(sin.readline())
    endtopow = dict()
    maxhero = 0
    for _ in range(m):
        h = [int(x) for x in sin.readline().split()]
        maxhero = max(maxhero, h[0])
        if h[1] in endtopow:
            endtopow[h[1]] = max(h[0], endtopow[h[1]])
        else:
            endtopow[h[1]] = h[0]
    endurances = [0 for x in range(n+2)]
    for i in range(len(endurances) - 2, -1, -1):
        if i in endtopow:
            endurances[i] = max(endurances[i+1], endtopow[i])
        else:
            endurances[i] = endurances[i+1]
    days = 0
    msofar = 0
    maxpow = 0
    i = 0
    cant = False
    while i < n:
        maxpow = max(maxpow, monpows[i])
        if maxpow > maxhero:
            cant = True
            break
        if maxpow <= endurances[msofar + 1]:
            i += 1
            msofar += 1
        else:
            msofar = 0
            maxpow = 0
            days += 1
    days += 1
    if not cant:
        print(days)
    else:
        print(-1)


t = int(input())
for _ in range(t):
    # print()
    n = int(input())
    a = list(map(int, input().split()))
    m = int(input())
    b = [tuple(map(int, input().split())) for __ in range(m)]
    ans = 1
    # mx[i] stores the max power of the hero that can go i steps
    mx = [0] * (n + 1)
    for p, s in b:
        mx[s] = max(mx[s], p)
    for i in range(n-1, -1, -1):
        mx[i] = max(mx[i], mx[i+1])

    # print(a)
    # print(b)
    if mx[1] < max(a):
        print(-1)
    else:
        index = 1
        ma = 0
        for mon in a:
            ma = max(mon, ma)
            if mx[index] < ma:
                index = 1
                ans += 1
                ma = mon
            index += 1
        # ind = 0
        # while ind < n:
        #     temp = 0
        #     for i in range(m):
        #         l = 0
        #         if b[i][0] <= temp:
        #             break
        #         if ind + temp == n:
        #             break
        #         # print(a[ind:len(a)])
        #         end = min(ind+b[i][0], len(a))
        #         for j in range(ind, end):
        #             if a[j] > b[i][1]:
        #                 break
        #             l += 1
        #         if l > temp:
        #             temp = l
        #     # print(temp, ind)
        #     ind += temp
        #     ans += 1
        #     # print(a, temp)
        print(ans)


import sys
def I():
        return sys.stdin.readline().rstrip()
for _ in range(int(I())):
    n = int(I())
    a = list( map( int, I().split() ) )
    m = int(I())
    pl = sorted([ list( map( int, I().split() ) ) for _ in range( m ) ])
    pln, mxs = [], 0
    for x in pl[::-1]:
        if x[ 1 ] > mxs:
            pln.append( x )
        mxs = max( mxs, x[ 1 ] )
    pl = pln[::-1]
    m = len( pl )
    p, s = list(map( list, list(zip( *pl )) ))
    if max( a ) > max( p ):
        print( -1 )
    else:
        days = 0
        c = 0
        d2 = 1
        while d2 <= m:
            d2 *= 2
        d2 //= 2
        while c < n:
            days += 1
            mx = 0
            inday = 0
            while c < n:
                mx = max( mx, a[ c ] )
                inday += 1
                pi = -1
                d = d2
                while d:
                    np = pi + d
                    if np < m and p[ np ] < mx:
                        pi = np
                    d //= 2
                pi += 1
                if pi < m and s[ pi ] >= inday:
                    c += 1
                else:
                    break
        print( days )


t = int(input())

for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    m = int(input())
    h = [tuple(map(int, input().split())) for i in range(m)]
    h.sort(reverse=True)
    new_h = []
    prev = 0
    for p, s in h:
        if s > prev:
            new_h.append((p, s))
            prev = s

    h = new_h
    hum = 0
    res = 1
    cur = 0
    maxp = 0
    for mon in a:
        maxp = max(mon, maxp)
        cur += 1
        if mon > h[0][0]:
            res = -1
            break
        if hum < len(h) and cur > h[hum][1]:
            hum += 1
        if hum == len(h) or maxp > h[hum][0]:
            res += 1
            hum = 0
            cur = 1
            maxp = mon

    print(res)



# -*- coding: utf-8 -*-

import sys
from bisect import bisect_left

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return list(map(int, input().split()))
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

class SegTree:

    def __init__(self, n, func, intv, A=[]):

        self.n = n
        self.func = func
        self.intv = intv
        n2 = 1
        while n2 < n:
            n2 <<= 1
        self.n2 = n2
        self.tree = [self.intv] * (n2 << 1)
        if A:
            for i in range(n):
                self.tree[n2+i] = A[i]
            for i in range(n2-1, -1, -1):
                self.tree[i] = self.func(self.tree[i*2], self.tree[i*2+1])

    def update(self, i, x):

        i += self.n2
        self.tree[i] = x
        while i > 0:
            i >>= 1
            self.tree[i] = self.func(self.tree[i*2], self.tree[i*2+1])

    def query(self, a, b):

        l = a + self.n2
        r = b + self.n2
        s = self.intv
        while l < r:
            if r & 1:
                r -= 1
                s = self.func(s, self.tree[r])
            if l & 1:
                s = self.func(s, self.tree[l])
                l += 1
            l >>= 1
            r >>= 1
        return s

    def get(self, i):
        return self.tree[i+self.n2]

    def all(self):
        return self.tree[1]

def bisearch_max(mn, mx, func):

    ok = mn
    ng = mx
    while ok+1 < ng:
        mid = (ok+ng) // 2
        if func(mid):
            ok = mid
        else:
            ng = mid
    return ok

def check(m):
    mx = st.query(cur, m)
    idx = bisect_left(P, mx)
    if idx == M:
        return False
    _, s = PS[idx]
    scnt = m - cur
    return s >= scnt

ans = []
for _ in range(INT()):
    N = INT()
    A = LIST()
    M = INT()
    PS = []
    for i in range(M):
        p, s = MAP()
        PS.append((p, s))

    PS.sort()
    for i in range(M-1, 0, -1):
        if PS[i][1] > PS[i-1][1]:
            PS[i-1] = (PS[i-1][0], PS[i][1])
    P, _ = list(zip(*PS))
    
    st = SegTree(N, max, 0, A)
    cur = day = 0
    while cur < N:
        res = bisearch_max(cur, N+1, check)
        if res == cur:
            ans.append(str(-1))
            break
        cur = res
        day += 1
    else:
        ans.append(str(day))

print('\n'.join(ans))


import sys
input = sys.stdin.readline

t = int(input())
ANS = []
for _ in range(t):
    n = int(input())
    a = list(map(int,input().split()))
    m = int(input())
    ps = [list(map(int, input().split())) for _ in range(m)]
    p = [0] * (n+1)
    for i in range(m):
        p[ps[i][1]] = max(p[ps[i][1]], ps[i][0])
    for i in range(n)[::-1]:
        p[i] = max(p[i], p[i + 1])
    if p[1] < max(a):
        ANS.append(-1)
        continue
    ans = 0
    mx = 0
    cnt = 0
    i = 0
    for x in a:
        cnt += 1
        mx = max(mx, x)
        if p[cnt] < mx:
            ans += 1
            mx = x
            cnt = 1
    if cnt:
        ans += 1
    ANS.append(ans)

print('\n'.join(map(str, ANS)))


import sys
input = sys.stdin.readline

t = int(input())
ANS = []
for _ in range(t):
    n = int(input())
    a = list(map(int,input().split()))
    m = int(input())
    ps = [list(map(int, input().split())) for _ in range(m)]
    p = [0] * (n+1)
    for i in range(m):
        p[ps[i][1]] = max(p[ps[i][1]], ps[i][0])
    for i in range(n)[::-1]:
        p[i] = max(p[i], p[i + 1])
    if p[1] < max(a):
        print(-1)
        continue
    ans = 0
    mx = 0
    cnt = 0
    i = 0
    for x in a:
        cnt += 1
        mx = max(mx, x)
        if p[cnt] < mx:
            ans += 1
            mx = x
            cnt = 1
    if cnt:
        ans += 1
    print(ans)