题目链接
题目简述
有两行数,都是 的排列,你可以交换一列上的两个数。问,有多少个数阵中一行中没有同样的两个数。答案对 取模。
解题思路
我们先看个样例:
1 2 3 4 5
5 3 4 2 1
如果我们要将第一列交换,为了满足规则,必然要将第五列交换。
我们设 表示第一行的第 个数, 表示第二行中 的位置。
那么我们交换第 列,就必须交换第 列,然后一直交换,直到第 列已经被交换了,这就是一个置换环。
设有 个置换环,则答案是 。
代码
#include<bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const int N = 4e5 + 10;
int a[N], b[N], m[N];
bool vis[N];
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
memset(vis, 0, sizeof vis);
for(int i = 1; i <= n;i ++)
cin >> a[i];
for(int i = 1; i <= n; i++)
cin >> b[i], m[b[i]] = i;
long long ans = 1;
for(int i = 1; i <= n; i++){
if(vis[a[i]])continue;
ans *= 2, ans %= mod;
for(int j = i; !vis[a[j]]; j = m[a[j]])
vis[a[j]] = 1;
}
cout << ans << endl;
}
}