File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed
Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ ```java
2+
3+ import java.io.*;
4+ import java.util.*;
5+
6+ public class Main {
7+ public static void main(String[] args) throws IOException {
8+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
9+
10+ int N = Integer.parseInt(br.readLine());
11+
12+ int[] P = new int[N];
13+ StringTokenizer st = new StringTokenizer(br.readLine());
14+ for (int i = 0; i < N; i++) {
15+ P[i] = Integer.parseInt(st.nextToken());
16+ }
17+
18+ int[] S = new int[N];
19+ st = new StringTokenizer(br.readLine());
20+ for (int i = 0; i < N; i++) {
21+ S[i] = Integer.parseInt(st.nextToken());
22+ }
23+
24+ int[] current = new int[N];
25+ for (int i = 0; i < N; i++) {
26+ current[i] = i;
27+ }
28+
29+ boolean isGoal = true;
30+ for (int i = 0; i < N; i++) {
31+ if (current[i] % 3 != P[i]) {
32+ isGoal = false;
33+ break;
34+ }
35+ }
36+
37+ if (isGoal) {
38+ System.out.println(0);
39+ return;
40+ }
41+
42+ int maxAttempts = 500000;
43+
44+ for (int shuffle = 1; shuffle <= maxAttempts; shuffle++) {
45+ int[] next = new int[N];
46+ for (int i = 0; i < N; i++) {
47+ next[i] = current[S[i]];
48+ }
49+ current = next;
50+
51+ boolean success = true;
52+ for (int i = 0; i < N; i++) {
53+ if (current[i] % 3 != P[i]) {
54+ success = false;
55+ break;
56+ }
57+ }
58+
59+ if (success) {
60+ System.out.println(shuffle);
61+ return;
62+ }
63+
64+ if (shuffle > 1) {
65+ boolean backToStart = true;
66+ for (int i = 0; i < N; i++) {
67+ if (current[i] != i) {
68+ backToStart = false;
69+ break;
70+ }
71+ }
72+ if (backToStart) {
73+ System.out.println(-1);
74+ return;
75+ }
76+ }
77+ }
78+
79+ System.out.println(-1);
80+ }
81+ }
82+ ```
You can’t perform that action at this time.
0 commit comments