Notice
Recent Posts
Recent Comments
Link
250x250
«   2025/05   »
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 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

피너클의 it공부방

백준 9214 첫번째 항 (c++) : 피너클 본문

백준

백준 9214 첫번째 항 (c++) : 피너클

피너클 2022. 4. 27. 01:35
728x90
반응형

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

 

9214번: 첫 번째 항

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 줄에 걸쳐 최대 100글자의 정수 n이 주어지며, 입력의 끝은 0으로 주어진다.

www.acmicpc.net

문자열을 사용하는 구현문제다.

 

int i = 1;
string str;
while (true) {
	cin >> str;
	if (str == "0") break;
	
	cout << "Test " << i << ": " << s(str) << endl;
	i++;
}

int i는 몇번째 테스트인지를 나타낸다.

string str은 입력받을 문자열이다.

계속해서 반복문을 돌리다 0이 입력되면 반복문을 빠져나간다.

"Test i: s(str)"을 출력한뒤 i++을 함으로써 다음 테스트를 준비한다.

string s(string str) {
	if (str.length() % 2 == 1) return str;
	string sam = "";
	for (int i = 0; i < str.length(); i += 2) {
		for (int j = 0; j < str[i] - '0'; j++) sam += str[i + 1];
	}
	if (sam == str) return sam;
	return s(sam);
}

문제를 푸는 함수 s다.

string str을 전달받고 만약 str의 길이가 2의 배수가 아니라면 바로 str을 반환한다.

32211이라면 2가 3개, 1이 2개, 그후 남는 1을 사용할수가 없으니 무조건 반환을 한다.

string sam은 str이전의 문자열이 들어갈 샘플이다.

문자열의 길이만큼 반복하며 i에다가 2를 더해준다.

s[i]는 s[i+1]이 몇번 사용되는지 개수다. s[i]의 수만큼 sam에 s[i+1]을 추가해준다.

그후 만약 sam과 str이 같다면 이전항과 지금의 항이 같다는 뜻이니 그대로 반환해주고

다르다면 다른 이전항이 존재한다는 소리니 s(sam)을 해준다.

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

string s(string str) {
	if (str.length() % 2 == 1) return str;
	string sam = "";
	for (int i = 0; i < str.length(); i += 2) {
		for (int j = 0; j < str[i] - '0'; j++) sam += str[i + 1];
	}
	if (sam == str) return sam;
	return s(sam);
}

int main()
{
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(0);
	int i = 1;
	string str;
	while (true) {
		cin >> str;
		if (str == "0") break;
		
		cout << "Test " << i << ": " << s(str) << endl;
		i++;
	}
}

전체코드다.

728x90
반응형
Comments