Problem:
 Score : 600 points    Problem Statement Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N .
Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N , A_i \leq B_i holds:   Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y .       Constraints  2 \leq N \leq 10^5  1 \leq A_i,B_i \leq 10^9         Input Input is given from Standard Input in the following format:  N  A_1  A_2  ...  A_N  B_1  B_2  ...  B_N       Output If the objective is achievable, print Yes ; if it is not, print No .        Sample Input 1 3
1 3 2
1 2 3      Sample Output 1 Yes  We should swap the values of A_2 and A_3 .       Sample Input 2 3
1 2 3
2 2 2      Sample Output 2 No       Sample Input 3 6
3 1 2 6 3 4
2 2 8 3 4 3      Sample Output 3 Yes

Solution (Python):

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


def count_loop(start, idx_map):
    count = 0
    idx = start
    while True:
        idx = idx_map[idx]
        count += 1
        if idx == 0:
            break
    return count


A, B = zip(*sorted(zip(A, B), key=lambda x: x[1]))
idx_map = sorted(range(N), key=lambda i: A[i])
A = sorted(A)

check_1 = all(A[i] <= B[i] for i in range(N))
check_2 = any(A[i + 1] <= B[i] for i in range(N - 1))
check_3 = count_loop(0, idx_map) <= N - 2

if check_1 and (check_2 or check_3):
    print("Yes")
else:
    print("No")

Solution (Python):
import sys
input = sys.stdin.readline

n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = sorted(zip(B, A))
B, A = zip(*C)
D = sorted((a, i) for i, a in enumerate(A))
E, indices = zip(*D)
for e, b in zip(E, B):
  if e > b:
    print("No")
    exit()
S = {0}
now = 0
for _ in range(n-1):
  if indices[now] in S:
    print("Yes")
    exit()
  now = indices[now]
  S.add(now)
for i in range(n-1):
  if E[i+1] <= B[i]:
    print("Yes")
    exit()
print("No")

Solution (Python):
import sys
input = sys.stdin.readline

n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = sorted(zip(B, A))
B, A = zip(*C)
D = sorted((a, i) for i, a in enumerate(A))
E, indices = zip(*D)
for e, b in zip(E, B):
  if e > b:
    print("No")
    exit()
S = {0}
now = 0
for _ in range(n-1):
  if indices[now] in S:
    print("Yes")
    exit()
  now = indices[now]
  S.add(now)
for i in range(n-1):
  if E[i+1] <= B[i]:
    print("Yes")
    exit()
print("No")

Solution (Python):
n = int(input())
a = [ [int(s),i]  for i,s in enumerate(input().split())]
b = [ [int(s),i]  for i,s in enumerate(input().split())]
a.sort(reverse=True)
b.sort(reverse=True)

go = [-1] * n

b_ind = 0
ans = 'No'
for a_ind, (j,j_ind) in enumerate(a):
    while(b[b_ind][0] >= j ):
        b_ind += 1

        if(b_ind == n)&(a_ind < n-1):
            print('Yes')
            exit()

        if(b_ind == n):
            break

    if(b_ind == a_ind):
        print('No')
        exit()

    if(b_ind > a_ind+1):
        ans = 'Yes'

    go[j_ind] = b[a_ind][1]


