Problem:


Score : 800 points

Problem Statement

You are given integers N,\ A and B.
Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.

P_0=A

P_{2^N-1}=B

For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.

Constraints

1 \leq N \leq 17

0 \leq A \leq 2^N-1

0 \leq B \leq 2^N-1

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

If there is no permutation that satisfies the conditions, print NO.

If there is such a permutation, print YES in the first line.
Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between.
If there are multiple solutions, any of them is accepted.

Sample Input 1

2 1 3

Sample Output 1

YES
1 0 2 3

The binary representation of P=(1,0,2,3) is (01,00,10,11), where any two adjacent elements differ by exactly one bit.

Sample Input 2

3 2 1

Sample Output 2

NO



Sample input:
2 1 3


Sample output:
YES
1 0 2 3

Submission status: Runtime Error

Solution code:


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

visited = {}

for i in range(2**N):
	visited.setdefault(i,False)

stack = [A]
visited[A] = True 
end_flag = False

'''
def diff1(a,b):
	i = min(a,b)
	j = max(a,b)
	ans = False
	for k in range(N):
		if (j-i) == 2**k:
			if (i%(2**(k+1)))//(2**k)==0:
				ans = True
				break
		else:
			continue
	return ans
'''

def diff1(a,b):
	n = len(bin(abs(a-b)))-3 #aとbの差が2の何乗か
	if (min(a,b)%(2**(n+1)))//(2**n)==0:
		return True
	else:
		return False

answer = []

def df():
	global visited
	global stack
	global B
	global end_flag
	global answer
	#print('{0},{1}'.format(stack[-1:-7:-1],len(stack)))
	#print(answer)
	#スタックが空なら終了
	if stack == []:
		pass
	#終了フラグが立っていれば何もしない
	elif end_flag == True:
		pass
	else:
		#stackの長さが2**Nならその数列を出力すればよい
		if len(stack)==2**N:
			end_flag = True #終了フラグを立てる
			answer = stack
			return stack
		#ノードのdiff1判定がFalseなら深い層に進まない
		elif len(stack)>=2 and diff1(stack[0],stack[1])==False:
			#訪問情報とstackの先頭を削除
			visited[stack[0]] = False
			stack.pop(0)
		#最後の数がBでなければならないので,stackの長さが2**N未満なのにstackにBが含まれていたらそれもダメ
		elif len(stack)<2**N and B in stack:
			#訪問情報とstackの先頭を削除
			visited[stack[0]] = False
			stack.pop(0)
		#どのノードも未訪問か,diff1判定がTrueなら次の層へ
		else:
			#まずnodeの候補を取得するがその数はstack[0]±2**k(k=0,...,N)に制限する
			for k in range(N+1):
				for f in [-1,1]:
					node = stack[0] + k*f
					if node >= 0 and node <= 2**N-1:
						#未訪問なら
						if visited[node] == False:
							#訪問済みにしたうえでスタックを更新して
							visited[node] = True
							stack = [node] + stack
							#再帰的呼び出し
							df()
						#nodeが訪問済みなら何もしない
						else:
							continue
			#ループを抜けたあとは全子ノードが訪問済みなので
			visited[stack[0]] = False
			stack.pop(0)

			'''
			for node in list(visited.keys()):
				#未訪問なら
				if visited[node] == False:
					#訪問済みにしたうえでスタックを更新して
					visited[node] = True
					stack = [node] + stack
					#再帰的呼び出し
					df()
				#nodeが訪問済みなら何もしない
				else:
					continue
			#ループを抜けたあとは全子ノードが訪問済みなので
			visited[stack[0]] = False
			stack.pop(0)
			'''

df()

if len(answer)>0:
	print('YES')
	print(' '.join([str(x) for x in answer[::-1]+[B]]))
else:
	print('NO')

#深さ優先探索はスタック, 幅優先探索はキュー

