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



Sample input:
3
1 3 2
1 2 3


Sample output:
Yes

Submission status: Time Limit Exceeded

Solution code:
from operator import itemgetter

N = int(input())
A = [int(a) for a in input().split()]
B = [int(b) for b in input().split()]

L = []
for i in range(N):
    L.append([A[i], B[i]])
    
L.sort(key=itemgetter(1))


def f(n, l, u, L):
    if u-l < 2:
        return u
    else:
        m = (u+l)//2
        if L[m][1] > n:
            return f(n, l, m, L)
        else:
            return f(n, m, u, L)

i = 0
cnt = 0

while cnt < N-2 and i < len(L):
    if L[i][0] > L[i][1]:
        t = f(L[i][0], 0, len(L)-1, L)
        if L[i][0] <= L[t-1][1]:
            t -= 1
        temp = L[i][0]
        L[i][0] = L[t][0]
        L[t][0] = temp
        if L[t][0] == L[t][1]:
            L.pop(t)
        cnt += 1
    else:
        i += 1
        
ans = "Yes"
for i in range(len(L)):
    if L[i][0] > L[i][1]:
        ans = "No"
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
As = list(map(int, input().strip().split()))
Bs = list(map(int, input().strip().split()))


def swap(i, j, lis):
    temp = lis[i]
    lis[i] = lis[j]
    lis[j] = temp


def search(lis, i, most):
    ret = -1
    for j in range(i + 1, len(lis)):
        if most >= lis[j] > ret:
            ret = j
    return ret


for i in range(N):
    for j in range(i + 1, N):
        if Bs[i] > Bs[j]:
            swap(i, j, Bs)
            swap(i, j, As)

#print(As)
#print(Bs)
cnt = 0
exissw = 1
for i in range(N):
    if As[i] > Bs[i]:
        lessMostIdx = search(As, i, Bs[i])
        if lessMostIdx != -1:
            swap(i, lessMostIdx, As)
            cnt += 1
        else:
            exissw = 0
            break
if exissw == 0:
    print("No")
else:
    if cnt > N - 2:
        print("No")
    else:
        print("Yes")
        #print(As)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import copy
n = int(input())
alis = list(map(int, input().split()))
blis = list(map(int, input().split()))

nlis = []
for i in range(n):
    nlis.append(i)
rootlis = list(itertools.combinations(nlis, 2))
rootlis2 = []
for i in range(n-1):
    rootlis2.extend(list(itertools.combinations(rootlis, i)))
countyes = 0
for lis in rootlis2:
    alist = copy.deepcopy(alis)
    blist = copy.deepcopy(blis)
    count = 0
    for li in lis:
        alist[li[0]], alist[li[1]] = alist[li[1]], alist[li[0]]
    for i in range(n):
        if alist[i] <= blist[i]:
            count += 1
    
    if count == n:
        print("Yes")
        countyes += 1
        break
if countyes == 0:
    print("No")

Submission status: Time Limit Exceeded

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

swap_cnt = 0
for i in range(n):
  max_ = i
  if a[i]<=b[i]:
  	max_value = a[i]
  else:
    max_value = 0
    
  for j in range(i,n):
    if (a[j]<b[i])&(a[j]>max_value):
      max_ = j
      max_value = a[j]
    elif a[j]==b[i]:
      max_ = j
      max_value = a[j]
      break
  
  if max_ != i:
    #a[i]<=>a[max_]
    swap = a[i]
    a[i] = a[max_]
    a[max_] = swap
    swap_cnt+=1
    #print(i)
    #print(swap_cnt)
  #else:
    #print('pass')
    #print(swap_cnt)
  if a[i]>b[i]:
    swap_cnt = n
    break
if swap_cnt<=n-2:
  print('Yes')
else:
  print('No')

Submission status: Time Limit Exceeded

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

count1 = 0
count2 = 0

AB = []
AB_new = []
A_new = sorted(A)
B_new = sorted(B)

for i in range(N):
    AB.append([A[i],B[i]])
    AB_new.append([A_new[i],B_new[i]])
    
aaa = sorted(AB, key=lambda x:x[0])

for i in range(N):
    if B_new[i] >= A_new[i]:
        count2 += 1
        
for i in range(N):
    for j in range(N):
        if AB_new[i] == aaa[j]:
            count1 = 1
            break
        if AB_new[i][0] < aaa[j][0]:
            break
    if count1 == 1:
        break

