개발자/문제풀이 (C언어)
[백준/BOJ] 25501번 재귀의 귀재 (C/C++)
devBB
2024. 1. 8. 21:56
728x90
반응형
백준 온라인 저지(BOJ) 25501번 재귀의 귀재
https://www.acmicpc.net/problem/25501
25501번: 재귀의 귀재
각 테스트케이스마다, isPalindrome 함수의 반환값과 recursion 함수의 호출 횟수를 한 줄에 공백으로 구분하여 출력한다.
www.acmicpc.net
* 사용언어 : C언어, C++
1. 문제
문제에 주어진 함수를 활용하여
각 단어마다 isPalindrome 함수의 반환값과 recursion 함수의 호출 횟수를 출력
2. 풀이
문제에 주어진 코드에서 recursion과 isPalindrome 함수를 하나로 합쳤습니다.
함수의 호출 횟수는 함수의 가장 첫 줄에서 전역 변수로 선언해둔 cnt 값을 1 증가시키도록 하여 계산했습니다.
그 외 풀이는 단순하니 아래 코드로 대체하겠습니다.
3. 코드
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
/*
25501_재귀의 귀재
1112KB 12ms
*/
#include <cstdio>
#include <string.h>
char s[1001];
int T, res, cnt;
int isPalindrome(const char *s, int l, int r) {
++cnt;
if (l >= r) return 1;
else if (s[l] != s[r]) return 0;
else return isPalindrome(s, l + 1, r - 1);
}
int main() {
#ifdef _WIN32
freopen("input.txt", "r", stdin);
#endif // _WIN32
scanf("%d", &T);
while (T--) {
cnt = 0;
scanf("%s", s);
res = isPalindrome(s, 0, strlen(s) - 1);
printf("%d %d\n", res, cnt);
}
return 0;
}
* printf 안 res 자리에 isPalindrome 함수를 그대로 넣으면 cnt 값이 0으로 출력됩니다.
728x90
반응형