Baekjoon/Silver

C++ / 백준 / 21314 / 민겸 수

GitHubSeob 2023. 7. 7. 20:56
문제

 

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

 

21314번: 민겸 수

민겸 수 하나가 주어진다. 민겸 수는 대문자 M과 K로만 이루어진 문자열이며, 길이는 3,000을 넘지 않는다.

www.acmicpc.net

 

문제풀이

 

가장 큰 수는 K가 나올 때까지 기다렸다가 K가 나오면 M과 합치면 된다.

K가 나오지 않은 채로 끝나면 남은 M들은 다 1로 바꿔야 가장 큰 수가 된다.

 

가장 작은 수는 K가 나오면 바로바로 5를 더한다.

 

string largest(string num) {
	int idx(0), idx2(0), m_cnt(0);
	string answer("");

	for (idx = 0; idx < num.size(); ++idx) {
		if (num[idx] == 'M') {
			++m_cnt;
		}
		else if (num[idx] == 'K') {
			answer += '5';
			answer.insert(answer.size(), m_cnt, '0');
			m_cnt = 0;

		}
		if (idx + 1 == num.size()) {
			answer.insert(answer.size(), m_cnt, '1');
		}
	}
	return answer;
}

가장 큰 수를 만드는 함수이다. M이 나오면 개수를 센다.

K가 나오면 5를 더하고, 이전 m의 개수만큼 0을 더한다.

K가 아닌 M으로 끝나는 경우가 있으므로 마지막 조건문으로 이전 m의 개수만큼 1을 더한다.

변환 과정을 함수로 만들었으므로 답을 return 한다.

 

string smallest(string num) {
	int idx(0), idx2(0), m_cnt(0);
	string answer("");

	for (idx = 0; idx < num.size(); ++idx) {
		if (num[idx] == 'M') {
			(idx == 0 || num[idx - 1] == 'K') ? answer += '1' : answer += '0';
		}
		else if (num[idx] == 'K') {
			answer += '5';
		}
	}
	return answer;
}

가장 작은 수를 만드는 과정이다.

K를 만나는 순간은 바로 5를 적어야 가장 작은 수가 된다. (MK -> 50 or 15)

 

M인 경우에는 1 또는 0을 더하는 경우이다.

첫 문자이거나, 이전 문자가 K인 경우 1을 더한다.

그 외의 경우는 0을 더하면 된다.

 

코드
#include <iostream>
#include <string>
using namespace std;

string largest(string num) {
	int idx(0), idx2(0), m_cnt(0);
	string answer("");

	for (idx = 0; idx < num.size(); ++idx) {
		if (num[idx] == 'M') {
			++m_cnt;
		}
		else if (num[idx] == 'K') {
			answer += '5';
			answer.insert(answer.size(), m_cnt, '0');
			m_cnt = 0;

		}
		if (idx + 1 == num.size()) {
			answer.insert(answer.size(), m_cnt, '1');
		}
	}
	return answer;
}

string smallest(string num) {
	int idx(0), idx2(0), m_cnt(0);
	string answer("");

	for (idx = 0; idx < num.size(); ++idx) {
		if (num[idx] == 'M') {
			(idx == 0 || num[idx - 1] == 'K') ? answer += '1' : answer += '0';
		}
		else if (num[idx] == 'K') {
			answer += '5';
		}
	}
	return answer;
}


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

	int idx(0);
	string num("");
	cin >> num;

	cout << largest(num) << '\n';
	cout << smallest(num);
}