if count1 == 1 and count2 == N:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
k = 0
A.sort()
for i in range(N):
    if A[i] <= B[i]:
        continue
    else:
        for j in range(N):
            if B[j] == min(B):
                w = B[j]
                B[j] = B[i]
                B[i] = w
                k += 1
if k <= N-2:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
ASort=sorted(A)
BSort=sorted(B)
g=0
for i in range(N):
    if ASort[i]>BSort[i]:
        g=1
        break
ans=0
if g==0:
    _A=[]
    for i,a in enumerate(A):
        _A.append((i,a))
    _A.sort(key=lambda x:x[1])
    index=[]
    for i in range(N):
        index.append(_A[i][0])
    update=1
    while update:
        update=0
        for i in range(1,N):
            if index[i]<index[i-1]:
                update=1
                buf=index[i-1]
                index[i-1]=index[i]
                index[i]=buf
                ans+=1
if ans>N-2 or g==1:
    print("No")
else:
    print("Yes")

Submission status: Time Limit Exceeded

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

flag = False
k = 0
while(not flag and k<n):
    if AB[k][0] <= AB[k][1]:
        ABd = AB[:k] + AB[k+1:]

        As = list()
        Bs = list()
        for i, j in ABd:
            As.append(i)
            Bs.append(j)

        As.sort()

        for i in range(n-1):
            if As[i] > Bs[i]:
                break
        else:
            flag = True

    k += 1

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

Submission status: Time Limit Exceeded

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

count1 = 0
count2 = 0

AB = []
AB_new = []

for i in range(N):
    AB.append([A[i],B[i]])
    
#print(AB)

A_new = sorted(A)
B_new = sorted(B)

for i in range(N):
    AB_new.append([A_new[i],B_new[i]])
    
#print(AB_new)
#print(AB_new[0])
aaa = sorted(AB, key=lambda x:x[0])
#print(aaa)

for i in range(N):
    if B_new[i] >= A_new[i]:
        count2 += 1
        
for i in range(N):
    for j in range(N):
        if AB_new[i] == aaa[j]:
            count1 = 1
            break
    if count1 == 1:
        break
#print(A_new)
#print(B_new)
#print(count1)

if count1 == 1 and count2 == N:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

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

orderA = {}
orderB = {}

for k, ((_, i), (_, j)) in enumerate(zip(AI, BI)):
    orderA[i] = k
    orderB[j] = k

path = 0
visited = [False] * N
for i, a in enumerate(orderA):
    if visited[i]:
        continue
    visited[i] = True
    length = 0
    now = orderB[i]
    while now != a:
        now = orderA[now]
        visited[now] = True
        now = orderB[now]
        length += 1
    path = max(path, length)

if path <= N - 2:
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n = int(input())
a = np.array(input().split(), dtype=np.int)
b = np.array(input().split(), dtype=np.int)
flag = False
for i in np.where(a <= b)[0]:
  mask = np.ones(n, dtype=np.bool)
  mask[i] = False
  if np.all(np.sort(a[mask]) <= np.sort(b[mask])):
    flag = True
    break
if flag:
  print('Yes')
else:
  print('No')

Submission status: Time Limit Exceeded

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

C = sorted([[A[i], B[i]] for i in range(N)], key=lambda c : (c[1]))
#print(C)
count = 0
for i in range(N):
    if C[i][0] <= C[i][1]:
        continue
    ok = False
    for j in range(N-1, i, -1):
        if C[j][0] <= C[i][1]:
            C[i][0], C[j][0] = C[j][0], C[i][0]
            count += 1
            ok = True
            break
    if not ok:
        print("No")
        exit(0)

if count <= N-2:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

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

cnta=0
for i in range(1,N):
    for j in range(i,N):
        if A[i-1]>A[j]:
            cnta+=1

cntb=0
for i in range(1,N):
    for j in range(i,N):
        if B[i-1]>B[j]:
            cntb+=1

if cnta>N-2 or cntb>N-2:
    print("No")
    exit()


A.sort()
B.sort()

for i in range(N):
    if not A[i]<=B[i]:
        print("No")
        exit()
print("Yes")

Submission status: Time Limit Exceeded

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

diff,zeros=[],[]
for i in range(N):
    dif = sorted(B)[i]-sorted(A)[i]
    zero = B[i]-A[i]
    if zero < 0:
        zeros.append(zero)
    if dif >= 0:
        diff.append(dif)
    
print('Yes') if (len(diff) == N) and (len(zeros) <= N-2) else print('No')

