/*
给出一种映射f,问一个序列经过任意次映射的复合,问能得到多少种不同的文本
"he may encrypt the letter for several times. "
here may be ai=aj when i≠j. 不是一一映射
如果是一一映射的,就是一个一个的环了(因为出度、入度为 1)
看watashi的
这题就变成环引出尾巴出来了
答案就成了:max{x[i]} + LCM{y[i]}
x[i]为尾巴长度,y[i]为环长度
注意求x[],y[]数组的方法,用栈
而求LCM时,要分解质因子才行
因为LCM(a%MOD,b%MOD) != LCM(a,b)%MOD
*/
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stack>
#include<map>
using namespace std;
const int MAXN = 1 << 17;
int p[MAXN];
void init()
{
for(int i = 2 ; i < MAXN ; i ++)
{
if(p[i] != 0 )continue;
for(int j = i ; j < MAXN; j += i )
{
p[j] = i;
}
}
}
struct LCM
{
static const long long MOD = 1000000007LL;
map<int,int>mp;
void feed(int x)
{
while(x>1)
{
int p = ::p[x];
int c = 0;
do
{
x /= p;
c ++;
}while(x%p==0);
mp[p] = max(mp[p],c);
}
}
long long lcm()
{
long long ret = 1;
for(map<int,int>::iterator it = mp.begin() ; it != mp.end() ; it++)
{
for(int i =0 ; i < it->second ; i ++)
ret *= it->first;
ret %= MOD;
}
return ret;
}
};
int a[MAXN] , x[MAXN] , y[MAXN];
int main()
{
init();
int n,p,q;
while(~scanf("%d",&n))
{
for(int i = 0 ; i < n ; i ++)
{
scanf("%d",&a[i]);
x[i] = y[i] = -1;
}
for(int i = 0 ; i < n ; i ++)
{
if(x[i]!=-1)
continue;
stack<int>s;
p = i ;
while(true)
{
x[p] = s.size();
s.push(p);
q = a[p];
if(x[q] != -1)
{
if(y[q] == -1)//circle
{
int loop = x[p] - x[q] + 1;
for(int i = 0 ; i < loop ; i ++)
{
p = s.top();
s.pop();
x[p] = 0;
y[p] = loop;
}
}
//else non-circle
break;
}
else
{
p = q;
}
}
while(!s.empty())
{
p = s.top();
s.pop();
x[p] = x[a[p]]+1;
y[p] = y[a[p]];
}
}
LCM lcm;
int base = 0;
scanf("%d",&n);
for(int i = 0 ;i < n ; i++)
{
scanf("%d",&p);
base = max(base , x[p]);
lcm.feed(y[p]);
}
printf("%lld\n" , (base + lcm.lcm())%LCM::MOD);
}
return 0;
}