#深さ優先探索
#分岐候補をスタックに積む方法ともいえる
#1.探索木の根ノードをスタックに積む
#2.スタックが空なら終了
#3.スタックが空でなければ先頭ノードをチェック
#4.スタック先頭モードの子ノードのうち未探索のものが存在するかどうかを判定
#5-1.未探索の子ノードが存在すれば,そのノードをスタックの先頭に積む
#5-2.2に戻る
#6-1.スタック先頭ノードの子ノードがいずれも探索済みなら,先頭ノードをスタックから1つ削除
#6-2.2に戻る

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python2
"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>

"""
from __future__ import division, print_function

import itertools
import os
import sys
from atexit import register
from cStringIO import StringIO

range = xrange

filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip

sys.stdout = StringIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = StringIO(os.read(0, os.fstat(0).st_size)).readline


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

    seq = [i for i in range(1 << n) if (i != a) and (i != b)]

    items = [[]]
    for j in seq:
        new_items = []
        for i, item in enumerate(items):
            if i % 2:
                new_items.extend(item[:i] + [j] + item[i:] for i in range(len(item) + 1))
            else:
                new_items.extend(item[:i] + [j] + item[i:] for i in reversed(range(len(item) + 1)))
        items = new_items

    for item in items:
        x, y = item[0] ^ a, item[-1] ^ b
        if (x & (x - 1) == 0) and (y & (y - 1) == 0):
            print('YES')
            print(a, end=' ')
            print(*item, end=' ')
            print(b)
            return

    print('NO')


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
_=input()
_=input()
print('YES')
print('1 0 2 3')

Submission status: Runtime Error

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

 
numdiff = bin(A ^ B).count("1")


if numdiff >= (2 ** N) or numdiff % 2 == 0:
    print("NO")


else:
    
    pos = []
    for i in range(2 ** N):
        neigh = set()
        temp = list(bin(i)[2:])
        
        if len(temp) < N:
            temp = ["0"] * (N - len(temp)) + temp
        for t in range(len(temp)):
            if temp[t] == '0':
                temp[t] = '1'
            else:
                temp[t] = '0'
            neigh.add(int("".join(temp), 2))
            if temp[t] == '0':
                temp[t] = '1'
            else:
                temp[t] = '0'
        pos.append(neigh)
    

    
    
    def dfs(rem, paths, visited):
        if len(rem) == 1:
            for r in rem:
                if bin(A ^ B).count("1") == 1: return paths
                return False

        for next in pos[paths[-1]]:
            if next in rem:
                v = visited.copy()
                v.add(next)
                r = rem.copy()
                r.remove(next)
                p = paths[:]
                p.append(next)
                x = dfs(r, p, v)
                if x != False:
                    return x
        return False
    rem = set()
    for i in range(2 ** N):
        rem.add(i)
    rem.remove(A)
    rem.remove(B)    
    x = dfs(rem, [A], set())
    if not x:
        print("NO")
    else:
        print("YES")

        for i in x:
            print(i, end = " ")
        print(B)

Submission status: Runtime Error

Solution code:
N,A,B=[int(x) for x in input().split()]


SA=bin(A)[2:]
SB=bin(B)[2:]

mx=max(len(SA),len(SB))
SA=("0"*mx+SA)[-mx:]
SB=("0"*mx+SB)[-mx:]

diff=0
L=[]
for i in range(len(SA)):
    if SA[i]!=SB[i]:
        L.append(i)
        diff+=1


if diff%2==0:
    print('NO')
else:
    
    out=str(int(SA,2))+" "
    print('YES')
    for i in L:
            if SA[i]=="1":
                SA=SA[:i]+"0"+SA[i+1:]
            else:
                SA=SA[:i]+"1"+SA[i+1:]
            out+=str(int(SA,2))+" "


    for j in range(2**N-i-2):
        if SA[0]=="0":
            SA="1"+SA[1:]
        else:
            SA="0"+SA[1:]
        out+=str(int(SA,2))+" "
        
print(out.strip())
"""
for t in out.split():
    print(("0000"+bin(int(t))[2:])[-3:])
