[BaekJoon] #11868 - 님 게임 2 [Java][C++]
[BaekJoon] #11868 - 님 게임 2 [Java][C++]
1. 아이디어
님 게임에서 모든 더미의 돌 개수를 XOR한 Nim-Sum이 0인지만 보면 되는 문제다. Nim-Sum이 0이 아니면 Nim-Sum의 최상위 비트가 켜진 더미 하나를 골라 그 더미를 원래 크기와 Nim-Sum의 XOR 값으로 줄일 수 있고 이 값은 원래 크기보다 작으므로, 선공이 Nim-Sum을 0으로 만들어 넘길 수 있다. 반대로 Nim-Sum이 0이면 더미 하나만 바꾸는 이동으로는 Nim-Sum이 반드시 0이 아니게 되어 후공이 다시 0으로 되돌릴 수 있고, 모든 돌이 사라진 상태의 Nim-Sum도 0이므로 마지막 돌은 0을 만들어 넘기는 쪽이 가져간다. 결국 Nim-Sum이 0이 아니면 선공이, 0이면 후공이 이긴다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = 입력값 n)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int nimsum = 0;
int n = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
while (n-- > 0) {
nimsum ^= Integer.parseInt(st.nextToken());
}
if (nimsum != 0) {
System.out.println("koosaga");
} else {
System.out.println("cubelover");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int nimsum = 0;
int n;
cin >> n;
while (n--) {
int p;
cin >> p;
nimsum ^= p;
}
if (nimsum) {
cout << "koosaga";
} else {
cout << "cubelover";
}
}
This post is licensed under CC BY 4.0 by the author.