Function
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 365 Accepted Submission(s): 142
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
题解 :
考虑置换 aa 的一个循环节,长度为 ll ,那么有
f(i)=bf(ai)=bbf(aai)=b⋯bf(i)l times b
。
那么 f(i)f(i) 的值在置换 bb 中所在的循环节的长度必须为 ll 的因数。
而如果 f(i)f(i) 的值确定下来了,这个循环节的另外 l - 1l−1 个数的函数值也都确定下来了。
答案就是 \
sum_{i = 1}^{k} \sum_{j | l_i} {j \cdot cal_j}∑i=1k∑j∣lij⋅calj
改为 \
prod_{i = 1}^{k} \sum_{j | l_i} {j \cdot cal_j}∏i=1k ∑j∣li j⋅calj
,其中 kk 是置换 aa 中循环节的个数, l_ili
表示置换 aa 中第 ii 个循环节的长度, cal_jcalj
表示置换 bb 中长度为 jj 的循环节的个数。
时间复杂度是
O(n+m)
。
AC代码:
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
const int MAX = 1e5 + 10;
const int mod = 1e9 + 7;
int a[MAX],b[MAX],num[2][MAX],vis[MAX],n,m;
void dfs(int *p,int o,int nl,int x){
if(vis[o]){
num[x][nl]++; // 循环节为 nl 的个数
return ;
}
vis[o] = 1;
dfs(p,p[o],nl + 1,x);
}
int main()
{
int nl = 0;
while(~scanf("%d %d",&n,&m)){
memset(num,0,sizeof(num));
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]);
for(int i = 0; i < n; i++)
if(!vis[i]) // 计算 a 里面的循环体
dfs(a,i,0,0);
memset(vis,0,sizeof(vis));
for(int i = 0; i < m; i++)
if(!vis[i]) // 计算 b 里面的循环体
dfs(b,i,0,1);
LL ans = 1;
for(int i = 1; i <= n; i++)
if(num[0][i]){
LL sum = 0;
for(int j = 1; j * j <= i; j++){
if(i % j == 0){
sum = (sum + (LL)j * num[1][j] % mod) % mod;
if(j * j != i)
sum = (sum + (LL)i / j * num[1][i / j] % mod) % mod;
}
}
for(int j = 1; j <= num[0][i]; j++)
ans = ans * sum % mod;
}
printf("Case #%d: %lld\n",++nl,ans);
}
return 0;
}