Today Tonnnny the monkey learned a new algorithm called Bogo Sort. The teacher gave Tonnnny the code of Bogo sort:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
The teacher said the shuffle function is to uniformly randomly permute the array a with length n , and the algorithm's expectation complexity is O(n⋅n!).
However, Tonnnny is a determined boy — he doesn't like randomness at all! So Tonnnny improved Bogo Sort. He had chosen one favourite permutation p with length N , and he replaced the random shuffle with shuffle of p , so the improved algorithm, Tonnnny Sort, can solve sorting problems for length N array — at least Tonnnny thinks so.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Tonnnny was satsified with the new algorithm, and decided to let you give him a different array of length N every day to sort it with Tonnnny Sort.
You are the best friend of Tonnnny. Even though you had found the algorithm is somehow wrong, you want to make Tonnnny happy as long as possible. You're given N, p, and you need to calculate the maximum number of days that Tonnnny will be happy, since after that you can't give Tonnnny an array that can be sorted with Tonnnny Sort and didn't appeared before.
The answer may be very large. Tonnnny only like numbers with at most N digits, so please output answer mod10N instead.
AC代码:
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
InputReader ip = new InputReader(System.in);
PrintWriter op = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = ip.nextInt();
int[] p = new int[n + 1];
int[] pf = new int[n + 1];
for (int i = 1; i <= n; ++i) {
p[i] = ip.nextInt();
pf[p[i]] = i;
}
List<Integer> nums = new ArrayList<>();
boolean[] flags = new boolean[n + 1];
for (int i = 1; i <= n; ++i) {
if (flags[i]) continue;
int cnt = 1;
int cur = p[i];
while (true) {
flags[cur] = true;
if (pf[cur] == p[i])
break;
cur = pf[cur];
++cnt;
}
nums.add(cnt);
}
// op.println(nums);
BigInteger ans = new BigInteger(nums.get(0).toString());
BigInteger mod = BigInteger.TEN.pow(n);
for (int i = 1; i < nums.size(); ++i) {
int num = nums.get(i);
BigInteger bigNum = new BigInteger(String.valueOf(num));
BigInteger gcd = ans.gcd(bigNum);
ans = ans.multiply(bigNum).divide(gcd);
}
op.println(ans.mod(mod));
op.flush();
}
}
class InputReader {
private final BufferedReader buf;
private StringTokenizer tkl;
public InputReader(InputStream is) {
buf = new BufferedReader(new InputStreamReader(is));
}
public boolean hasNext() {
try {
while (tkl == null || !tkl.hasMoreElements())
tkl = new StringTokenizer(buf.readLine());
} catch (Exception e) {
return false;
}
return true;
}
public String next() {
return hasNext() ? tkl.nextToken() : null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}