now = 0
cnt = 0
for _ in range(n-1):
    now = go[now]
    cnt += 1
    if(now==0):
        print('Yes')
        exit()

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    
    class UnionFind():
        """
        parents : 親要素(findしない場合は根ではないことの注意)，根の場合は"-(要素数）"
        find(x):要素xの属するグループの根を返す
        size(x):要素xの属するグループの要素数を返す
        same(x,y):x,yが同じグループに属しているか返す
        members(x):要素xが属するグループに属する要素をリストで返す
        roots:全ての根の要素を返す
        group_count():グループの数を返す
        all_group_members():{根要素：[そのグループに含まれる要素のリスト]}の辞書を返す
        """
        def __init__(self, n):
            self.n = n
            self.parents = [-1] * n

        def find(self, x):
            
            if self.parents[x] < 0:
                return x
            else:
                self.parents[x] = self.find(self.parents[x])
                return self.parents[x]

        def union(self, x, y):
            x = self.find(x)
            y = self.find(y)

            if x == y:
                return

            if self.parents[x] > self.parents[y]:
                x, y = y, x

            self.parents[x] += self.parents[y]
            self.parents[y] = x

        def size(self, x):
            return -self.parents[self.find(x)]

        def same(self, x, y):
            return self.find(x) == self.find(y)

        def members(self, x):
            root = self.find(x)
            return [i for i in range(self.n) if self.find(i) == root]

        def roots(self):
            return [i for i, x in enumerate(self.parents) if x < 0]

        def group_count(self):
            return len(self.roots())

        def all_group_members(self):
            return {r: self.members(r) for r in self.roots()}

        def __str__(self):
            return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
        
    
    mod=10**9+7
    N=I()
    A=LI()
    B=LI()
    
    A,B=zip(*sorted(zip(A,B)))
    
    
    
    
    
    
    
    
    
    
    A1=sorted(A)
    B1=sorted(B)
    
    from collections import defaultdict
    dd = defaultdict(int)
    
    
    
    for i in range(N):
        dd[B1[i]]=i
    
    flag=1
    
    
    for i in range(N):
        if B1[i]<A1[i]:
            flag=0
            break
        
    flag2=0
    
    for i in range(N-1):
        if B1[i]>=A1[i+1]:
            flag2=1
            break
        
    flag3=0
    uf=UnionFind(N)
    
    for i in range(N):
        a=dd[B[i]]
        b=dd[B1[i]]
        uf.union(a,b)
    
    if uf.group_count()==1:
        flag3=1
        
    if flag2==0 and flag3:
        flag=0
        
        
    if flag==1:
        print("Yes")
    else:
        print("No")
    
  
    

main()

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
A=[(A[i],i) for i in range(N)]
B=[(B[i],i) for i in range(N)]

check=True
Ainc=True
Binc=True
ABinc=True
A.sort()
B.sort()

for i in range(N):
    if A[i][0]>B[i][0]:
        check=False
    if i>0:
        if A[i-1]==A[i]:
            Ainc=False
        if B[i-1]==B[i]:
            Binc=False
        if B[i-1]>=A[i]:
            ABinc=False

if not check:
    print("No")
else:
    if (not Ainc) or (not Binc) or (not ABinc):
        print("Yes")
    else:
        edge=[[] for i in range(N)]
        for i in range(N):
            edge[A[i][1]].append(B[i][1])

        que=[0]
        while True:
            v=que[-1]
            nv=edge[v][0]
            if nv==0:
                break
            else:
                que.append(nv)
        if len(que)==N:
            print("No")
        else:
            print("Yes")

Solution (Python):
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
iA = [(i, A[i]) for i in range(N)]
iB = [(i, B[i]) for i in range(N)]
iA.sort(key=lambda t: t[1])
iB.sort(key=lambda t: t[1])

for i in range(N):
    if iA[i][1]>iB[i][1]:
        print('No')
        exit()

to = [-1]*N

for i in range(N):
    to[iB[i][0]] = iA[i][0]

s = {0}
now = 0

while True:
    now = to[now]
    
    if now in s:
        break
    
    s.add(now)

if len(s)<N:
    print('Yes')
    exit()

for i in range(N-1):
    if iA[i+1][1]<=iB[i][1]:
        print('Yes')
        exit()

print('No')

Solution (Python):
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
ab = [(x,y) for x,y in zip(a,b)]
ab.sort(key = lambda x:x[1])
a = list(list(zip(*ab))[0])
ai = [[a[i],i] for i in range(n)]
flg = 0
if len(set(b)) == n:
  ai.sort()
  for i in range(n):
    ai[i][0] = i
  ai.sort(key = lambda x:x[1])
  idc = list(zip(*ai))[0]
  cnt = 0
  plc = 0
  while True:
    plc = idc[plc]
    cnt += 1
    if plc == 0:
      break
  if cnt == n:
    flg = 1
a.sort()
b.sort()
for x,y in zip(a,b):
  if x > y:
    print("No")
    exit()
if not flg:
  print("Yes")
