Problem:
 Score : 600 points    Problem Statement Given are two sequences A and B , both of length N . A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i ( 1 \leq i \leq N ) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.      Constraints  1\leq N \leq 2 \times 10^5  1\leq A_i,B_i \leq N  A and B are each sorted in the ascending order.  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  A_1  A_2  \cdots  A_N  B_1  B_2  \cdots  B_N       Output If there exist no reorderings that satisfy the condition, print No .  If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.  If there are multiple reorderings that satisfy the condition, you can print any of them.        Sample Input 1 6
1 1 1 2 2 3
1 1 1 2 2 3      Sample Output 1 Yes
2 2 3 1 1 1       Sample Input 2 3
1 1 2
1 1 3      Sample Output 2 No       Sample Input 3 4
1 1 2 3
1 2 3 3      Sample Output 3 Yes
3 3 1 2

Solution (Python):
"""

和がN以下なら恐れくYES
過半数にならないようにとっていけばいい
和がちょうどNなのが2つあったら、それを取る

和がNになるやつが現れるまでは自由にとり
N個になったら、それ+1個を取る

"""

import sys
from sys import stdin



class SegTree:

    def __init__(self,N,first):
        self.NO = 2**(N-1).bit_length()
        self.First = first
        self.data = [first] * (2*self.NO)

    def calc(self,l,r):
        return max(l,r)

    def update(self,ind,x):
        ind += self.NO - 1
        self.data[ind] = x
        while ind >= 0:
            ind = (ind - 1)//2
            self.data[ind] = self.calc(self.data[2*ind+1],self.data[2*ind+2])

    def query(self,l,r):
        L = l + self.NO
        R = r + self.NO
        s = self.First
        while L < R:
            if R & 1:
                R -= 1
                s = self.calc(s , self.data[R-1])
            if L & 1:
                s = self.calc(s , self.data[L-1])
                L += 1
            L >>= 1
            R >>= 1
        return s

    def get(self,ind):
        ind += self.NO - 1
        return self.data[ind]

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

nA = [0] * (N+1)
nB = [0] * (N+1)
nS = [0] * (N+1)

for i in A:
    nA[i] += 1
    nS[i] += 1
for i in B:
    nB[i] += 1
    nS[i] += 1

if max(nS) > N:
    print ("No")
    sys.exit()

print ("Yes")

ST = SegTree( N+1 , (float("-inf") , 0) )
for i in range(N):
    ST.update( i , (nS[i] , i) )

B.sort()
B.reverse()

out = None
ans = []
for i in range(N):

    num,inds = ST.query(0,N+1)
    if num == N-i:
        out = inds
        break

    if A[-1] == B[-1]:
        B.reverse()

    nas,tmp = ST.get(A[-1])
    ST.update( A[-1] ,  ( nas-1 , A[-1] ) )
    nab,tmp = ST.get(B[-1])
    ST.update( B[-1] , ( nab-1 , B[-1] ) )
    ans.append( (A[-1],B[-1]) )
    del A[-1]
    del B[-1]

if out != None:
    for i in A:
        if i != out:
            ans.append( (i,out) )
    for i in B:
        if i != out:
            ans.append( (out,i) )

ans.sort()
pla = []
for aa,bb in ans:
    pla.append(bb)
print (*pla)

Solution (Python):
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
B = list(reversed(list(map(int, input().split()))))

ac = Counter(A)
bc = Counter(B)

am = ac.most_common(1)[0]

if am[1]+bc[am[0]] > N:
    print("No")
    exit()

j = 0

for i in range(N):
    if A[i] == B[i]:
        while B[i]==A[j] or B[j]==A[i]:
            j += 1
            j %= N
        B[i], B[j] = B[j], B[i]

print("Yes")
print(*B)

Solution (Python):
from collections import deque

n=int(input())
A=[int(i) for i in input().split()]
B=[int(i) for i in input().split()]
ans=[-1 for i in range(n)]

newB=[]
cnt=1
old=B[0]
for i in range(1,n):
    if old!=B[i]:
        newB.append((old,cnt))
        cnt=1
        old=B[i]
    else:
        cnt+=1
else:
    newB.append((old,cnt))
B=deque(newB)

def firstDec():
    now=B.popleft()
    if now[1]>1:
        B.appendleft((now[0],now[1]-1))

tori=0

for i in range(n):
    if B[0][0]!=A[i]:
        ans[i]=B[0][0]
        firstDec()
        continue

    B.rotate(-1)
    if B[0][0]!=A[i]:
        ans[i]=B[0][0]
        firstDec()
        continue
    
    OK=False
    while tori<i:
        if ans[tori]!=B[0][0] and A[tori]!=B[0][0]:
            ans[i]=ans[tori]
            ans[tori]=B[0][0]
            OK=True
            break
        B.rotate()
        if ans[tori]!=B[0][0] and A[tori]!=B[0][0]:
            ans[i]=ans[tori]
            ans[tori]=B[0][0]
            OK=True
            break
        tori+=1
    if OK:
        continue
    
    print("No")
    break
