【递归+记忆搜索C++】P1464 Function

题目:
https://www.luogu.com.cn/problem/P1464?contestId=30130

思路:
记忆化搜索,其实跟暴力搜索差不多,就是把得到的每一个答案都存起来,再次用到的时候直接使用就可以了。
这个题也是这个意思,把已经求出的结果存起来,用到时直接用,不用再计算

上代码:

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define ll long long
ll a,b,c;
ll num[25][25][25]={0};

ll w(ll a1, ll b1, ll c1)
{
    if(a1<=0 || b1<=0 || c1<=0)
        return 1;
    else if(a1>20 || b1>20 || c1>20)
       return w(20,20,20);
    if(num[a1][b1][c1])
        return num[a1][b1][c1];
    if(a1<b1 && b1<c1)
       num[a1][b1][c1] = w(a1,b1,c1-1) + w(a1,b1-1,c1-1) - w(a1,b1-1,c1);
    else
       num[a1][b1][c1] = (w(a1-1,b1,c1) + w(a1-1,b1-1,c1) + w(a1-1,b1,c1-1) - w(a1-1,b1-1,c1-1));
    return num[a1][b1][c1];

}


int main()
{
    memset(num,0,sizeof(num));
    while(cin>>a>>b>>c)
    {
        if(a==-1 && b==-1 && c==-1)
            break;
        cout<<"w("<<a<<", "<<b<<", "<<c<<") = "<<w(a,b,c)<<endl;
   

    }


}

你可能感兴趣的:(算法)