출처: https://www.hackerrank.com/challenges/absolute-permutation/problem
단순히 완전 순열을 구성해서는 해결되지 않았다.
[패턴 분석] - Output을 보기 좋게 구조화
Input
1
100 2
Output
3 4 1 2 7 8 5 6 11 12 9 10 15 16 13 14 19 20 17 18
23 24 21 22 27 28 25 26 31 32 29 30 35 36 33 34
39 40 37 38 43 44 41 42 47 48 45 46 51 52 49 50
55 56 53 54 59 60 57 58 63 64 61 62 67 68 65 66
71 72 69 70 75 76 73 74 79 80 77 78 83 84 81 82
87 88 85 86 91 92 89 90 95 96 93 94 99 100 97 98
문제에서 요구한 형태를 만족하기 위해서는
n % (2 * k) == 0 이어야 한다.
위의 패턴을 수치적으로 분석해보면 (k = 3이라고 가정)
i = 1 일 때, arr[i] = 1 + 3 = 4
i = 2 일 때, arr[i] = 2 + 3 = 5
i = 3 일 때, arr[i] = 3 + 3 = 6
i = 4 일 때, arr[i] = 4 - 3 = 1
i = 5 일 때, arr[i] = 5 - 3 = 2
i = 6 일 때, arr[i] = 6 - 3 = 3
i = 7 일 때, arr[i] = 7 + 3 = 10
...
▶ (2 * k) 단위로 반복되므로 n개는 해당 수치에 나누어 떨어져야 한다.
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = Integer.parseInt(sc.next());
while(tc-- > 0) {
int n = Integer.parseInt(sc.next());
int k = Integer.parseInt(sc.next());
if (k == 0) {
for(int i=0; i < n; i++) {
System.out.print((i+1) + " ");
}
}
else if(n % (2*k) == 0) {
for(int i=1; i <= n; i++) {
int val = (i % (2*k) == 0) ? 2*k : i % (2*k);
if(val <= k) System.out.print((i + k) + " ");
else System.out.print((i - k) + " ");
}
}
else {
System.out.print(-1);
}
System.out.println();
}
}
}
'PS 문제 풀이 > HackerRank' 카테고리의 다른 글
[HackerRank] Almost Sorted (Java) (0) | 2021.02.14 |
---|---|
[HackerRank] Cut the sticks (Java) (0) | 2021.02.14 |
[HackerRank] Kangaroo (Java) (0) | 2021.02.14 |
[HackerRank] The Power Sum (0) | 2021.02.14 |
[HackerRank] Jumping on the Clouds (0) | 2021.02.14 |
댓글