else:
  for i in range(1,n):
    if a[i] <= b[i-1]:
      print("Yes")
      exit()
  print("No")

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline

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

    A_sorted = sorted(A)
    B_sorted = sorted(B)
    for a, b in zip(A_sorted, B_sorted):
        if a > b:
            print('No')
            exit()
    for i in range(N-1):
        if A_sorted[i+1] <= B_sorted[i]:
            print('Yes')
            exit()

    AB = [(a, b) for a, b in zip(A, B)]
    AB.sort(key=lambda x: x[1])
    A_new = [ab[0] for ab in AB]
    a2i = {a: i for i, a in enumerate(A_new)}
    A_cmp = [0] * N
    for i, a in enumerate(sorted(A_new)):
        A_cmp[a2i[a]] = i
    cnt = 0
    i = 0
    seen = [0] * N
    while True:
        if not seen[i]:
            seen[i] = 1
            cnt += 1
            i = A_cmp[i]
        else:
            break
    if cnt == N:
        print('No')
    else:
        print('Yes')


if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

X = sorted(range(n), lambda i: A[i])
Y = sorted(range(n), lambda i: B[i])

U = [0] * n; V = [0] * n
for i in range(n): U[X[i]] = i
for i in range(n): V[Y[i]] = i


for i in range(n):
  if A[X[i]] > B[Y[i]]:
    print("No")
    exit()


for i in range(n - 1):
  if A[X[i + 1]] <= B[Y[i]]:
    print("Yes")
    exit()


cnt = 0
i = 0
while cnt < n - 1:
  j = X[i]
  i = V[j]
  if i == 0:
    print("Yes")
    exit()
  cnt += 1

print("No")

Solution (Python):
import sys
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = sorted([[a[i], b[i]] for i in range(n)], key=lambda x: x[1])
a = [(x[0], i) for i, x in enumerate(c)]
b = [x[1] for x in c]
a.sort()
for i in range(n):
	if a[i][0] > b[i]:
		print("No")
		sys.exit()
cur, cnt = 0, 0
while a[cur][1] != 0:
	cnt += 1
	cur = a[cur][1]
if cnt < n-1:
	print("Yes")
else:
	for i in range(n-1):
		if a[i+1][0] <= b[i]:
			print("Yes")
			break
	else:
		print("No")

Solution (Python):
def examA():
    N = I()
    ans = (N-1)//2
    print(ans)
    return

def examB():
    N = I()
    D = LI()
    d = Counter(D)
    loop = max(d.keys())
    if D[0]!=0 or d[0]!=1:
        print(0)
        return

    ans = 1; cur = 1
    for i in range(loop+1):
        if d[i]==0:
            print(0)
            return
        for _ in range(d[i]):
            ans *= cur
            ans %= mod2
        cur = d[i]
    print(ans)
    return

def examC():
    class UnionFind():
        def __init__(self, n):
            self.parent = [-1 for _ in range(n)]
            

        def find(self, x):
            
            if self.parent[x] < 0:
                return x
            else:
                self.parent[x] = self.find(self.parent[x])
                return self.parent[x]

        def unite(self, x, y):
            
            x, y = self.find(x), self.find(y)
            if x == y:
                return False
            else:
                if self.size(x) < self.size(y):
                    x, y = y, x
                self.parent[x] += self.parent[y]
                self.parent[y] = x

        def same(self, x, y):
            
            return self.find(x) == self.find(y)

        def size(self, x):
            
            x = self.find(x)
            return -self.parent[x]

        def is_root(self, x):
            
            return self.parent[x] < 0

        def members(self, x):
            
            root = self.find(x)
            return [i for i in range(self.n) if self.find(i) == root]

        def group_count(self):
            
            return len(self.roots())

        def all_group_members(self):
            
            return {r: self.members(r) for r in self.roots()}
    N = I()
    A = LI()
    B = LI()
    indices = [i for i in range(len(B))]
    sorted_indices = sorted(indices, key=lambda i: B[i])
    sorted_B = [B[i] for i in sorted_indices]
    sorted_A = sorted(A)

    d = defaultdict(int)

    for i in range(N):
        d[sorted_A[i]] = sorted_B[i]
        if sorted_A[i]>sorted_B[i]:
            print("No")
            return
    for i in range(N-1):
        if sorted_A[i+1]<=sorted_B[i]:
            print("Yes")
            return
    uf = UnionFind(N)
    indices_A = [i for i in range(len(A))]
    sorted_indices_A = sorted(indices_A, key=lambda i: A[i])
    for i in range(N):
        uf.unite(sorted_indices[i],sorted_indices_A[i])
    if uf.size(0)<N:
        print("Yes")
        return
    print("No")
    return

