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):
import sys
from copy import deepcopy
import itertools
input = sys.stdin.readline

N = int(input())
A0 = list(map(int, input().split()))
B0 = list(map(int, input().split()))




B1 = []
for i, b in enumerate(B0):
	B1.append((b, i))
B1.sort()
A1 = []
B = []
for b, i in B1:
	B.append(b)
	A1.append(A0[i])


A = []
idx = 0
gr = itertools.groupby(B)
for key, group in gr:
    length = len(list(group))
    if length == 1:
        A.append(A1[idx])
    else:
        A_pre = A1[idx:idx+length]
        A_pre.sort()
        A = A + A_pre
    idx += length







C0 = deepcopy(A)
C1 = []
for i, c in enumerate(C0):
	C1.append((c, i))
C1.sort()
C = []
for c, i in C1:
    C.append(c)

for i in range(N):
    if C1[i][0] > B[i]:
        print('No')
        exit()



num_set = set([i for i in range(1, N)])
components = 1
prev = 0
while num_set:
	c, i = C1[prev]
	if i in num_set:
		num_set.discard(i)
		prev = i
	else:
		prev = num_set.pop()
		components += 1



if components != 1:
	print('Yes')
else:
    ok = False
    for i in range(1, N):
        if C[i] <= B[i - 1]:
            ok = True
            break
    if ok:
        print('Yes')
    else:
        print('No')

Solution (Python):
class Unionfind:

    __slots__ = ['parents','sizes']

    def __init__(self, n):
        self.parents = list(range(n))
        self.sizes = [1]*n

    def root(self, x):
        if self.parents[x] == x:
            return x
        else:
            root_x = self.root(self.parents[x])
            self.parents[x] = root_x
            return root_x

    def unite(self, x, y):
        x = self.root(x); y = self.root(y)
        if x == y:
            return
        if self.sizes[x] < self.sizes[y]:
            x, y = y, x
        self.sizes[x] += self.sizes[y]
        self.parents[y] = x

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

    
    def kind(self):
        for v in range(N):
            self.root(v)
        return len(list(set(self.parents)))

    
    def size(self, x):
        self.sizes[x] = self.sizes[self.root(x)]
        return self.sizes[x]

N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
sA = sorted(enumerate(A), key=lambda x : x[1])
sB = sorted(enumerate(B), key=lambda x : x[1])


if not all(a <= b for (i, a), (j, b) in zip(sA, sB)):
    print("No")
    exit()

uf = Unionfind(N)

for (i, a), (j, b) in zip(sA, sB):
    uf.unite(i, j)


if uf.kind() > 1:
    print("Yes")
    exit()




if any(sB[i][1] >= sA[i+1][1] for i in range(N-1)):
    print("Yes")
    exit()



print("No")

Solution (Python):
import numpy as np

N = int(input())
A = np.array(list(map(int,input().split())))
B = np.array(list(map(int,input().split())))
Bsi = np.argsort(B)
A2 = A[Bsi]
Bs = B[Bsi]
A2si = np.argsort(A2)
As = A2[A2si]
C = Bs-As
if any(C[C<0]):
    ans = 'No'
else:
    if all(As[1::]-Bs[:-1:] > 0):
        pi = 0
        i = 0
        while i<N-1:
            pi = A2si[pi]
            if pi == 0:
                ans = 'Yes'
                break
            else:
                i += 1
        else:
            ans = 'No'
    else:
        ans = 'Yes'
        
print(ans)

Solution (Python):
import numpy as np

N = int(input())
A = np.array(list(map(int,input().split())))
B = np.array(list(map(int,input().split())))
Bsi = np.argsort(B)
A2 = A[Bsi]
Bs = B[Bsi]
A2si = np.argsort(A2)
As = A2[A2si]
C = Bs-As
if any(C[C<0]):
    ans = 'No'
else:
    D = A2-As
    if any(D == 0):
        ans = 'Yes'
    elif all(As[1::]-Bs[:-1:] > 0):
        pi = 0
        i = 0
        while i<N-1:
            pi = A2si[pi]
            if pi == 0:
                ans = 'Yes'
                break
            else:
                i += 1
        else:
            ans = 'No'
    else:
        ans = 'Yes'
        
