import sys
import time
from itertools import combinations
def get_requests(f=sys.stdin):
"""Read requests from stdin according to problem statement"""
num_requests = int(f.readline())
starts = f.readline().split()
ends = f.readline().split()
return sorted(zip(map(int, starts), map(int, ends)))
def requests_overlap(a, b):
"""Check to see if two requests overlap"""
a, b = sorted((a, b))
return a[1] >= b[0]
def is_valid(requests):
"""Check the validity of a sequence of requests by checking for overlaps"""
for a, b in combinations(requests, 2):
if requests_overlap(a, b):
return False
return True
def int2bit_mask(num, min_length=0):
"""Get the binary representation of a number"""
mask = []
while num:
mask.insert(0, bool(num % 2))
num //= 2
while len(mask) < min_length:
mask.insert(0, False)
return mask
def masks(pop, max_pop):
"""Get all bit masks with a specific population"""
for bits in combinations(range(max_pop), pop):
yield [True if bit in bits else False for bit in range(max_pop)]
def apply_mask(requests, mask):
"""Get the list of requests represented by a bit mask"""
return [r for r,b in zip(requests, mask) if b]
def brute_force(requests):
"""Method #1"""
best_count, best = 0, tuple()
for i in range(2**len(requests)):
masked = apply_mask(requests, int2bit_mask(i, len(requests)))
if len(masked) > best_count and is_valid(masked):
best_count, best = len(masked), masked
return best_count, best
def smarter(requests):
for pop in range(len(requests), 0, -1):
for mask in masks(pop, len(requests)):
masked = apply_mask(requests, mask)
if is_valid(masked):
return pop, masked
if __name__ == '__main__':
requests = get_requests()
start = time.time()
print('Brute force:', brute_force(requests))
end = time.time()
print('Solved in:', end-start)
start = time.time()
print('Ordered masks:', smarter(requests))
end = time.time()
print('Solved in:', end-start)
aW1wb3J0IHN5cwppbXBvcnQgdGltZQpmcm9tIGl0ZXJ0b29scyBpbXBvcnQgY29tYmluYXRpb25zCgpkZWYgZ2V0X3JlcXVlc3RzKGY9c3lzLnN0ZGluKToKICAgICIiIlJlYWQgcmVxdWVzdHMgZnJvbSBzdGRpbiBhY2NvcmRpbmcgdG8gcHJvYmxlbSBzdGF0ZW1lbnQiIiIKICAgIG51bV9yZXF1ZXN0cyA9IGludChmLnJlYWRsaW5lKCkpCiAgICBzdGFydHMgPSBm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ICAgIHJlcXVlc3RzID0gZ2V0X3JlcXVlc3RzKCkKICAgIAogICAgc3RhcnQgPSB0aW1lLnRpbWUoKQogICAgcHJpbnQoJ0JydXRlIGZvcmNlOicsIGJydXRlX2ZvcmNlKHJlcXVlc3RzKSkKICAgIGVuZCA9IHRpbWUudGltZSgpCiAgICBwcmludCgnU29sdmVkIGluOicsIGVuZC1zdGFydCkKICAgIAogICAgc3RhcnQgPSB0aW1lLnRpbWUoKQogICAgcHJpbnQoJ09yZGVyZWQgbWFza3M6Jywgc21hcnRlcihyZXF1ZXN0cykpCiAgICBlbmQgPSB0aW1lLnRpbWUoKQogICAgcHJpbnQoJ1NvbHZlZCBpbjonLCBlbmQtc3RhcnQp
Brute force: (10, [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16), (17, 18), (19, 20)])
Solved in: 0.0040128231048583984
Ordered masks: (10, [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16), (17, 18), (19, 20)])
Solved in: 3.3855438232421875e-05