def examD():
    class Dijkstra(object):
        """
        construct: O(ElogV)
        """

        def __init__(self, edges, start=0):
            """
            :param list of list of list of int edges:
            :param int start=0:
            """
            self.__dist = [inf] * len(edges)
            self.__dist[start] = 0
            self.__calculate(edges, start)

        @property
        def dist(self):
            return self.__dist

        def __calculate(self, edges, start):
            Q = [(0, start)]  
            while (Q):
                dist, v = heapq.heappop(Q)
                if self.dist[v] < dist: continue  
                for u, cost in edges[v]:
                    if self.dist[u] > self.dist[v] + cost:
                        self.__dist[u] = self.dist[v] + cost
                        heapq.heappush(Q, (self.dist[u], u))
    N, M = LI()
    V = [[]for _ in range(N)]
    for _ in range(M):
        l, r, c = LI()
        l -=1; r -=1
        V[l].append((r,c))
    for i in range(N-1):
        V[i+1].append((i,0))

    D = Dijkstra(V)
    ans = D.dist[N-1]
    if ans==inf:
        ans = -1
    print(ans)
    return

def examE():
    N, K = LI()
    ans = [[]for _ in range(N)]


    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LFI(): return list(map(float,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examC()

"""

"""

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

"""
aをsort,bをsortして大小関係を比較したときa[i]>b[i]の場合:No.
a,bをsortする前のindexをai,biとし,a,bをsortした後の同じindexのペアについて
aiからbiへの辺をもったグラフを作る.(aiからbiへswapで移動)
このグラフのサイクルの数(連結成分の数)をxとするとswap回数はn-x回(max:n-1,min:0).これは,最小全域森の辺の数.
よってx>=2の場合:Yes.
x=1の場合,sort後のa,bについてa[i+1]<=b[i]を満たすとき、a[i+1],a[i]を入れ替えても条件を満たす.
よって,これが出来るときx=2になるため,Yes
x=1かつこれが出来ないとき:No
"""
n = I()
a = LI()
b = LI()
a = [(a[i],i) for i in range(n)]
b = [(b[i],i) for i in range(n)]
a.sort()
b.sort()
for i in range(n):
    if b[i][0] < a[i][0]:
        print('No')
        quit()

edges = [None]*n
for i in range(n):
    edges[a[i][1]] = b[i][1]

lst = [None]*n

def dfs(s):
    if lst[s] == None:
        lst[s] = tmp
        dfs(edges[s])
    return

tmp = 0
for i in range(n):
    if lst[i] == None:
        dfs(i)
        tmp += 1

lst = list(Counter(lst).values())
if len(lst) >= 2:
    print('Yes')
    quit()

for i in range(n-1):
    if b[i][0] >= a[i+1][0]:
        print('Yes')
        quit()

print('No')

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = LI()
b = LI()
a = [(a[i],i) for i in range(n)]
b = [(b[i],i) for i in range(n)]
a.sort()
b.sort()
for i in range(n):
    if b[i][0] < a[i][0]:
        print('No')
        quit()

edges = [None]*n
for i in range(n):
    edges[a[i][1]] = b[i][1]

lst = [None]*n

def dfs(s):
    if lst[s] == None:
        lst[s] = tmp
        dfs(edges[s])
    return

tmp = 0
for i in range(n):
    if lst[i] == None:
        dfs(i)
        tmp += 1

lst = list(Counter(lst).values())
if len(lst) >= 2:
    print('Yes')
    quit()

for i in range(n-1):
    if b[i][0] >= a[i+1][0]:
        print('Yes')
        quit()

print('No')

Solution (Python):


class UnionFind:
    def __init__(self, size):
        self.data = [-1] * size
    def find(self, x):
        if self.data[x] < 0:
            return x
        else:
            self.data[x] = self.find(self.data[x])
            return self.data[x]
    def union(self, x, y):
        x, y = self.find(x), self.find(y)
        if x != y:
            if self.data[y] < self.data[x]:
                x, y = y, x
            self.data[x] += self.data[y]
            self.data[y] = x
        return (x != y)
    def same(self, x, y):
        return (self.find(x) == self.find(y))
    def size(self, x):
        return -self.data[self.find(x)]

N, *AB = map(int, open(0).read().split())
A, B = AB[:N], AB[N:]

AI = sorted((a, i) for i, (b, a) in enumerate(sorted(zip(B, A))))

A.sort()
B.sort()

if any(a > b for a, b in zip(A, B)):
    print("No")
    quit()

uf = UnionFind(N)
for j, (a, i) in enumerate(AI):
    uf.union(i, j)

if uf.size(0) != N or any(a <= b for a, b in zip(A[1:], B)):
    print("Yes")
else:
    print("No")

Solution (Python):


class UnionFind:
    def __init__(self, size):
        self.data = [-1] * size
    def find(self, x):
        if self.data[x] < 0:
            return x
        else:
            self.data[x] = self.find(self.data[x])
            return self.data[x]
    def union(self, x, y):
        x, y = self.find(x), self.find(y)
        if x != y:
            if self.data[y] < self.data[x]:
                x, y = y, x
            self.data[x] += self.data[y]
            self.data[y] = x
        return (x != y)
    def same(self, x, y):
        return (self.find(x) == self.find(y))
    def size(self, x):
        return -self.data[self.find(x)]

N, *AB = map(int, open(0).read().split())
A, B = AB[:N], AB[N:]

AI = sorted((a, i) for i, (b, a) in enumerate(sorted(zip(B, A))))

A.sort()
B.sort()

if any(a > b for a, b in zip(A, B)):
    print("No")
    quit()


uf = UnionFind(N)
for j, (a, i) in enumerate(AI):
    uf.union(i, j)

parents = {uf.find(i) for i in range(N)}
if len(parents) > 1:
    print("Yes")
    quit()

if any(a <= b for a, b in zip(A[1:], B)):
    print("Yes")
else:
    print("No")

Solution (Python):
n = int(input())
lsa = list(map(int, input().split()))
lsb = list(map(int, input().split()))

ls = [[a, b] for a, b in zip(lsa, lsb)]
ls.sort(key=lambda x: x[1])
lsa = [l[0] for l in ls]
lsb = [l[1] for l in ls]

lsasort = sorted(lsa)
for i in range(n):
    if lsasort[i]>lsb[i]:
        flag = False
        break
else:
    flag = True

if flag:
    lscycle = [[p, q] for p, q in zip(range(n), lsa)]
    lscycle.sort(key=lambda x: x[1])

    count=0
    idx=0
    while True:
        idx=lscycle[idx][0]
        count+=1
        if idx == 0:
            break

    if count != n:
        flag = True
    else:
        for i in range(n-1):
            if lsasort[i+1] <= lsb[i]:
                flag = True
                break
        else:
            flag = False

if flag:
    print("Yes")
else:
    print("No")

Solution (Python):
N=int(input())
A=[int(i) for i in input().split()]
B=[int(i) for i in input().split()]
X=sorted([(A[i],B[i]) for i in range(N)],key=lambda x:x[1])
A=[X[i][0] for i in range(N)]
B=[X[i][1] for i in range(N)]
C=sorted([(A[i],i) for i in range(N)],key=lambda x:x[0])
for i in range(N):
    if C[i][0]>B[i]:
        print("No")
        exit()
if len(set(A))<N:
    print("Yes")
    exit()
Y=[0 for i in range(N)]
j=0
for i in range(N):
    Y[j]=1
    j=C[j][1]
    
if sum(Y)==N:
    
    
    for i in range(N-1):
        if C[i+1][0]<=X[i][1]:
            print("Yes")
            exit()
    print("No")
else:
    print("Yes")

Solution (Python):
import sys
from bisect import bisect as br
from collections import Counter
readline = sys.stdin.readline

def check(A, B):
    SA = sorted(A)
    SB = sorted(B)
    if any(a > b for a, b in zip(SA, SB)):
        return 'No'
    if all(a <= b for a, b in zip(A, B)):
        return 'Yes'
    if any(br(SA, SB[i]) != i+1 for i in range(N)):
        return 'Yes'
    if len(set(A)) != N or len(set(B)) != N:
        return 'Yes'
    P = [None]*N
    Aidx = Counter()
    Bidx = Counter()
    for i in range(N):
        a = A[i]
        b = B[i]
        Aidx[a] = i
        Bidx[b] = i
        
    for i in range(N):
        sa = SA[i]
        sb = SB[i]
        P[Aidx[sa]] = Bidx[sb]
    visited = set()
    vn = 0
    while vn not in visited:
        visited.add(vn)
        vn = P[vn]
    if len(visited) == N:
        return 'No'
    return 'Yes'

N = int(readline())
A = list(map(int, readline().split()))
B = list(map(int, readline().split()))
print(check(A, B))

Solution (Python):
def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    ab = sorted([[a[i], b[i]] for i in range(n)], key=lambda x: x[1])

    base=[a for a,b in ab]
    
    
    
    ini=10**9+1
    
    basesize=len(base)
    num,depth=1,1
    while num<basesize:
        num*=2
        depth+=1
    num-=1
    
    monoid=min
    
    treesize=num*2+1
    tree=[None]*treesize
    
    for i in range(num,num+basesize):tree[i]=base[i-num]
    for i in range(num+basesize, treesize):tree[i]=ini
    
    for i in range(num-1,-1,-1):
        tree[i]=monoid(tree[2*i+1],tree[2*i+2])
    
    
    def max_index(index_func):
        
        i=0
        while i<num:
            k=2*i+1
            if index_func(tree[k+1]):
                i=k+1
                continue
            if index_func(tree[k]):
                i=k
                continue
            return -1
        return i-num

    
    def min_index(index_func):
        
        i=0
        while i<num:
            k=2*i+1
            if index_func(tree[k]):
                i=k
                continue
            if index_func(tree[k+1]):
                i=k+1
                continue
            return -1
        return i-num

    
    def search(lower,upper):
        
        ret=ini
        l=lower+num
        r=upper+num
        while l<r:
            if r%2==0:
                r-=1
                ret=monoid(ret,tree[r])
            if l%2==0:
                ret=monoid(ret,tree[l])
                l+=1
            l//=2
            r//=2
        return ret

    
    def update(index,new_value):
        i=index+num
        tree[i]=new_value
        while i!=0:
            i=(i-1)//2
            temp=monoid(tree[2*i+1],tree[2*i+2])
            if tree[i]!=temp:
                tree[i]=temp
                continue
            break
    
    cnt = 0
    for i in range(n):
        a,b=ab[i][0],ab[i][1]
        if a > b:
            t = max_index(lambda x:x<=b)
            if t <= i:
                print("No")
                return 0
            update(i, a)
            update(t, a)
            ab[i][0], ab[t][0] = ab[t][0], a
            cnt+=1
    if cnt <= n - 2:
        print("Yes")
    else:
        print("No")
main()

Solution (Python):
def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    ab = sorted([[a[i], b[i]] for i in range(n)], key=lambda x: x[1])

    class segtree():
        def __init__(self,base,monoid,ini):
            
            
            
            self.ini=ini
            
            self.basesize=len(base)
            self.num,self.depth=1,1
            while self.num<self.basesize:
                self.num*=2
                self.depth+=1
            self.num-=1
            
            self.monoid=monoid
            
            self.treesize=self.num*2+1
            self.tree=[None]*self.treesize
            
            for i in range(self.num, self.num+self.basesize):self.tree[i]=base[i-self.num]
            for i in range(self.num+self.basesize, self.treesize):self.tree[i]=ini
            
            for i in range(self.num-1,-1,-1):
                self.tree[i]=monoid(self.tree[2*i+1],self.tree[2*i+2])
        
        
        def max_index(self,index_func):
            
            i=0
            while i<self.num:
                k=2*i+1
                if index_func(self.tree[k+1]):
                    i=k+1
                    continue
                if index_func(self.tree[k]):
                    i=k
                    continue
                return -1
            return i-self.num
    
        
        def min_index(self,index_func):
            
            i=0
            while i<self.num:
                k=2*i+1
                if index_func(self.tree[k]):
                    i=k
                    continue
                if index_func(self.tree[k+1]):
                    i=k+1
                    continue
                return -1
            return i-self.num
    
        
        def search(self,lower,upper):
            
            ret=self.ini
            l=lower+self.num
            r=upper+self.num
            while l<r:
                if r%2==0:
                    r-=1
                    ret=self.monoid(ret,self.tree[r])
                if l%2==0:
                    ret=self.monoid(ret,self.tree[l])
                    l+=1
                l//=2
                r//=2
            return ret
    
        
        def update(self,index,new_value):
            i=index+self.num
            self.tree[i]=new_value
            while i!=0:
                i=(i-1)//2
                temp=self.monoid(self.tree[2*i+1],self.tree[2*i+2])
                if self.tree[i]!=temp:
                    self.tree[i]=temp
                    continue
                break
    
    s=segtree([a for a,b in ab],min,10**9+1)
    cnt = 0
    for i in range(n):
        a,b=ab[i][0],ab[i][1]
        if a > b:
            t = s.max_index(lambda x:x<=b)
            if t <= i:
                print("No")
                return 0
            s.update(i, a)
            s.update(t, a)
            ab[i][0], ab[t][0] = ab[t][0], a
            cnt+=1
    if cnt <= n - 2:
        print("Yes")
    else:
        print("No")
    
main()

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
l = list(zip(b, a))
 
a.sort()
b.sort()
for i in range(n):
  if a[i] > b[i]:
    print('No')
    exit()

ptr, pos = {}, {}
for i in range(n):
  if i > 0 and a[i] <= b[i - 1]:
    print('Yes')
    exit()
  ptr[l[i][1]] = l[i][0]
  pos[b[i]] = i

sta, now, cnt = a[0], a[0], 1
while True:
  now = a[pos[ptr[now]]]
  if now == sta:
    break
  cnt += 1
if cnt == n:
  print('No')
else:
  print('Yes')

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

aa = [[a[i], i] for i in range(n)]
bb = [[b[i], i] for i in range(n)]

aa.sort()
bb.sort()

flag = 0
for i in range(n):
    if aa[i][0] > bb[i][0]:
        print("No")
        exit(0)
    if i and aa[i][0] <= bb[i - 1][0]:
        flag = 1

if flag:
    print("Yes")
    exit(0)

sta = [0] * 100005

from bisect import *
from collections import defaultdict

mp = defaultdict(int)

pos = 0
cnt = 1
while cnt <= n - 1:
    sta[pos] = 1
    
    pos = bisect_left(bb, [a[pos],-1])
    pos = bb[pos][1]
    cnt += 1
    if sta[pos] and cnt <= n - 1:
        print("Yes")
        exit(0)

print("No")

Solution (Python):
import numpy as np

n = int(input())
a = np.array(input().split(), dtype=np.int)
b = np.array(input().split(), dtype=np.int)
arg = np.argsort(b)
a = a[arg]
b = b[arg]
arg = np.argsort(a)
if np.all(a[arg] <= b):
  i = arg[0]
  cycle_size = 1
  while i != 0:
    i = arg[i]
    cycle_size += 1
  if cycle_size == n and np.all(a[arg[1:]] > b[:-1]):
    print('No')
  else:
    print('Yes')
else:
  print('No')

Solution (Python):
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return " ".join(map(str,x))
def max2(x): 
    return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""



n = onem()
A = l()
B = l()

def count(start,id):
    co = 0
    s = start

    while True:
        s = id[s]
        co += 1
        if s == 0:
            break
    return co

L = []

for i in range(n):
    L.append([A[i],B[i]])
L.sort(key=lambda x:x[1])
p = sorted(range(n) , key = lambda i:L[i][0])

A.sort()



bo1 = all(A[i] <= L[i][1] for i in range(n))
bo2 = any(A[i+1] <= L[i][1] for i in range(n-1))
bo3 = count(0,p) <= n-2

print("Yes" if (bo1 and (bo2 or bo3)) else "No")

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

def count_loop(start, idx_map):
    count = 0
    idx = start
    while True:
        idx = idx_map[idx]
        count += 1
        if idx == 0:
            break
    return count

A, B = zip(*sorted(zip(A, B), key=lambda x: x[1]))
idx_map = sorted(range(N), key=lambda i: A[i])
A = sorted(A)

check_1 = all(A[i] <= B[i] for i in range(N))
check_2 = any(A[i + 1] <= B[i] for i in range(N - 1))
check_3 = count_loop(0, idx_map) <= N - 2
print("Yes" if check_1 and (check_2 or check_3) else "No")