print(ans)

Solution (Python):
from collections import deque
from operator import itemgetter


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

info = [(a[i], b[i]) for i in range(n)]
info = sorted(info, key = itemgetter(1))
for i in range(n):
    a[i], b[i] = info[i]

s = sorted(a)
t = sorted(b)
for i in range(n):
    if s[i] > t[i]:
        print("No")
        exit()

sorted_a = sorted(zip(a, range(len(a))))
graph = [[] for i in range(n)]
for i in range(n):
    u = i
    v = sorted_a[i][1]
    if u != v:
        graph[u].append(v)

used = [False]*n
pos = 0
used[pos] = True
q = deque([pos])
while q:
    pos = q.pop()
    for next_pos in graph[pos]:
        if used[next_pos]:
            continue
        q.append(next_pos)
        used[next_pos] = True

for i in range(n):
    if not used[i]:
        print("Yes")
        exit()

for i in range(n-1):
    if s[i+1] <= t[i]:
        print("Yes")
        exit()

print("No")

Solution (Python):
from operator import itemgetter


class UnionFind:
    def __init__(self, n):
        self.table = [-1] * n

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

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

    def union(self, x, y):
        r1 = self._root(x)
        r2 = self._root(y)
        if r1 == r2:
            return
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2


def solve(n, aaa, bbb):
    aai = sorted(enumerate(aaa), key=itemgetter(1))
    bbi = sorted(enumerate(bbb), key=itemgetter(1))
    uft = UnionFind(n)
    for (ai, a), (bi, b) in zip(aai, bbi):
        if a > b:
            return False
        uft.union(ai, bi)
    if sum(r < 0 for r in uft.table) > 1:
        return True
    return any(a <= b for (ai, a), (bi, b) in zip(aai[1:], bbi))


n = int(input())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))
print('Yes' if solve(n, aaa, bbb) else 'No')

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

ab = [[a[i], b[i]] for i in range(n)]
ab.sort(key=lambda x:x[1])

a = [ab[i][0] for i in range(n)]
b = [ab[i][1] for i in range(n)]

a2 = [[a[i], i] for i in range(n)]
a2.sort(key=lambda x:x[0])

flag1 = 0
for i in range(n):
    if a2[i][0] > b[i]:
        flag1 = 1

flag2 = 1
idx = a2[0][1]
cnt = 0
while idx != 0:
    idx = a2[idx][1]
    cnt += 1

if cnt == n-1:
    for i in range(n-1):
        if a2[i+1][0] <= b[i]:
            flag2=0
            break
else:
    flag2 = 0

if flag1 == 1 or flag2 == 1:
    print('No')
else:
    print('Yes')

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def len_cycle(edge, start=0):
    stack = [start]
    cnt = 0
    pop, push = stack.pop, stack.append
    while stack:
        cnt+=1
        from_ = pop()
        for to in edge[from_]:
            push(to)
            if to == start:
                return cnt
    return 0
def main():
    N=I()
    A=LI()
    B=LI()

    A_with_index = [(a,i) for i,a in enumerate(A)]
    B_with_index = [(b,i) for i,b in enumerate(B)]
    A_with_index.sort()
    B_with_index.sort()

    for i,(a,_) in enumerate(A_with_index):
        b = B_with_index[i][0]
        if a>b:
            print("No")
            return

    B_dict = {}
    for j,(b,i) in enumerate(B_with_index):
        B_dict[j] = i

    edge = [[]for _ in range(N)]
    for i,(a,from_) in enumerate(A_with_index):
        to = B_dict[i]
        edge[from_] += to,

    cycle = len_cycle(edge)
    if cycle != N:
        print("Yes")
        return 
    for i in range(N-1):
        a = A_with_index[i+1][0]
        b = B_with_index[i][0]
        if a<=b:
            print("Yes")
            return
    print("No")




