求助,一直MLE

P1464 Function

Lienqwq @ 2022-05-21 14:40:40


#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll f[25][25][25],a,b,c;
ll w(ll a,ll b,ll c)
{
    if(a<=0||b<=0||c<=0)return 1;
    else if(a>20||b>20||c>20)return w(20,20,20);
    else if(f[a][b][c]!=0)return w(20,20,20);
    else if(a<b&&b<c) f[a][b][c]=w(a,b-1,c-1)-w(a,b-1,c);
    else f[a][b][c]=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 f[a][b][c];
}
int main()
{
    while(scanf("%lld%lld%lld",&a,&b,&c)==3)
    {
        memset(f,0,sizeof(f));
        if(a==-1&&b==-1&&c==-1)break;
        printf("w(%lld, %lld, %lld) = %lld\n",a,b,c,w(a,b,c));
    }
    return 0;
}

by metaphysis @ 2022-05-21 14:56:00

@abablx

需要记忆化求值。


by Lienqwq @ 2022-05-21 15:12:56

@metaphysis 请问else if(f[a][b][c]!=0)return f[a][b][c];这个算记忆化吗?


by metaphysis @ 2022-05-21 15:20:46

@abablx

算记忆化,但是实现细节有问题。


by metaphysis @ 2022-05-21 15:23:14

@abablx

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll f[32][32][32];
ll w(ll a,ll b,ll c)
{
    if(a<=0||b<=0||c<=0)return 1;
    if(a>20||b>20||c>20) return w(20,20,20);
    if (f[a][b][c]) return f[a][b][c];
    if(a<b&&b<c) return f[a][b][c]=w(a,b,c-1) + w(a,b-1,c-1)-w(a,b-1,c);
    return f[a][b][c]=w(a-1,b,c)+w(a-1,b-1,c)+w(a-1,b,c-1)-w(a-1,b-1,c-1); 
}
int main()
{
    int a, b, c;
    while(scanf("%d %d %d",&a,&b,&c))
    {
        if(a==-1&&b==-1&&c==-1)break;
        printf("w(%d, %d, %d) = %lld\n",a,b,c,w(a,b,c));
    }
    return 0;
}

by Lienqwq @ 2022-05-21 15:26:53

@metaphysis 过了,谢谢!


by Bingxiu @ 2022-05-27 13:26:41

else if(f[a][b][c]!=0)return w(20,20,20); 你看一眼是不是这里写错了,似乎应该是f[a][b][c]


|