/*hdu6038[找规律+循环节] 2017多校1*/ #include<bits/stdc++.h> using namespace std; typedef long long LL; const double eps=1e-8; const int inf=0x3f3f3f3f; const int mod=1000000007; int n,m,lop,kase=1,maxlop; int a[100005],b[100005],mark[100005]; LL Arep[100005],Brep[100005]; LL fastpow(LL a,LL b){ LL ret=1,x=a; while(b){ if(b&1){ ret=(ret*x)%mod; } x=(x*x)%mod; b>>=1; } return ret; } void dfs(int now,int dps){ if(mark[now]){ Arep[dps]++; return; } mark[now]=1; dfs(a[now],dps+1); } void dfs2(int now,int dps){ if(mark[now]){ Brep[dps]++; return; } mark[now]=1; dfs2(b[now],dps+1); } void solve(){ maxlop=0; for(int i=0;i<n;i++){ if(!mark[a[i]]){ dfs(i,0); } } memset(mark,0,sizeof(mark)); for(int i=0;i<m;i++){ if(!mark[b[i]]){ dfs2(i,0); } } memset(mark,0,sizeof(mark)); LL ans=0,sum=1; for(int i=1;i<=n;i++){ if(Arep[i]){ ans=0; for(int j=1;j*j<=i;j++){ if(i%j==0){ ans=(ans+(Brep[j]%mod)*(j%mod))%mod; if(j*j!=i){ ans=(ans+(Brep[i/j]%mod)*((i/j)%mod))%mod; } } } sum=(sum*fastpow(ans,Arep[i]))%mod; } } printf("Case #%d: %lld ",kase++,sum); } int main(){ //freopen("1006.txt","r",stdin); //freopen("out.txt","w",stdout); while(~scanf("%d%d",&n,&m)){ memset(mark,0,sizeof(mark)); memset(Arep,0,sizeof(Arep)); memset(Brep,0,sizeof(Brep)); for(int i=0;i<n;scanf("%d",&a[i]),i++); for(int i=0;i<m;scanf("%d",&b[i]),i++); solve(); } return 0; }