if __name__ == '__main__':
    main()

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

n = int(input())
a = [int(item) for item in input().split()]
b = [int(item) for item in input().split()]


a_s = sorted(a)
b_s = sorted(b)
for i, (aa, bb) in enumerate(zip(a_s, b_s)):
    if aa > bb:
        print("No")
        exit()


for ai1, bi in zip(a_s[1:], b_s):
    if ai1 <= bi:
        print("Yes")
        exit()


ba = []
for i, (aa, bb) in enumerate(zip(a, b)):
    ba.append((bb, aa))
ba.sort()

a_idx = []
for i, (bb, aa) in enumerate(ba):
    a_idx.append((aa, i))
a_idx.sort()

visited = [0] * n
cycle = 0
for i in range(n):
    curr = i
    if visited[curr] == 1:
        continue
    cycle += 1
    while visited[curr] == 0:
        visited[curr] = 1
        curr = a_idx[curr][1]
if cycle > 1:
    print("Yes")
else:
    print("No")

Solution (Python):
n=int(input())
al=list(map(int,input().split()))
bl=list(map(int,input().split()))
ail=[(i,a) for i,a in enumerate(al)]
bil=[(i,b) for i,b in enumerate(bl)]
ail=sorted(ail,key=lambda x:x[1])
bil=sorted(bil,key=lambda x:x[1])
if not all([ail[i][1]<=bil[i][1] for i in range(n)]):
    print('No')
    exit()
if any([ail[i+1][1]<=bil[i][1] for i in range(n-1)]):
    print('Yes')
    exit()
c=[(ail[i][0],bil[i][0]) for i in range(n)]
c=sorted(c)
idx=0
for _ in range(n-1):
    idx=c[idx][1]
    if idx==0:
        print('Yes')
        break
else:
    print('No')

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ba = sorted((y, x) for x, y in zip(a, b))
a = [x for y, x in ba]
b = [y for y, x in ba]




ap = sorted((x, i) for i, x in enumerate(a))


if any(ap[i][0] > b[i] for i in range(n)):
    print('No')
    exit()
if any(ap[i + 1][0] <= b[i] for i in range(n - 1)):
    print('Yes')
    exit()

rep = [ap[i][1] for i in range(n)]
p = 0
c = 0
while True:
    c += 1
    p = rep[p]
    if p == 0:
        break
print(['No', 'Yes'][c != n])

Solution (Python):






from collections import defaultdict
class UnionFind:
    def __init__(self, n):
        class KeyDict(dict):
            
            def __missing__(self,key):
                self[key] = key
                return key
        self.parent = KeyDict()
        self.rank = defaultdict(int)
        self.weight = defaultdict(int)

    
    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            
            
            y = self.find(self.parent[x])           
            self.weight[x] += self.weight[self.parent[x]]   
            self.parent[x] = y      
            return self.parent[x]

    
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        
        if self.rank[x] < self.rank[y]:
            self.parent[x] = y
        else:
            self.parent[y] = x
        
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1

    
    def weighted_union(self, x, y, w):
        
        px = self.find(x)
        py = self.find(y)
        
        
        if self.rank[px] < self.rank[py]:
            self.parent[px] = py
            self.weight[px] = - w - self.weight[x] + self.weight[y]
        else:
            self.parent[py] = px
            self.weight[py] =  w + self.weight[x] - self.weight[y]
        if self.rank[px] == self.rank[py]:
            self.rank[px] += 1
        return 0

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

N = int(input())
As  = list(map(int, input().split()))
Bs  = list(map(int, input().split()))
As_ind = [(a,i) for i,a in enumerate(As)]
Bs_ind = [(b,i) for i,b in enumerate(Bs)]
As_ind.sort()
Bs_ind.sort()



uf = UnionFind(N)
cnt = 0
for A,B in zip(As_ind,Bs_ind):
    
    if A[0] > B[0]:
        print("No")
        exit()
    uf.union(A[1],B[1])


d_ans = defaultdict(int)

for i in range(N):
    root = uf.find(i)
    d_ans[root] += 1