else:
    print("Yes")
    print(" ".join([str(num) for num in ans]))

Solution (Python):
import sys
from sys import exit
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
        return C
    S = set([1])
    for k in C:
        T = deepcopy(S)
        for x in T:
            for i in range(1,C[k]+1):
                S.add(x*(k**i))
    if mode=='set':
        return S
    if mode=='list':
        return sorted(list(S))

N=intput()
A=lint()
B=lint()
CA=dict()
for i in range(N):
    a=A[i]
    CA.setdefault(a,[i,i])
    CA[a][1]=i
CB=dict()
for i in range(N):
    a=B[i]
    CB.setdefault(a,[i,i])
    CB[a][1]=i
S=set()
for a in CA:
    if a not in CB:
        continue
    la,ra=CA[a]
    lb,rb=CB[a]
    for x in range(la-rb,ra-lb+1):
        S.add(x%N)
if len(S)==N:
    print('No')
    exit()
print('Yes')
for i in range(N):
    if i not in S:
        for j in range(N):
            print(B[(j-i)%N], end=' ')
        sys.exit()

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

    ai, bi = 0, 0
    al, bl = [], []
    while ai < n and bi < n:
        ax, bx = a[ai], b[bi]
        la, lb = [], []
        if ax == bx:
            cnt = 2

            la.append(ai)
            ai += 1
            while ai < n and a[ai] == ax:
                la.append(ai)
                cnt += 1
                ai += 1

            lb.append(bi)
            bi += 1
            while bi < n and b[bi] == bx:
                lb.append(bi)
                cnt += 1
                bi += 1

            if cnt > n:
                print('No')
                exit()

        elif ax < bx:
            la.append(ai)
            ai += 1
        else:
            lb.append(bi)
            bi += 1

        al.append(la)
        bl.append(lb)

    print('Yes')

    slit = 0
    for i in range(len(al)):
        if len(al[i]) == 0 or len(bl[i]) == 0:
            continue
        if al[i][-1] - bl[i][0] + 1 > slit:
            slit = al[i][-1] - bl[i][0] + 1

    print(' '.join(map(str, b[n-slit:] + b[:n-slit])))

main()

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

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

    judge_a = Counter(a)
    judge_b = Counter(b)
    judge = judge_a + judge_b
    
    flag = True
    for v in judge.values():
        if v > n:
            flag = False
    
    if flag:
        i, j = 0, 0

        cycle = 0
        while i < n and j < n:
            ii, jj = i, j
            if a[i] < b[j]:
                i += 1
                continue
            if a[i] > b[j]:
                j += 1
                continue
            if a[i] == b[j]:
                while i < n-1 and a[i] == a[i+1]:
                    i += 1
                while j < n-1 and b[j] == b[j+1]:
                    j += 1
            cycle = max(cycle, i-jj+1)
            i += 1
            j += 1
        
        ans = [0]*n
        for i in range(n):
            ans[(i+cycle)%n] = b[i]
        
        for i in range(n):
            if a[i] == ans[i]:
                print("No")
                sys.exit()
        print("Yes")
        print(*ans)
    else:
        print("No")

if __name__ == "__main__":
    main()

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = 10**6
mod = 10 ** 9 + 7 





N = INT()
A = LIST()
B = LIST()

CA = Counter(A)
CB = Counter(B)

for k in CB.keys():
	if CB[k] > N-CA[k]:
		print("No")
		exit()
else:
	print("Yes")

B = B[::-1]

j = 0
jdx = 1

for i in range(N):
	if A[i] == B[i]:
		if B[i] == B[j] or B[i] == A[j]:
			j = -1
			jdx = -1
		B[i], B[j] = B[j], B[i]
		j += jdx

print(*B)

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

l, r = 0, N + 1
while r - l > 1:
    m = (r + l) // 2
    if np.all(B[N - m:] > A[:m]):
        l = m
    else:
        r = m

if np.all(B[:N - l] < A[l:]):
    print('Yes')
    print(*np.roll(B, l))
else:
    print('No')

Solution (Python):
mod = 1000000007
eps = 10**-9


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

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

    B.reverse()
    idx = []
    x = -1
    for i in range(N):
        if A[i] == B[i]:
            idx.append(i)
            x = A[i]
    if len(idx) == 0:
        print("Yes")
        print(*B)
    else:
        l = 0
        r = N-1
        for i in idx:
            if A[l] != x and B[l] != x:
                B[l], B[i] = B[i], B[l]
                l += 1
            else:
                if A[r] != x and B[r] != x:
                    B[r], B[i] = B[i], B[r]
                    r -= 1
                else:
                    print("No")
                    exit()
        print("Yes")
        print(*B)


if __name__ == '__main__':
    main()

Solution (Python):


