5で割り切れて2で割り切れない場合に分岐させつつBFS
import sys def halve(numbers): return [int(n / 2) for n in numbers] def sweep(numbers): return [n for n in numbers if n % 5 != 0] def get_data(f): N = int(f.readline()) numbers = [int(n) for n in f.readline().split()] return (N, numbers) def is_sweep_ok(numbers): for n in numbers: if n % 5 != 0: return False return True def calc_cycle(numbers_set, count): #print numbers_set new_numbers_set = [] for numbers in numbers_set: if is_sweep_ok(numbers): return count else: new_numbers_set.append(halve(numbers)) for number in numbers: if (number % 5 == 0 and number % 2 != 0): new_numbers_set.append(sweep(numbers)) break return calc_cycle(new_numbers_set, count + 1) if __name__ == '__main__': with open(sys.argv[1]) as f: T = int(f.readline()) total_count = 0 while(total_count < T): N, numbers = get_data(f) if len(numbers) != N: print "error invalid numbers" print calc_cycle([numbers], 1) total_count += 1