if len(d_ans) >= 2:
    print("Yes")
else:
    
    
    
    for i in range(1,N):
        if As_ind[i][0] <= Bs_ind[i-1][0]:
            print("Yes")
            exit()
    print("No")

Solution (Python):

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ba = sorted((y, x) for x, y in zip(a, b))
a = [x for y, x in ba]
b = [y for y, x in ba]

ap = sorted((x, i) for i, x in enumerate(a))
if any(ap[i][0] > b[i] for i in range(n)):
    print('No')
    exit()
if any(ap[i + 1][0] <= b[i] for i in range(n - 1)):
    print('Yes')
    exit()

rep = [ap[i][1] for i in range(n)]
p = 0
c = 0
while True:
    c += 1
    p = rep[p]
    if p == 0:
        break
print(['No', 'Yes'][c != n])

Solution (Python):
import numpy as np

n = int(input())
a = np.array(list(map(int, input().split())))
b = np.array(list(map(int, input().split())))

a_sort = np.sort(a)
b_sort = np.sort(b)






if (a_sort > b_sort).any():
    print('No')
    exit()


if (a_sort[1:] <= b_sort[:-1]).any():
    print('Yes')
    exit()


index = b.argsort()
a = a[index]
sort_dict = a.argsort().tolist()
start = 0
from_ = start
count = 0
while True:
    count += 1
    from_ = sort_dict[from_]
    if from_ == start:
        break

if count != n:
    print('Yes')
else:
    print('No')

Solution (Python):
import numpy as np

n = int(input())
a = np.array(list(map(int, input().split())))
b = np.array(list(map(int, input().split())))

a_sort = np.sort(a)
b_sort = np.sort(b)






if (a_sort > b_sort).any():
    print('No')
    exit()


if (a_sort[1:] <= b_sort[:-1]).any():
    print('Yes')
    exit()


index = b.argsort()
a = a[index]
sort_dict = a.argsort().tolist()
from_ = 0
count = 0
while True:
    count += 1
    from_ = sort_dict[from_]
    if from_ == 0:
        break

if count != n:
    print('Yes')
else:
    print('No')

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
import numpy as np
a = sorted(A)
b = sorted(B)
a = np.array(a)
b = np.array(b)
A = np.array(A)
B = np.array(B)
if (a<=b).sum()!=N:
  print('No')

else:
  bx = np.argsort(B)
  A = A[bx]
  ax = np.argsort(A)
  dic = {}
  for i,x in enumerate(ax):
    dic[x]=i
    
  m = 0
  c = 0
  while True:
    m = dic[m]
    c += 1
    
    if (m==0) and (c!=N):
      print('Yes')
      exit()
    elif (c==N):
      break
      
  judge = False
  for i in range(N-1):
    if b[i]>=a[i+1]:
      judge = True
      break
      
  if judge:
    print('Yes')
  else:
    print('No')

Solution (Python):



from collections import Counter
def ri():
    return int(input())

def rl():
    return list(input().split())

def rli():
    return list(map(int, input().split()))

def main():
    n = ri()
    la = rli()
    lb = rli()
    lab = []
    for i in range(n):
        lab.append([la[i], lb[i]])

    la.sort()
    lb.sort()
    for i in range(n):
        if la[i] > lb[i]:
            print("No")
            return

    
    lab.sort()
    
    for i in range(n):
        lab[i].append(i)
    
    lab.sort(key=lambda x: x[1])
    
    length = 1
    fr = 0
    to = lab[0][2]
    while to != 0:
        fr = to
        to = lab[fr][2]
        length += 1
    
    if length < n:
        print("Yes")
        return

    
    for i in range(n-1):
        if lb[i] >= la[i+1]:
            print("Yes")
            return
    
    
    print("No")


if __name__ == '__main__':
    main()

Solution (Python):


import sys
import math
import collections
import operator
import numpy

