알고리즘/백준 알고리즘

[백준] 2941 - 크로아티아 알파벳

TIM_0529 2022. 12. 29. 06:24
반응형
#include <iostream>
#include <string>
using namespace std;


int main() {
	char alpa[105];
	int num = 0;
	cin >> alpa;
	int size = strlen(alpa);
	for (int i = 0; i < size; i++)
	{
		if (alpa[i] == 'c'){
			if (alpa[i + 1] == '=') {
				cout << "find = " << alpa[i] << alpa[i + 1] << endl;
				num--;
			}
			else if (alpa[i + 1] == '-') {
				cout << "find = " << alpa[i] << alpa[i + 1] << endl;
				num--;
			}
		}

		if (alpa[i] == 'd') {
			if (alpa[i + 1] == 'z') {
				if (alpa[i + 2] == '=') {
					cout << "find = " << alpa[i] << alpa[i + 1] << endl;
					num--;
				}
			}
			else if (alpa[i + 1] == '-') {
				cout << "find = " << alpa[i] << alpa[i + 1] << endl;
				num--;
			}
		}
		if (alpa[i] == 'l' || alpa[i] == 'n') {
			if (alpa[i + 1] == 'j') {
				cout << "find = " << alpa[i] << alpa[i + 1] << endl;
				num--;
			}
		}
		if (alpa[i] == 's' || alpa[i] == 'z') {
			if (alpa[i + 1] == '=') {
				cout << "find = " << alpa[i] << alpa[i + 1] << endl;
				num--;
			}
		}
	}
	cout << size + num;
}

풀이는 간단하게 모든 경우를 조건으로 걸어놓고 총 합에서 빼는 식으로 했다. C++ 를 사용해서 풀었고 메모리는 2020kb를 차지했다. 

 

다른사람의 코드를 보겠다.

#include <stdio.h>
int main() {
	char a[101] = { 0, };
	int n = 0;
	scanf("%s", a);
	for (int i = 0; a[i] != '\0'; i++) {
		if (a[i] == '=' || a[i] == '-') {
			if (a[i - 2] == 'd'&&a[i - 1] == 'z') n--;
			continue;
		}
		if (a[i] == 'j') {
			if (a[i - 1] == 'l' || a[i - 1] == 'n') continue;
		}
		n++;
	}
	printf("%d", n);
	return 0;
}

더욱 간단하게 풀었고 scanf 와 printf 를 사용해서 메모리와 속도 모두 내가 한 것보다 덜 나왔다. 1112kb 이다.

 

여기서 궁금한게 i 가 = 일 떄 i -2 의 인덱스 위치를 배열 a 에서 찾게 되는데, 만약  i  가  0 번째 자리에 있다고 하면 에러가 나야 정상이다. 근데 이게 왜 정답인지 궁금해서 복사 붙혀넣기 하고 실행해 보니 역시 Visual Studio 에서는 실행이 제대로 되지 않았다.

반응형

'알고리즘 > 백준 알고리즘' 카테고리의 다른 글

[백준] 1712 - 손익분기점  (0) 2022.12.30
[백준] 1316-그룹단어 체커  (2) 2022.12.29
[백준] 5622 - 다이얼  (0) 2022.12.29
[백준] 5622 - 다이얼  (0) 2022.12.29
[백준] 5622 - 다이얼  (0) 2022.12.28