def ans(N, A, B):
    B = B[::-1]

    match_vals = set()

    for i in range(N):
        if A[i] == B[i]:
            match_vals.add(A[i])

    if len(match_vals) == 0:
        print("Yes")
        print(*B)
        return

    assert(len(match_vals) == 1)
    [m] = list(match_vals)

    ok = []
    bad = []
    for i in range(N):
        if B[i] != m and A[i] != m:
            ok += [i]
        if A[i] == B[i]:
            bad += [i]

    if len(bad) > len(ok):
        print('No')
        return

    for i in range(len(bad)):
        B[bad[i]], B[ok[i]] = B[ok[i]], B[bad[i]]

    print('Yes')
    print(*B)

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

ans(N, A, B)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
idx_B = 0
ma = 0
for idx_A, a in enumerate(A):
    while idx_B < N and B[idx_B] < a:
        idx_B += 1
    if ma < idx_A - idx_B:
        ma = idx_A - idx_B
Ans = (B+B)[N-ma-1:2*N-ma-1]
for a, b in zip(A, Ans):
    if a == b:
        print("No")
        exit()
print("Yes")
print(" ".join(map(str, Ans)))

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


b = sorted(b, reverse=True)

inds = []
val = -1
for i in range(n):
    if a[i] == b[i]:
        val = a[i]
        inds.append(i)
if val == -1:
    print("Yes")
    print(*b)
    exit()

is_val = [False] * n
for i in range(n):
    if a[i] == val or b[i] == val:
        is_val[i] = True

for i in range(n):
    if not is_val[i] and inds:
        j = inds.pop()
        b[i], b[j] = b[j], b[i]
if not inds:
    print("Yes")
    print(*b)
    exit()
print("No")

Solution (Python):
from bisect import bisect_left,bisect_right
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
aset=set(a)
bset=set(b)
ans=0
for i in range(n):
  if a[i] in bset:
    ans=max(i-bisect_left(b,a[i]),ans)
b=(b+b+b)[n-ans-1:n+n-ans-1]
for i in range(n):
  if a[i]==b[i]:
    exit(print("No"))
print("Yes")
print(*b)

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

    B.reverse()
    l, r = 0, N - 1

    for i in range(N):
        if A[i] != B[i]:
            continue
        if l < i and A[i] != B[l] and A[l] != B[i]:
            B[l], B[i] = B[i], B[l]
            l += 1
            continue
        if i < r and A[i] != B[r]:
            B[i], B[r] = B[r], B[i]
            r -= 1
            continue
        return None
    return B

t = main()
if t is None:
    print('No')
else:
    print('Yes')
    print(' '.join(map(str, t)))

Solution (Python):
import sys
from heapq import *

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

countA = [0] * (N + 1)
countB = [0] * (N + 1)
for x in A:
    countA[x] += 1
for x in B:
    countB[x] += 1

q = []
only_A = []
only_B = []
for i in range(N + 1):
    if countA[i] and countB[i]:
        q.append((-countA[i] - countB[i], i))
        continue
    for _ in range(countA[i]):
        only_A.append(i)
    for _ in range(countB[i]):
        only_B.append(i)
heapify(q)

if q and -q[0][0] > N:
    print('No')
    exit()
print('Yes')

ans = []
while q:
    _, x = heappop(q)
    if q:
        _, y = heappop(q)
        flag = True
    else:
        y = only_B.pop()
        flag = False
    countA[x] -= 1
    countB[y] -= 1
    ans.append((x, y))
    if countA[x]:
        heappush(q, (-countA[x] - countB[x], x))
    else:
        for _ in range(countB[x]):
            only_B.append(x)
    if flag and countB[y]:
        heappush(q, (-countA[y] - countB[y], y))
    if flag and not countB[y]:
        for _ in range(countA[y]):
            only_A.append(y)
while only_A:
    x, y = only_A.pop(), only_B.pop()
    assert countA[x] > 0
    assert countB[y] > 0
    countA[x] -= 1
    countB[y] -= 1
    ans.append((x, y))

ans.sort()
X, Y = zip(*ans)
print(*Y)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]



def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N = I()
A = IL()
B = IL()

dicA = DD(int)
dicB = DD(int)
for a in A:
  dicA[a] += 1
for b in B:
  dicB[b] += 1
giri = 0
moji = None
for k in A:
  if dicA[k] + dicB[k] > giri:
    giri = dicA[k] + dicB[k] 
    moji = k
  if dicA[k] + dicB[k] > N:
    print("No")
    exit()
print("Yes")

count = 0
q = deque([])
for b in B:
  if b == moji:
    count += 1
  else:
    q.append(b)
    
ans = []
for i in range(N):
  if count and A[i] != moji:
    ans.append(moji)
    count -= 1
    continue
  if q[-1] != A[i]:
    ans.append(q.pop())
  else:
    ans.append(q.popleft())
print(*ans)