Submission status: Time Limit Exceeded

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

diff,zeros=[],[]
for i in range(N):
    dif = sorted(B)[i]-sorted(A)[i]
    zero = B[i]-A[i]
    if zero < 0:
        zeros.append(zero)
    if dif >= 0:
        diff.append(dif)

if (len(diff) == N) and (len(zeros) <= N-2):
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]

count =0
success = True
for i in range(n):
    if a[i] > b[i]:
        next_min_index = a.index(min(a[1+1:]))
        a[i] , a[next_min_index] = a[next_min_index], a[i]
        if a[i] > b[i]:
            success = False
            break
        count+=1
if (success ==False or count>n-2):
    print("No")
else:
    print("Yes")

Submission status: Time Limit Exceeded

Solution code:
import sys
n = int(input())
a_ls = [int(i) for i in sys.stdin.readline().split()]
b_ls = [int(i) for i in sys.stdin.readline().split()]
a_ls, b_ls = zip(*sorted([(a, b) for a, b in zip(a_ls, b_ls)], key=lambda x:x[1]))
a_ls = list(a_ls)
cnt = 0
last = n - 1
flg = True
for i, (a, b) in enumerate(zip(a_ls, b_ls)):
    if b < a:
        last = n - 1
        while b < a_ls[last]:
            last -= 1
            if last <= i:
                flg = False
                break
        a_ls[i], a_ls[last] = a_ls[last], a_ls[i]
        cnt += 1
        if cnt > n - 2:
            flg = False
            break
    if not flg:
        break
if flg:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A1=[int(s) for s in input().split()]
B1=[int(s) for s in input().split()]
A2=[(A1[i],i) for i in range(N)]
B2=[(B1[i],i) for i in range(N)]
A=sorted(A2)
B=sorted(B2)
#print(A)
#print(B)
for i in range(N):
  if B[i][0]<A[i][0]:
    print("No")
    break
else:
  for i in range(N-1):
    if B[i][0]>=A[i+1][0]:
      print("Yes")
      break
  else:
    C=[e[1] for e in A]
    a=C[0]
  #  print(a)
    k=B[0][1]
    for i in range(N-2):
      k=B[C.index(k)][1]
   #   print(k)
      if k==a :
        print("Yes")
        break
    else:
      print("No")

Submission status: Time Limit Exceeded

Solution code:



N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
sA,sB=sorted(A),sorted(B)
data=[[a,b] for a,b in zip(sA,sB) if b>=a]
if  len(data)!=N:
    print("No")
    exit()
flag=[[a,b] for a,b in zip(A,B) if b>=a]
A=sorted(A,reverse=True)
B=sorted(B,reverse=True)


blist=[i[1] for i in flag]


for i in range(N):
    for m in range(N-i):
        if not B[i+m] in blist:break

        if B[i+m]>=A[i]:
            for a1,b1 in flag:
                if B[i+m]==b1 and A[i]==a1:
                    print("Yes")
                    exit()
        else:break
print("No")

Submission status: Time Limit Exceeded

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

diff,zeros=[],[]
for i in range(N):
    dif = sorted(B)[i]-sorted(A)[i]
    zero = B[i]-A[i]
    diff.append(dif)
    zeros.append(zero)

l_zero = [i for i in zeros if i < 0]
l_diff = [i for i in diff if i >= 0]
if (len(l_diff) == N) and (len(l_zero) <= N-2):
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int, input().split()))
B=list(map(int, input().split()))
A_, B_=sorted(A), sorted(B)
flag=True
for i in range(N):
  if A_[i]>B_[i]:
    flag=False
    break
if not flag:
  print("No")
else:
  C=[(A[i], B[i]) for i in range(N)]
  C.sort(key=lambda x:(x[1], x[0]))
  A=[C[i][0] for i in range(N)]
  ans=0
  for i in range(N):
    minv=A[i]
    mini=i
    if A[i]==A_[i]:
      continue
    for j in range(i+1, N):
      if A[mini]>A[j]:
        minv=A[j]
        mini=j
    if mini!=i:
      ans+=1
      A[i], A[mini]=A[mini], A[i]
    else:
      break
  if ans<=N-2:
    print("Yes")
  else:
    print("No")

Submission status: Time Limit Exceeded

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

count1 = 0
count2 = 0

A_new = sorted(A)
B_new = sorted(B)

for i in range(N):
    if B_new[i] >= A_new[i]:
        count2 += 1
        
