Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Python 3.7.4
- import sys
- # Given two lists of numbers l1 and l2
- # returns True if l1 is lexicographically less
- # than l2
- def lexicographically_less(l1, l2):
- for i in range(0,len(l1)):
- if l1[i]>l2[i]:
- return False
- return True
- def solve(n, ls):
- def find_sequence(n, ls, prod, seq): #Function to find the sequence with backtracking
- nonlocal ans #Best answer so far
- if prod > n: #If the product is greater than n, we can stop, these cases are not valid
- return
- if prod == n:
- if len(ans)==0: #If this is the first valid sequence found
- ans = seq[:]
- return
- elif len(seq)<len(ans): #If this sequence is shorter than the best answer so far
- ans = seq[:]
- return
- elif len(seq)==len(ans) and lexicographically_less(seq, ans): #If this sequence has the same size and is lexicographically less than the best answer so far
- ans = seq[:]
- return
- for num in ls:
- if num*prod > n: #If the product is greater than n, we can stop, these cases are not valid
- break #Break and not continue because values are sorted, any greater value will only increase the product
- #Backtrack step
- seq.append(num)
- find_sequence(n, ls, prod*num, seq)
- seq.pop()
- ans=[] #Best answer so far
- seq=[1] #Current sequence
- #Remove all repeated elements
- ls = list(set(ls))
- #Sort the list
- ls.sort()
- #Remove all elements that do not divide n
- #They do not contribute to finding a valid
- #sequence
- ls = [x for x in ls if n % x == 0]
- find_sequence(n, ls, 1, seq)
- if len(ans)==0: #Answer not found
- print(-1)
- else: #Answer found
- for num in ans:
- print(num, end=" ")
- print('\n')
- if __name__ == "__main__":
- #Read the input
- n, k = map(int, input().split())
- ls = list(map(int, input().split()))
- #Call the function to solve the problem
- solve(n, ls)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement