import re,copy,sys
sys.setrecursionlimit(2**30)
class linklist():
def __init__(self):
self.head = None
self.last = None
self.size = 0
def push(self,data):
if not self.head:
self.head = tree(data)
self.last = self.head
else:
self.last.next = tree(data)
self.last.next.prev = self.last
self.last = self.last.next
self.size = self.size + 1
def __len__(self):
return self.size
class tree():
def __init__(self,data):
self.data = data
self.children = linklist()
self.father = None
self.number = 0
self.next = None
self.prev = None
self.counter = 0
self.level = 0
self.c1 = []
self.c2 = []
def addchild(self,data):
self.children.push(data)
self.children.last.father = self
self.number += 1
self.children.last.leg = copy.copy(self.leg)
self.children.last.leg.append(data)
self.children.last.level = self.level + 1
def findchild(self,data):
curnode = self.children.head
while True:
if curnode.data == data:
return curnode
curnode = curnode.next
def test(data):
global ind,fat
tmp = copy.copy(fat.leg)
tmp.append(data)
t1 = copy.copy(tmp)
tmp = [main[x] for x in tmp]
if ind == sorted(tmp).index(main[data]):
return True
return False
def chain(typ):
global fat,ind
if typ:
if len(fat.leg) == 5:
return fat.leg
other = [main[x] for x in fat.leg]
ind = sorted(ref[:fat.level+2]).index(ref[fat.level+1])
fat.c1=[x for x in range(fat.data+1,leng) if (main[fat.data]-main[x]) \
*(ref[fat.level]-ref[fat.level+1]) > 0 and main[x] not in other]
fat.c1 = [x for x in fat.c1 if test(x)]
if len(fat.c1) > 0:
fat.addchild(fat.c1[0])
fat.c2.append(fat.c1[0])
fat = fat.findchild(fat.c1[0])
return chain("abracadabra")
else:
if not fat.father:
return None
else:
fat = fat.father
return chain(None)
else:
temp = [x for x in fat.c1 if x not in fat.c2]
if len(temp) == 0:
if not fat.father:
return None
else:
fat = fat.father
return chain(None)
else:
fat.c2.append(temp[0])
fat.addchild(temp[0])
fat = fat.findchild(temp[0])
return chain("abracadabra")
count = int(raw_input())
for cc in range(count):
leng,ref = [int(x) for x in re.findall("""\d+""",raw_input())]
main = [int(x) for x in re.findall("""-?\d+""",raw_input())]
ref = [int(x)-1 for x in str(ref)]
ran = leng - 5
for i in range(ran + 1):
fat = tree(i)
fat.leg = [i]
res = chain("abracdabra")
if res:
break
if res:
print " ".join([str(x) for x in res])
else:
print -1
This post has been edited by cupidvogel: 06 February 2012 - 09:37 AM

New Topic/Question
Reply




MultiQuote



|