for i in range(N):
    for j in range(N):
        if A_new[i] == A[j] and B_new[i] == B[j]:
            count1 = 1
            break
    if count1 == 1:
        break
#print(A_new)
#print(B_new)
#print(count1)

if count1 == 1 and count2 == N:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
sA,sB=sorted(A),sorted(B)
data=[[a,b] for a,b in zip(sA,sB) if b>=a]
if  len(data)!=N:
    print("No")
    exit()
flag=[[a,b] for a,b in zip(A,B) if b>=a]
A=sorted(A,reverse=True)
B=sorted(B,reverse=True)
for i in range(N):
    for m in range(N-i):
        if B[i+m]>=A[i]:
            for a1,b1 in flag:
                if B[i+m]==b1 and A[i]==a1:
                    print("Yes")
                    exit()
        else:break
print("No")

Submission status: Time Limit Exceeded

Solution code:

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

if (max(b) < max(a)):
    print ('No')

else :
    count = 0
    for i in range(len(a)):
        if (a[i] > b[i]):
            for j in range(len(b)):
                if (a[i] <= b[j] and a[j] <= b[i]):
                    a[i],a[j] = a[j],a[i]
                    count = count + 1
                    break

    for k in range(len(a)):
        if (a[i] > b[i]):
            print ('No')
    

    if (n-2 >= count and k+1 == len(a)):
        print ('Yes')
    else :
        print ('No')

Submission status: Time Limit Exceeded

Solution code:
import copy

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')
        break
else:
    for i in range(n):
        C = copy.deepcopy(A)
        D = copy.deepcopy(B)
        if C[i] <= D[i]:
            C.pop(i)
            D.pop(i)
            for c, d in zip(sorted(C), sorted(D)):
                if c > d:
                    break
            else:
                print('Yes')
                break
    else:
        print('No')

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int, input().split()))
B=list(map(int, input().split()))
A_, B_=sorted(A), sorted(B)
flag=True
for i in range(N):
  if A_[i]>B_[i]:
    flag=False
    break
if not flag:
  print("No")
else:
  C=[(A[i], B[i]) for i in range(N)]
  C.sort(key=lambda x:(x[1], x[0]))
  A=[C[i][0] for i in range(N)]
  ans=0
  for i in range(N):
    minv=A[i]
    mini=i
    if A[i]==A_[i]:
      continue
    for j in range(i+1, N):
      if A[mini]>A[j]:
        minv=A[j]
        mini=j
    if mini!=i:
      ans+=1
      A[i], A[mini]=A[mini], A[i]
  if ans<=N-2:
    print("Yes")
  else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A, B = [], []
for i, a in enumerate(map(int,input().split())):
  A.append(a)
for i, b in enumerate(map(int,input().split())):
  B.append([b,A[i], i])
B.sort()

cnt = 0
for b, a, bi in B:
  minA = min(A)
  minA_i = A.index(minA)
  if minA > b:
    print('No')
    exit()

  if minA_i == bi:
    A[minA_i] == float('inf')
  else:
    A[minA_i] = A[bi]
    A[bi] = float('inf')
    cnt += 1
  
  #print(minA, b, cnt)
  if cnt > N-2:
    print('No')
    exit()
  
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int, input().split()))
B=list(map(int, input().split()))
A_, B_=sorted(A), sorted(B)
flag=True
for i in range(N):
  if A_[i]>B_[i]:
    flag=False
    break
if not flag:
  print("No")
else:
  C=[(A[i], B[i]) for i in range(N)]
  C.sort(key=lambda x:(x[1], x[0]))
  A_=[C[i][0] for i in range(N)]
  ans=0
  for i in range(N):
    minv=A_[i]
    mini=i
    for j in range(i+1, N):
      if A_[mini]>A_[j]:
        minv=A_[j]
        mini=j
    if mini!=i:
      ans+=1
      A_[i], A_[mini]=A_[mini], A_[i]
  if ans<=N-2:
    print("Yes")
  else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter


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

wrong_num = 0
for i in range(N):
    if A[i] > B[i]:
        wrong_num += 1
if wrong_num > N-2:
    print('No')
    exit()

c_a = Counter(A)
c_b = Counter(B)

for k, v in c_b.items():
    t = sum([v2 for k2, v2 in c_a.items() if k2 <= k])
    if t < v:
        print('No')
        exit()
print('Yes')

Submission status: Time Limit Exceeded

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

A_sort = sorted(A)
B_sort = sorted(B)

