-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbaekjoon_1158.java
66 lines (58 loc) · 1.54 KB
/
baekjoon_1158.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
56
57
58
59
60
61
62
63
64
65
66
package com.ssafy.algo;
import java.util.Scanner;
public class baekjoon_1158 {
static class MyLinkedList {
MyLinkedList prev;
MyLinkedList next;
int val;
public MyLinkedList(int val) {
this.val = val;
this.prev = null;
this.next = null;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// data input
int N = sc.nextInt();
int M = sc.nextInt();
MyLinkedList head = new MyLinkedList(1);
MyLinkedList tail = head;
for (int i = 2; i <= N; ++i) {
MyLinkedList next = new MyLinkedList(i);
tail.next = next;
next.prev = tail;
tail = next;
}
tail.next = head; // make circular
head.prev = tail;
// solve
MyLinkedList target = head;
int[] res = new int[N]; // output order res array
int resIdx = 0;
while (resIdx != N) {
if (target.next != null) {
// find next target from current location
for (int i = 0; i < M - 1; ++i) {
target = target.next;
}
// add current output to res array
res[resIdx++] = target.val;
// remove current element and update next target
MyLinkedList nextTarget = target.next;
target.next.prev = target.prev;
target.prev.next = target.next;
target.next = null;
target.prev = null;
target.val = -1;
target = nextTarget;
}
}
// data output
System.out.print("<");
for (int i = 0; i < resIdx - 1; ++i) {
System.out.print(res[i] + ", ");
}
System.out.println(res[resIdx - 1] + ">");
} // end of main
} // end of class