Author: | MathModel |
Prepared by: | MathModel |
Edited by: | MathModel |
Each index is a column (a_i,b_i) that may be swapped independently . Targeting \mathsf{MEX}(a)=\mathsf{MEX}(b)=k means both arrays contain all of \{0,1,\dots,k-1\} and both miss .
Let be the smallest value occurring in no column at all . Neither array can produce , so both miss it automatically , and is the largest common reachable . It is also the only one : a value that appears somewhere is always handed to or to by its column , so no value below can be missing from both , and the common is pinned to exactly .
What remains is one per-value question : can sit in both arrays at once ? A column with a_i=b_i=v delivers to both arrays however it is set , and a column with only one side equal to delivers to exactly one array , our choice of side . So is placeable in both arrays precisely when some column has a_i=b_i=v (write s_v=1) , or at least two distinct columns contain (write c_v\ge 2) . If some v<g fails both tests then lands in one array and not the other , the two values diverge , and the answer is NO .
Sweep v=0,1,2,\dots while is present . A present value with s_v=0 and c_v\le 1 gives NO , and reaching the first absent value with no failure gives YES .
def solve():
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
p=[0]*(n+1)
s=[0]*(n+1)
c=[0]*(n+1)
for i in range(n):
x=a[i]
y=b[i]
if(x<=n):
p[x]=1
c[x]+=1
if(y<=n):
p[y]=1
if(x==y):s[y]=1
else:c[y]+=1
for i in range(n+1):
if(not p[i]):break
if(not(s[i]or c[i]>1)):
print('NO')
return
print('YES')Time complexity: per test case . Memory complexity: .