import math def main(): n = int(input()) a_size = int(input()) a = list(map(int, input().split())) c_size = int(input()) c = list(map(int, input().split())) # Sort A's cards in descending order a_sorted = sorted(a, reverse=True) if not a_sorted: print(0) return max_a = a_sorted[0] # Split C's cards into beatable and unbeatable, then sort each group descending beatable = [d for d in c if d < max_a] unbeatable = [d for d in c if d >= max_a] c_sorted = sorted(beatable, reverse=True) + sorted(unbeatable, reverse=True) len_a = len(a_sorted) len_c = len(c_sorted) if len_c == 0: print(0) return # Calculate LCM of len_a and len_c def lcm(x, y): return x * y // math.gcd(x, y) if x and y else 0 lcm_ac = lcm(len_a, len_c) # Calculate victories per cycle per_cycle = 0 for i in range(lcm_ac): a_idx = i % len_a c_idx = i % len_c if a_sorted[a_idx] > c_sorted[c_idx]: per_cycle += 1 full_cycles = n // lcm_ac remainder = n % lcm_ac total = full_cycles * per_cycle # Calculate victories in remainder for i in range(remainder): a_idx = i % len_a c_idx = i % len_c if a_sorted[a_idx] > c_sorted[c_idx]: total += 1 print(total) if __name__ == "__main__": main()