def check_cycle(i_pair):
    i_orig_sorted_dict = {i_orig: i_sort for i_orig, i_sort in i_pair}
    cycle_dict = {}
    for i_orig, i_sort in i_pair:
        i_current = i_orig
        while True:
            if not i_current in cycle_dict:
                cycle_dict[i_current] = i_orig
            else:
                break
            i_current = i_orig_sorted_dict[i_current]
    return len(numpy.unique(list(cycle_dict.values())))


N, = map(int, sys.stdin.readline().rstrip().split(" "))
As = list(map(int, sys.stdin.readline().rstrip().split(" ")))
Bs = list(map(int, sys.stdin.readline().rstrip().split(" ")))
AB_sorted = list(sorted(zip(As, Bs), key=operator.itemgetter(1)))
Bs = list(map(operator.itemgetter(1), AB_sorted))
As_original = list(map(operator.itemgetter(0), AB_sorted))
A_i_pair = [(i_orig, i_sort) for i_sort, (i_orig, value) in enumerate(sorted(enumerate(As_original), key=operator.itemgetter(1)))]
As.sort()





A_reserve_dict = {}
last_reserve = None
for i in range(len(As)):
    if As[i] > Bs[i]:
        print("No")
        break
else:
    
    
    
    
    if check_cycle(A_i_pair) >= 2:
        print("Yes")
    else:
        for i in range(len(As) - 1):
            if As[i + 1] <= Bs[i]:  
                print("Yes")
                break
        else:
            print("No")
exit(0)

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
xa = sorted([(a[i], i) for i in range(N)], key = lambda x: x[0])
xb = sorted([(b[i], i) for i in range(N)], key = lambda x: x[0])
for i in range(N):
  if xa[i][0] > xb[i][0]:
    print("No")
    exit(0)
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.root = [-1] * (n + 1)
    self.rnk = [0] * (n + 1)

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

  def Unite(self, x, y):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if x == y:
      return 
    elif self.rnk[x] > self.rnk[y]:
      self.root[x] += self.root[y]
      self.root[y] = x
    else:
      self.root[y] += self.root[x]
      self.root[x] = y
      if self.rnk[x] == self.rnk[y]:
        self.rnk[y] += 1

  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)

  def Count(self, x):
    return -self.root[self.Find_Root(x)]
uf = UnionFind(N)
c = 0

f = 0
for i in range(N):
  
  if uf.isSameGroup(xa[i][1], xb[i][1]):
    c += 1
  uf.Unite(xa[i][1], xb[i][1])
if c >= 2:
  print("Yes")
else:
  for i in range(N - 1):
    if xa[i + 1] <= xb[i]:
      print("Yes")
      exit(0)
  print("No")

Solution (Python):
from operator import itemgetter

def solve():
    N = int(input())
    As = list(map(int, input().split()))
    Bs = list(map(int, input().split()))

    Cs = sorted(As)
    Ds = sorted(Bs)

    for A, B in zip(Cs, Ds):
        if A > B:
            return False

    for i in range(N-1):
        if Cs[i] <= Ds[i+1] and Cs[i+1] <= Ds[i]:
            return True

    ABs = [(A, B) for A, B in zip(As, Bs)]
    ABs.sort(key=itemgetter(1))

    As = [A for A, B in ABs]
    Bs = [B for A, B in ABs]
    iAs = list(range(N))
    iAs.sort(key=lambda iA: As[iA])
    convs = dict()
    for i in range(N):
        convs[As[iAs[i]]] = i

    for i in range(N-2):
        if As[i] <= Bs[i]:
            return True
        X, Y = As[i], As[iAs[i]]
        As[i], As[iAs[i]] = As[iAs[i]], As[i]
        iAs[convs[X]], iAs[convs[Y]] = iAs[convs[Y]], iAs[convs[X]]

    if As[N-2] <= Bs[N-2] and As[N-1] <= Bs[N-1]:
        return True
    else:
        return False

if solve():
    print('Yes')