for i in range(len(A)):
    if A_sort[i] > B_sort[i]:
        print("No")
        exit()

tmp = 0
swap_cnt = 0
for i in range(len(A)):
    for j in range(i, len(A)):
        if A[i] > A[j]:
            tmp = A[i]
            A[i] = A[j]
            A[j] = tmp
            swap_cnt += 1
      
print("Yes" if swap_cnt <= N-2 else "No")

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from itertools import accumulate, dropwhile, takewhile, groupby
import bisect
import copy
import math

# 入力 =stdin.readline().rstrip()
# 分割 = stdin.readline().rstrip().split()

'''
条件に合うものを絞り込む
data = [1, 2, 3]
s = [x for x in data if x % 3 == 0]
'''

'''
文字配列を数値に
l_si = ['-10', '0', '100']

l_si_i = [int(s) for s in l_si]
'''

'''
a = [2, 4, 6, 8]
b = [3, 6, 9]

print(list(set(a) | set(b)))  # 和集合
print(list(set(a) & set(b)))  # 積集合
'''

'''
N = int(stdin.readline().rstrip())
A = [int(x) for x in stdin.readline().rstrip().split()]
count = 0
while len([x for x in A if x % 2 == 0]) == N:
    A = list(map(lambda y: y / 2, A))
    count += 1
print(count)
'''

'''
.append(要素)
.extend(要素)
.insert(場所,要素)
del 配列名[場所]
-1で末尾で末尾から一つ前
'''
'''
間に空白追加
' '.join(lis)
'''
'''
copy.copy(配列名)
'''
'''
sort()50
sorted(reverse=true)
'''
'''
2分探索
bisect.bisect_left(リスト, 要素)
'''
N = int(stdin.readline().rstrip())
_A = stdin.readline().rstrip().split()
_B = stdin.readline().rstrip().split()

A = [int(s) for s in _A]
B = [int(s) for s in _B]
a = copy.copy(A)
B.sort()
res = True

count = 0
for i in range(len(a)):
    for j in range(len(a)-1, i, -1):
        if a[j] < a[j-1]:
            a[j], a[j-1] = a[j-1], a[j]
            count += 1

if (a[N - 1] > B[N - 1] or a[N-2] > B[N-2]):
    res = False
if (count > (N - 2)):
    res = False

if (res):
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
import math
n = int(input())
a = (list(map(int, input().split())))
b = (list(map(int, input().split())))

inv = 0

for i in range(n):
  if max(a) > max(b):
    print('No')
    exit()
    
  if a[i] > b[i] :
    if min(a) > b[i]:
      print('No')
      exit()
    else:
      inv += 1
      
if inv <= n-2:
  print('Yes')
else:
  print('No')

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
c=0
for i in range(len(A)):
    if A[i]>B[i]:
        c+=1
    if sorted(A)[i]>sorted(B)[i]:
        print("No")
        exit()
print("Yes" if N-c>=2 else "No")

Submission status: Accepted

Solution code:

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

Submission status: Accepted

Solution code:
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")

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)))
    
    
    #基本的にBを恥からソートしてもN-1回，完全逆順とかならそれはそれで楽にソートできるので，
    #結局はBをソートするだけの話? 流石に違う気もするが...
    #=>A:1,2,3,4,5
    #  B:5,1,2,3,4みたいなケースが無理になるのか2,3,4,5,1もダメ．でも2,3,4,5,2はOK
    
    #普通にB:4,5,1,2,3みたいなのもダメ，Bが輪になっているとダメか
    #Bがある地点から昇順になるなら，つなげば1つのグループができる
    
    A1=sorted(A)
    B1=sorted(B)
    
    from collections import defaultdict
    dd = defaultdict(int)
    
    #Bの数字と順番を対応させる．Bないにかぶりがあるときはflag2で引っかかるはず?
    
    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#sortずみのB[i]を1箇所ずらしても条件を満たしうるか，これが1ならOK
    
    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()

Submission status: Accepted

Solution code:
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")

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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")

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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()

# 2通り以上の並べ方がある場合はOK 
for i in range(n - 1):
  if A[X[i + 1]] <= B[Y[i]]:
    print("Yes")
    exit()

# ループが小さいループになっていればOK
cnt = 0
i = 0
while cnt < n - 1:
  j = X[i]
  i = V[j]
  if i == 0:
    print("Yes")
    exit()
  cnt += 1

print("No")

Submission status: Accepted

Solution code:
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")