Problem Description
You are given a permutation a from 0 to n−1 and a permutation b from 0 to m−1.
Define that the domain of function f is the set of integers from 0 to n−1, and the range of it is the set of integers from 0 to m−1.
Please calculate the quantity of different functions f satisfying that f(i)=bf(ai) for each i from 0 to n−1.
Two functions are different if and only if there exists at least one integer from 0 to n−1 mapped into different integers in these two functions.
The answer may be too large, so please output it in modulo 109+7.
Input
The input contains multiple test cases.
For each case:
The first line contains two numbers n, m. (1≤n≤100000,1≤m≤100000)
The second line contains n numbers, ranged from 0 to n−1, the i-th number of which represents ai−1.
The third line contains m numbers, ranged from 0 to m−1, the i-th number of which represents bi−1.
It is guaranteed that ∑n≤106, ∑m≤106.
Output
For each test case, output “Case #x: y” in one line (without quotes), where x indicates the case number starting from 1 and y denotes the answer of corresponding case.
Sample Input
3 2
1 0 2
0 1
3 4
2 0 1
0 2 3 1
Sample Output
Case #1: 4
Case #2: 4
题目大意:有两个,数组a是[0~n-1]的排列,数组b是[0~m-1]的排列。现在定义f(i)=b[f(a[i])];
问f(i)有多少种取值,使得表达式f(i)=b[f(a[i])]全部合法。
解题思路:猛的一看可能感觉无从下手,不知道该怎么办,但由题目f(i)=b[f(a[i])]可以递推出f(i)=b[f(a[i])]=b[b[f(a[a[i]])]],以此类推,可以一直递推下去,我们可以得到i->a[i]->a[a[i]]->a[a[a[i]]]··· ···->i这样的一个环以第一个样例 a={1,0,2} b={0,1}为例:
那么f(0)=b[f(1)] f(1)=b[f(0)] f(2)=b[f(2)]
这里有两个环分别为 f(0)->f(1) 和f(2)
所以我们的任务就是在b中找环,该环的长度必须为a中环的长度的约数。为什么必须的是约数呢?因为如果b的环的长度是a的环的长度的约数的话,那也就意味着用b这个环也能构成a这个环,只不过是多循环了几次而已。然后找到a中所有环的方案数,累乘便是答案。
为什么要累乘呢?我最开始一直以为要累加。这个就用到了排列组合的思想,因为肯定要f(i)肯定要满足所有的数,而a中的每个环都相当于从a中取出几个数的方案数,所以总共的方案数应该累乘。
#include <bits/stdc++.h>
const int mod=1e9+7;
typedef long long LL ;
using namespace std;
int a[100005],b[100005],vis[100005];
vector<int> fac[100010];
void get_fac()
{
for(int i = 1; i <= 100000; i++){
for(int j = i; j <= 100000; j+=i)
fac[j].push_back(i);
}
}
int dfs(int aa[],int n)
{
if(vis[n])
return 0;
vis[n] = 1;
return dfs(aa,aa[n])+1;
}
int main()
{
int n,m,c=1;
get_fac();
while(~scanf("%d %d",&n,&m)){
memset(vis,0,sizeof(vis));
for(int i = 0; i < n; i++)
scanf("%d",&a[i]);
for(int i = 0; i < m; i++)
scanf("%d",&b[i]);
vector<int> A;
int B[100005];
memset(B,0,sizeof(B));
for(int i = 0; i < n; i++)
if(!vis[i])
A.push_back(dfs(a,i));
memset(vis,0,sizeof(vis));
for(int i = 0; i < m; i++)
if(!vis[i])
B[dfs(b,i)]++;
int la,lb,len;
LL ans = 1;
for(int i = 0; i < A.size(); i++)
{
la = A[i];
LL temp = 0;
len = fac[la].size();
for(int j = 0; j < len; j++){
lb = fac[la][j];
temp = (temp + (long long)(lb*B[lb]))%mod;
}
ans = (ans*temp)%mod;
}
printf("Case #%d: %lld\n",c++,ans);
}
return 0;
}