置换 2020牛客暑期多校训练营(第二场)J Just Shuffle
标签: 置换 JAVA大数 逆元 快速幂
题意:P为一个置换,
P
k
=
A
P^k=A
Pk=A,k是素数,求P
k是大素数,所以A的每个轮换的周期都小于k且与k互素,因此A的周期与k互素,我们可以构造x为k对于A周期m的逆元
x
k
≡
1
(
m
o
d
m
)
xk\equiv1\pmod m
xk≡1(modm)
则
A
x
k
=
A
A^{xk}=A
Axk=A
则
A
x
A^x
Ax则为我们想要的P
只要先解出x,快速幂求
A
x
A^x
Ax就可以作为一个答案
import java.math.BigInteger;
import java.util.*;
public class Main {
final static int maxn=200100;
static int a[]=new int[maxn];
static int a_copy[]=new int[maxn];
static int ans[]=new int[maxn];
static int ans_copy[]=new int[maxn];
static boolean vis[]=new boolean[maxn];
static BigInteger d,x,y;
static int n;
public static void main(String args[]) {
BigInteger k;
Scanner input=new Scanner(System.in);
n=input.nextInt();
k=input.nextBigInteger();
for(int i=1;i<=n;i++) {
a[i]=input.nextInt();
ans[i]=i;
}
BigInteger LCM=BigInteger.ONE;
for(int i=1;i<=n;i++) {
if(!vis[i]) {
long cnt=0;
int cur=i;
while(!vis[cur]){
vis[cur]=true;
cnt++;
cur=a[cur];
}
LCM=lcm(LCM,BigInteger.valueOf(cnt));
}
}
BigInteger x=inverse(k,LCM);
if(x.longValue()==-1){
System.out.println("-1");
}
else {
quick_pow(x);
for(int i=1;i<=n;i++){
System.out.print(ans[i]);
if(i==n)
System.out.print("\n");
else
System.out.print(" ");
}
}
}
public static BigInteger lcm(BigInteger x,BigInteger y) {
return x.multiply(y).divide(x.gcd(y));
}
public static BigInteger[] extgcd(BigInteger a,BigInteger b){
BigInteger[] tmp=new BigInteger[3];
if(b.longValue()==0){
tmp[0]=a;
tmp[1]=BigInteger.ONE;
tmp[2]=BigInteger.ZERO;
}
else{
tmp=extgcd(b,a.mod(b));
BigInteger Tmp=tmp[1];
tmp[1]=tmp[2];
tmp[2]=Tmp;
tmp[2]=tmp[2].subtract(tmp[1].multiply(a.divide(b)));
}
return tmp;
}
public static BigInteger inverse(BigInteger a,BigInteger n){
BigInteger[] tmp=new BigInteger[3];
tmp=extgcd(a,n);
if(tmp[0].longValue()==1){
tmp[1] = (tmp[1].mod(n).add(n)).mod(n);
if(tmp[1].longValue()==0)
tmp[1]=tmp[1].add(n);
}
else
tmp[1] = BigInteger.valueOf(-1);
return tmp[1];
}
public static void quick_pow(BigInteger x){
while(x!=BigInteger.ZERO){
if(x.mod(BigInteger.valueOf(2)).longValue()==1){
for(int i=1;i<=n;i++){
ans_copy[i]=ans[i];
}
for(int i=1;i<=n;i++){
ans[i]=ans_copy[a[i]];
}
}
for(int i=1;i<=n;i++){
a_copy[i]=a[i];
}
for(int i=1;i<=n;i++){
a[i]=a_copy[a_copy[i]];
}
x=x.divide(BigInteger.valueOf(2));
}
}
}