※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 24930번 문제인 Ordinary Ordinals이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/24930 

 

24930번: Ordinary Ordinals

Sets, sets, sets. Everything in math is just a set. Even the natural numbers can be represented as sets. For example, we can represent the the number $0$ as the empty set $\{\}$. The number $1$ can be represented as $\{\{\}\}$. But what about $2$? Conside

www.acmicpc.net

직접 괄호와 콤마의 개수를 직접 세어보면 괄호의 개수는 i=0부터 순서대로 2 4 8 16 32 64...로 나타난다.

 

또한 콤마의 개수는 i=0부터 순서대로 0 0 1 3 7 15... 로 나타난다.

 

위와 같은 나열에서 규칙이 쉽게 눈에 띄므로, 해당 규칙대로 값을 계산하여 출력하자. 이와 같은 규칙이 모든 i에 대하여 항상 성립한다는 것을 보이는 것은 어렵지 않다.

 

입력으로 들어오는 N이 2^63으로 매우 크니 점화식을 선형적으로 계산해나가는 것은 무리이다. 대신 binary exponentiation을 이용하여 문제를 해결하자.

 

아래는 제출한 소스코드이다.

#include <iostream>
using namespace std;
typedef long long ll;

ll N, NN, MOD;

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

	cin >> N >> MOD;
	if (N == 0) cout << 2 % MOD;
	else if (N == 1) cout << 4 % MOD;
	else {
		NN = max(N - 1, 0LL);

		ll ans1 = 1;
		ll tmp1 = 2;
		while (N) {
			if (N & 1) ans1 = (ans1 * tmp1) % MOD;
			N >>= 1;
			tmp1 = (tmp1 * tmp1) % MOD;
		}

		ans1 = (ans1 * 2) % MOD;

		ll ans2 = 1;
		ll tmp2 = 2;
		while (NN) {
			if (NN & 1) ans2 = (ans2 * tmp2) % MOD;
			NN >>= 1;
			tmp2 = (tmp2 * tmp2) % MOD;
		}

		if (ans2 > 0) ans2--;
		else ans2 = MOD - 1;

		cout << (ans1 + ans2) % MOD;
	}
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 23397 // C++] Katmandu  (0) 2022.04.17
[BOJ 24408 // C++] Mult!  (0) 2022.04.17
[BOJ 23854 // C++] The Battle of Giants  (0) 2022.04.17
[BOJ 24793 // C++] Shiritori  (0) 2022.04.17
[BOJ 24356 // C++] ЧАСОВНИК  (0) 2022.04.17

+ Recent posts