[ BOJ / C++ ] 9184번 신나는 함수 실행

황승환·2021년 8월 9일
0

C++

목록 보기
32/65

이번 문제는 주어진 조건들을 이용하여 재귀함수를 구현하는 문제였다.

  • int형으로 재귀함수를 정의한다.
  • 위의 제약 조건들을 입력한다.
  • 재귀 함수의 결과가 여러번 더해지는 경우에는 result에 값을 저장하고 result를 반환한다.
  • 무한 루프인 while문 안에서 a,b,c를 입력받고, a,b,c가 모두 -1일 때까지 반복한다.

Code

#include <iostream>
#include <cstring>
#define MAX 21
using namespace std;
int a, b, c;
int cache[MAX][MAX][MAX];

void Input(){
    cin>>a>>b>>c;
}

int w(int a, int b, int c){
    if(a<=0||b<=0||c<=0)
        return 1;
   
    if(a>=MAX||b>=MAX||c>=MAX)
        return w(20, 20, 20);
    int &result = cache[a][b][c];
    if (result != 0)
        return result;
    if (a < b && b < c)
        result=w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c);
    else
        result=w(a-1,b,c)+w(a-1,b-1,c)+w(a-1,b,c-1)-w(a-1,b-1,c-1);
    return result;
}


int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    while(1){
        Input();
        if(a==-1&&b==-1&&c==-1)
            break;
        cout<<"w("<<a<<", "<<b<<", "<<c<<") = "<<w(a,b,c)<<endl;
    }
    return 0;
}

profile
꾸준함을 꿈꾸는 SW 전공 학부생의 개발 일기

0개의 댓글