else:
    print('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")

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")

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")

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

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

X = list(zip(A, B))
X.sort(key=lambda x: x[1])

C = sorted((x[0], i) for i, x in enumerate(X))
idx_map = [C[i][1] for i in range(N)]
A = sorted(A)
B = sorted(B)

if any(A[i] > B[i] for i in range(N)):
    print("No")
    exit()

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

if count_loop(0, idx_map) < N:
    print("Yes")
    exit()

print("No")

Solution (Python):
class UnionFind :
    def __init__(self, size) :
        self.parent = list(range(size))
        self.height = [0] * size
        self.size = [1] * size
        self.component = size

    def root(self, index) :
        if self.parent[index] == index :  
            return index
        rootIndex = self.root(self.parent[index])  
        self.parent[index] = rootIndex  
        return rootIndex

    def union(self, index1, index2) :  
        root1 = self.root(index1)
        root2 = self.root(index2)

        if root1 == root2 :  
            return

        self.component -= 1  

        if self.height[root1] < self.height[root2] :
            self.parent[root1] = root2  
            self.size[root2] += self.size[root1]
        else :
            self.parent[root2] = root1  
            self.size[root1] += self.size[root2]
            if self.height[root1] == self.height[root2] :
                self.height[root1] += 1
        return

    def isSameRoot(self, index1, index2) :
        return self.root(index1) == self.root(index2)

    def sizeOfSameRoot(self, index) :
        return self.size[self.root(index)]

    def getComponent(self) :
        return self.component

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

for a, b in zip(sorted(A), sorted(B)):
    if a > b:
        print('No')
        exit()


BA = list(zip(A, B))
BA.sort()

AI = [(a, i) for i, (_, a) in enumerate(BA)]
AI.sort()

tree = UnionFind(N)
for nessIndex, (_, originalIndex) in enumerate(AI):
    tree.union(nessIndex, originalIndex)

V = set()
for i in range(N):
    V.add(tree.root(i))

if len(V) > 1:  
    print('Yes')
    exit()

if any(a <= b for a, b in zip(sorted(A)[1:], sorted(B)[:-1])):
    print('Yes')
    exit()

print('No')

Solution (Python):
n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
X=list(zip(A,B))
X.sort(lambda x:x[1])

C=[(x[0],i) for i,x in enumerate(X)]
C.sort()
perm=[C[i][1] for i in range(n)]

A.sort()
B.sort()

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

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

p=0
cnt=0
while(True):
    cnt+=1
    p=perm[p]
    if(p==0): break
print("Yes" if(cnt<n) else "No")

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

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

import numpy as np

def main():
    n = ni()
    a = np.array(list(li()))
    b = np.array(list(li()))

    idx = b.argsort().tolist()

    b = b[idx]
    a = a[idx]

    
    a_sorted = np.msort(a)
    if any(a_sorted > b):
        print('No')
        return

    
    
    if any(a_sorted[1:] <= b[:-1]):
        print('Yes')
        return

    perm = a.argsort().tolist()
    x = 0
    period = 0
    for i in range(n):
        period += 1
        x = perm[x]
        if x == 0:
            break

    print('Yes' if period < n else 'No')
    return

if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
A_s, B_s = sorted(A), sorted(B)
if any(a > b for a, b in zip(A_s, B_s)):
    print("No")
    quit()
A_idx = [(a, i) for i, a in enumerate(A)]
A_idx.sort()
B = [B[idx] for _, idx in A_idx]
B_idx = [(b, i) for i, b in enumerate(B)]
B_idx.sort()
perm = [0] * N
for i, (_, idx) in enumerate(B_idx):
    perm[idx] = i
cycle_len = 0
used = [False] * N
for i in range(N):
    if used[i]:
        continue
    cnt = 0
    now = i
    while not used[now]:
        used[now] = True
        cnt += 1
        now = perm[now]
    cycle_len += cnt - 1
if cycle_len < N - 1:
    print("Yes")
    quit()

if all(B_idx[i][0] < A_idx[i+1][0] for i in range(N-1)):
    print("No")
else:
    print("Yes")

Solution (Python):
class UnionFindTree():
    def __init__(self, N):
        self.N = N
        self.__parent_of = [None] * N
        self.__rank_of = [0] * N
        self.__size = [1] * N

    def root(self, value):
        if self.__parent_of[value] is None:
            return value
        else:
            self.__parent_of[value] = self.root(self.__parent_of[value])
            return self.__parent_of[value]

    def unite(self, a, b):
        r1 = self.root(a)
        r2 = self.root(b)
        if r1 != r2:
            if self.__rank_of[r1] < self.__rank_of[r2]:
                self.__parent_of[r1] = r2
                self.__size[r2] += self.__size[r1]
            else:
                self.__parent_of[r2] = r1
                self.__size[r1] += self.__size[r2]
                if self.__rank_of[r1] == self.__rank_of[r2]:
                    self.__rank_of[r1] += 1

    def is_same(self, a, b):
        return self.root(a) == self.root(b)

    def size(self, a):
        return self.__size[self.root(a)]

    def groups(self):
        groups = {}
        for k in range(self.N):
            r = self.root(k)
            if r not in groups:
                groups[r] = []
            groups[r].append(k)
        return [groups[x] for x in groups]


def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    X = sorted(zip(B, A))
    A = list(map(lambda x: x[1], X))
    B = list(map(lambda x: x[0], X))
    sortedA = sorted(A)
    for i in range(N):
        if sortedA[i] > B[i]:
            print("No")
            return
    for i in range(N-1):
        if sortedA[i+1] <= B[i]:
            print("Yes")
            return
    uft = UnionFindTree(N)
    desired_pos = {sortedA[i]: i for i in range(N)}
    for i in range(N):
        uft.unite(i, desired_pos[A[i]])
    if len(uft.groups()) == 1:
        print("No")
    else:
        print("Yes")


if __name__ == "__main__":
    main()

Solution (Python):
from heapq import heappush, heappop
from collections import deque
import re
import math
import functools

def sRaw():
    return input().rstrip("\r")

def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))