"""

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from tqdm import tqdm

N, A, B = [int(i) for i in input().split(" ")]




def whetherConnect(i,j):
    score=0
    for i in bin(i^j)[2::]:
        score+=int(i)
    return score==1

history=[A]
visitedFlag=[0 for i in range(2**N)]
visitedFlag[A]=1


for visitedCount in range(1,2**N):
    for i,flag in enumerate(visitedFlag):
        if flag==1:
            continue
        if i==B:
            if visitedCount==2**N-1:
                history.append(B)
                print("YES")
                print(" ".join([str(i) for i in history]))
                sys.exit()
        if whetherConnect(history[-1],i):
            history.append(i)
            visitedFlag[i]=1
            break

print("NO")

Submission status: Runtime Error

Solution code:
def metho(numList):
    if(len(numList)==1):
        return numList
    else:
        temp = metho(numList[1:])
        temp.append(numList[0])
        temp += metho(numList[1:])
        return temp


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

hajime = bin(a^b)
countOne = 0
flag = 0
for i in range(len(str(hajime))-2):
    if(str(hajime)[i+2]=="1"):
        countOne += 1
        flag = len(str(hajime)) - 2 - i
if(countOne!=1):
    print("NO")
else:
    print("YES")
    numList = list(range(1, n+1, 1))
    numList.remove(flag)
    kaeru = []
    kaeru = metho(list(numList))
    temp = kaeru
    kaeru.append(flag)
    kaeru += metho(list(numList))
    temp = a
    ans = []
    ans.append(temp)
    for i in range(len(kaeru)):
        temp = (temp ^ pow(2, int(kaeru[i]-1)))
        ans.append(temp)
    for i in range(len(ans)):
        if(i!=len(ans)-1):  # 最後以外はこっち
            print(ans[i], end=" ")
        else:  # 最後だけ
            print(ans[i])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from bisect import bisect, bisect_left
from collections import defaultdict
from itertools import permutations

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

N, A, B = inpl()
if bin(A^B).count("1")%2:
    print("YES")
    raise
else:
    print("NO")

Submission status: Runtime Error

Solution code:
mod = 1000000007

N = int(input())
C = []
for i in range(N):
    c = int(input())
    if i == 0 or C[-1] != c:
        C.append(c)
cases = [1] * (len(C) + 1)
indexes = dict()
for i in range(1, 1 + len(C)):
    c = C[i - 1]
    if c not in indexes:
        cases[i] = cases[i - 1]
    else:
        cases[i] = (cases[i - 1] + cases[indexes[c]]) % mod
    indexes[c] = i
print(cases[len(C)])

Submission status: Runtime Error

Solution code:

# coding: utf-8

# In[8]:


N,A,B = [int(x) for x in input().split()]


# In[9]:


l = [i^(i>>1) for i in range(2**N)]
["{:0>3b}".format(x) for x in l]


# In[10]:


if l[2**N-1]^l[0]^A == B:
    print("YES")
    ans = [x^X for x in l]
    if ans[0] == B:
        ans.reverse()
    print(" ".join([str(i) for i in ans]))
else:
    print("NO")

Submission status: Runtime Error

Solution code:


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

visited = {}

for i in range(2**N):
	visited.setdefault(i,False)

stack = [A]
visited[A] = True 

def diff1(a,b):
	i = min(a,b)
	j = max(a,b)
	ans = False
	for k in range(N):
		if (j-i) == 2**k:
			if (i%(2**(k+1)))//(2**k)==0:
				ans = True
				break
		else:
			continue
	return ans

answer = []

def df():
	global visited
	global stack
	global B
	global answer
	#print(visited)
	#print(stack)
	#print(answer)
	#スタックが空なら終了
	if stack == []:
		pass
	#スタックが空でなければまず評価を行う
	else:
		#stackの長さが2**Nならその数列を出力すればよい
		if len(stack)==2**N:
			answer = stack
			return stack
		#ノードのdiff1判定がFalseなら深い層に進まない
		elif len(stack)>=2 and diff1(stack[0],stack[1])==False:
			#訪問情報とstackの先頭を削除
			visited[stack[0]] = False
			stack.pop(0)
		#最後の数がBでなければならないので,stackの長さが2**N未満なのにstackにBが含まれていたらそれもダメ
		elif len(stack)<2**N and B in stack:
			#訪問情報とstackの先頭を削除
			visited[stack[0]] = False
			stack.pop(0)
		#どのノードも未訪問か,diff1判定がTrueなら次の層へ
		else:
			for node in list(visited.keys()):
				#未訪問なら
				if visited[node] == False:
					#訪問済みにしたうえでスタックを更新して
					visited[node] = True
					stack = [node] + stack
					#再帰的呼び出し
					df()
				#nodeが訪問済みなら何もしない
				else:
					continue
			#ループを抜けたあとは全子ノードが訪問済みなので
			visited[stack[0]] = False
			stack.pop(0)

df()

if len(answer)>0:
	print('YES')
	print(' '.join([str(x) for x in answer[::-1]+[B]]))
else:
	print('NO')

#深さ優先探索はスタック, 幅優先探索はキュー

#深さ優先探索
#分岐候補をスタックに積む方法ともいえる
#1.探索木の根ノードをスタックに積む
#2.スタックが空なら終了
#3.スタックが空でなければ先頭ノードをチェック
#4.スタック先頭モードの子ノードのうち未探索のものが存在するかどうかを判定
#5-1.未探索の子ノードが存在すれば,そのノードをスタックの先頭に積む
#5-2.2に戻る
#6-1.スタック先頭ノードの子ノードがいずれも探索済みなら,先頭ノードをスタックから1つ削除
#6-2.2に戻る

Submission status: Runtime Error

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

res = None
if N == 1:
	res = [
		None,
		[0b0, 0b1]
	][G]
elif N == 2:
	res = [
		None,
		[0b00, 0b10, 0b11, 0b01],
		[0b00, 0b01, 0b11, 0b10],
		None
	][G]

if res:
	print('YES')
	print(' '.join(f'{A ^ r}' for r in res))
else:
	print('NO')

Submission status: Runtime Error

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

 
numdiff = bin(A ^ B).count("1")


if numdiff >= (2 ** N) or numdiff % 2 == 0:
    print("NO")


else:
    print("YES")
    pos = set()
    for i in range(2 ** N):
        pos.add(i)
    pos.remove(A)
    pos.remove(B)
    ct = 0
    lt = list(bin(A)[2:])
    fb = list(bin(B)[2:])
    if lt == []:
        lt.append("0")
    if len(lt) < len(fb):
            lt = ["0"] * (len(fb) - len(lt)) + lt
    else:
        fb = ["0"] * (len(lt) - len(fb)) + fb
    print(A, end = " ")
    
    while ct < 2 ** N - 2:
        
        for i in range(len(lt)):
            if lt[i] == '1':
                lt[i] = '0'
                if int("".join(lt), 2) not in pos:
                    lt[i] = '1'
                else: break
            else:
                lt[i] = '1'
                if int("".join(lt), 2) not in pos:
                    lt[i] = '1'
                else: break
        
        print(int("".join(lt), 2), end = " ")
        pos.remove(int("".join(lt), 2))
        ct += 1
    print(B)

Submission status: Runtime Error

Solution code:
N, A, B = map(int, input().split())
if N==1:
    print(A, B)
    exit()
elif bin(A^B).count("1")%2==0:
    print("NO")
else:
    raise ValueError

Submission status: Runtime Error

Solution code:
N, A, B = map(int,input())
print("NO")

Submission status: Runtime Error

Solution code:
N, A, B = map(int, input().split())
AB = A ^ B
if bin(AB)[2:].count('1') != 1:
  print('NO')
else:
  print('YES')
  C = [0] * (1 << N)
  C[0] = str(A)
  pos = 0
  while AB % 2 == 0:
    pos += 1
    AB >>= 1
  for i in range(1, 1 << N):
    k = 0
    b = i
    while b % 2 == 0:
      k += 1
      b >>= 1
    A ^= 1 << ((pos + k + 1) % N)
    C[i] = str(A)
print(' '.join(C))

Submission status: Runtime Error

Solution code:
N, A, B = map(int, input().split())
if N==1:
    print(A, B)
    exit()
elif N%2==1:
    print("NO")
else:
    raise ValueError

Submission status: Runtime Error

Solution code:
def rec(v, mask, lst):
    mask |= 1 << v
    nlst = lst[:] + [v]

    # print(v, bin(mask)[2:].zfill(2 ** N), lst, mask, (1 << (1 << N)) - 1)
    if mask == (1 << (1 << N)) - 1:
        if v == B:
            global ans
            ans = nlst
            return True
        else:
            return False

    for nv in g[v]:
        if (mask >> nv) & 1 == 1: continue
        if rec(nv, mask, nlst):
            return


N, A, B = map(int, input().split())
g = [[] for _ in range(1 << N)]

for i in range(1 << N):
    for j in range(N):
        g[i].append(i & ~(1 << j) | ~i & (1 << j))
        # 隣接可能な値

ans = []
rec(A, 0, [])

# print(ans)
if ans:
    print('YES')
    print(*ans)
else:
    print('NO')

Submission status: Runtime Error

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

 
numdiff = bin(A ^ B).count("1")

if numdiff >= 2 * N:
    print("NO")

elif N % 2 == 0 and numdiff % 2 == 0:
    print("NO")
    
elif N % 2 == 1 and numdiff % 2 == 1:
    print("NO")
    
else:
    print("YES")
    ct = 0
    lt = list(bin(A)[2:])
    fb = list(bin(B)[2:])
    if lt == []:
        lt.append("0")
    print(A, end = " ")
    
    while ct < N * 2 - 2:
        if len(lt) < len(fb):
            lt = ["0"] * (len(fb) - len(lt)) + lt
        else:
            fb = ["0"] * (len(lt) - len(fb)) + fb
        if lt == fb:
            if lt[0] == "0":
                lt[0] = "1"
            else:
                lt[1] = "0"
            print(int("".join(lt), 2), end = " ")
        else:
            for i in range(len(lt)):
                if lt[i] == "1" and fb[i] == "0":
                    lt[i] = "0"
                    print(int("".join(lt), 2), end = " ")
                    break
                if lt[i] == "0" and fb[i] == "1":
                    lt[i] = "1"
                    print(int("".join(lt), 2), end = " ")
                    break
        ct += 1
    print(B, end = " ")

Submission status: Runtime Error

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

 
numdiff = bin(A ^ B).count("1")

if numdiff >= 2 * N:
    print("NO")

elif N % 2 == 0 and numdiff % 2 == 0:
    print("NO")
    
elif N % 2 == 1 and numdiff % 1 == 0:
    print("NO")
    
else:
    print("YES")
    ct = 0
    lt = list(bin(A)[2:])
    fb = list(bin(B)[2:])
    print(A, end = " ")
    
    while ct < N * 2 - 2:
        if len(lt) < len(fb):
            lt = ["0"] * (len(fb) - len(lt)) + lt
        else:
            fb = ["0"] * (len(lt) - len(fb)) + fb
        if lt == fb:
            if lt[0] == "0":
                lt[0] = "1"
            else:
                lt[1] = "0"
            print(int("".join(lt), 2), end = " ")
        else:
            for i in range(len(lt)):
                if lt[i] == "1" and fb[i] == "0":
                    lt[i] = "0"
                    print(int("".join(lt), 2), end = " ")
                    break
                if lt[i] == "0" and fb[i] == "1":
                    lt[i] = "1"
                    print(int("".join(lt), 2), end = " ")
                    break
        ct += 1
    print(B, end = " ")