Post

[BaekJoon] 16895번 - 님 게임 3 [Java][C++]

[BaekJoon] 16895번 - 님 게임 3 [Java][C++]

문제 링크


1. 아이디어


님 게임에서 선공 플레이어가 이기기 위해 할 수 있는 방법의 수를 구하는 문제로 선공에서 게임을 이기려면 Nim-Sum을 0으로 만들어 후공의 악수를 강요해야하므로 첫 턴에 Nim-Sum을 0으로 만들 수 있는 경우의 수를 구하는 것과 같다.

Nim-Sum이 $nim = p_1 \oplus p_2 \oplus p_3 \oplus … \oplus p_n$ 으로 계산됐을 때, 임의의 돌 더미 $p_i$ 의 돌을 $x$ 로 바꾼다면 Nim-Sum은 $nim’ = nim \oplus p_i \oplus x$ 가 된다. 이 $nim’$ 을 0으로 만들 수 있는지 보면 되는데 $0 = nim \oplus p_i \oplus x$ 는 $x = nim \oplus p_i$ 로 쓸 수 있고, 돌을 추가하지 못하고 제거만 가능하므로 $0 \le x < p_i$ 여야 한다. 따라서 $(nim \oplus p_i) < p_i$ 면 해당 돌 더미에서 돌을 제거하는 것으로 선공에서 이길 수 있다.


2. 코드


1. 풀이 [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
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 n = Integer.parseInt(br.readLine());
        int nimsum = 0;

        int[] arr = new int[n];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            nimsum ^= arr[i] = Integer.parseInt(st.nextToken());
        }

        int cnt = 0;
        for (int p : arr) {
            if ((p ^ nimsum) < p) cnt++;
        }

        System.out.println(cnt);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;
    int nimsum = 0;

    vector<int> v(n);
    for (int& p : v) cin >> p;
    for (int p : v) nimsum ^= p;

    int cnt = 0;
    for (int p : v) {
        if ((p ^ nimsum) < p) cnt++;
    }

    cout << cnt;
}

3. 디버깅


없음.


4. 참고


없음.


This post is licensed under CC BY 4.0 by the author.