import sys import sys import math MOD = 10**9 + 7 def extended_gcd(a, b): if b == 0: return (a, 1, 0) else: g, y, x = extended_gcd(b, a % b) y -= (a // b) * x return (g, x, y) def mod_inverse(a, m): g, x, y = extended_gcd(a, m) if g !=1: return 0 else: return x % m def main(): import sys import sys sys.setrecursionlimit(1 << 25) N_and_rest = sys.stdin.read().split() N = int(N_and_rest[0]) A = list(map(int, N_and_rest[1:N+1])) B = list(map(int, N_and_rest[N+1: 2*N+1])) # Find cycles in A visited_A = [False]*(N+1) cycle_A = {} cycle_len_A = {} pos_in_cycle_A = {} for i in range(1, N+1): if not visited_A[i]: cycle = [] x = i while not visited_A[x]: visited_A[x] = True cycle.append(x) x = A[x-1] La = len(cycle) for idx, z in enumerate(cycle): cycle_A[z] = cycle cycle_len_A[z] = La pos_in_cycle_A[z] = idx # Find cycles in B visited_B = [False]*(N+1) cycle_B = {} cycle_len_B = {} pos_in_cycle_B = {} for i in range(1, N+1): if not visited_B[i]: cycle = [] x = i while not visited_B[x]: visited_B[x] = True cycle.append(x) x = B[x-1] Lb = len(cycle) for idx, z in enumerate(cycle): cycle_B[z] = cycle cycle_len_B[z] = Lb pos_in_cycle_B[z] = idx total =0 for z in range(1, N+1): La = cycle_len_A[z] Lb = cycle_len_B[z] g = math.gcd(La, Lb) La_g = La // g Lb_g = Lb // g inv_La_g = mod_inverse(La_g, Lb_g) if Lb_g ==0: inv_La_g =0 # Calculate term1 and term2 term1 = (La_g * Lb_g * (g -1)) //2 term2 = (La * inv_La_g * (Lb_g * (Lb_g -1)) ) //2 total = (total + term1 + term2) % MOD print(total) if __name__ == "__main__": main()