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

 

이번에 볼 문제는 백준 24928번 문제인 Magical Runes이다.
문제는 아래 링크를 확인하자.

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

 

24928번: Magical Runes

Input consists of a single line that first begins with a string $S$ followed by an integer $D$. The length of $S$ will be between $1$ and $30$ (inclusive) and $S$ will consist only of characters A and B. The value $D$ satisfies $0≤D<2^{30}$. Fi

www.acmicpc.net

문제에서 주어지는 문자열을 거꾸로 뒤집고, A와 B를 각각 0과 1에 대응시켜보자.

 

이 때, 하루가 지날 때의 문자열의 변화는 0과 1에 대응된 이진수 표현을 기준으로 숫자가 1 증가하는 것과 같다는 점을 관찰하자.

 

따라서 D일이 지났을 때의 이진수 표현은 덧셈을 이용하여 한번에 구할 수 있고, 이를 다시 A와 B의 형태로 표현하는 것으로 문제를 해결할 수 있다.

 

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

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

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

	string S; int d; cin >> S >> d;
	reverse(S.begin(), S.end());
	int Slen = S.length();

	int intS = 0;
	for (auto& l : S) {
		intS <<= 1;
		if (l == 'B') intS++;
	}

	intS = (intS + d) % (1 << Slen);
	for (int i = 0; i < Slen; i++) {
		if (intS & 1) cout << 'B';
		else cout << 'A';
		intS >>= 1;
	}
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 15734 // C++] 명장 남정훈  (0) 2022.06.23
[BOJ 15733 // C++] 나는 누구인가  (0) 2022.06.22
[BOJ 16360 // C++] Go Latin  (0) 2022.06.20
[BOJ 5585 // C++] 거스름돈  (0) 2022.06.19
[BOJ 5588 // C++] 별자리 찾기  (0) 2022.06.19

+ Recent posts