INF = 1 << 29


def make1d_arr(n, val=INF):
    return [val for i in range(n)]


def make2d_arr(h, w, val=INF):
    return [[val for i in range(w)]for i in range(h)]


def gcd(a, b):
    if(b == 0):
        return a
    return gcd(b, a % b)


def BFord(n,es):
    v_cost = [INF]*n
    v_cost[0] = 0
    for v in range(n*2):
        for e in es:
            frm = e[0]
            to = e[1]
            if v_cost[to] > v_cost[frm]+e[2]:
                v_cost[to] = v_cost[frm]+e[2]
                if v >= n:
                    v_cost[to] = -INF
        if v == n-1:
            prev = v_cost[:]
    v_cost = [-INF if prev[idx]!=v_cost[idx] else v_cost[idx] for idx in range(n)]
    return v_cost
    
def ZAlgo(s):
    l = len(s)
    A = [0]*l
    i =1
    j =0
    A[0]=l
    while i<l:
        while i+j<l and s[j] == s[i+j]:
            j+=1
        if j==0:
            i+=1
            continue
        A[i]=j
        k=1
        while (i+k<l) and (k+A[k]<j):
            A[i+k] =A[k]
            k+=1
        i+=k
        j-=k
    return A


DIV = 998244353

def main():
    N = iRaw()
    As = isRaw()
    Bs = isRaw()
    BAs = list(zip(Bs,As))
    BAs.sort()
    AIs = [[ba[1],idx] for idx,ba in enumerate(BAs)]
    AIs.sort()
    sAidx = [0]*len(AIs)
    for sIdx,ai in enumerate(AIs):
        a,idx = ai
        if a>BAs[sIdx][0]:
            return "No"
        sAidx[idx]=sIdx
    cycleSize = 0
    curIdx = 0
    visited = [0]*len(AIs)
    while visited[curIdx]==0:
        visited[curIdx]=1
        cycleSize +=1
        curIdx = sAidx[curIdx]
    if cycleSize < N:
        return "Yes"

    for idx in range(N-1):
        if AIs[idx+1][0]<=BAs[idx][0]:
            return "Yes"
    return "No"

if __name__ == "__main__":
    print(main())