-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb1021.java
55 lines (43 loc) · 1.48 KB
/
b1021.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.io.*;
import java.util.*;
public class b1021 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
LinkedList<Integer> list = new LinkedList<>();
for (int i = 1; i <= n; i++) {
list.add(i);
}
st = new StringTokenizer(br.readLine());
int[] targets = new int[m];
for (int i = 0; i < m; i++) {
targets[i] = Integer.parseInt(st.nextToken());
}
int total = calculateTotal(targets, list);
System.out.println(total);
br.close();
}
private static int calculateTotal(int[] targets, LinkedList<Integer> list) {
int total = 0;
for (int target : targets) {
int idx = list.indexOf(target);
int left = idx;
int right = list.size() - idx;
if (left <= right) {
total += left;
for (int i = 0; i < left; i++) {
list.addLast(list.pollFirst());
}
} else {
total += right;
for (int i = 0; i < right; i++) {
list.addFirst(list.pollLast());
}
}
list.pollFirst();
}
return total;
}
}