全TLE,求助

P1464 Function

Lhy2021 @ 2023-01-06 14:26:25

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<stack>
#include<deque>
#include<map>
using namespace std;
long w(long a,long b,long c)
{
    if(a>20||b>20||c>20) 
    {
        a=20;b=20;c=20;
    }
    if(a<=0||b<=0||c<=0) return 1;
    if(a<b&&b<c) return w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c);
    return 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()
{
    long a,b,c;
    while(cin>>a>>b>>c)
    {
        if(a==-1&&b==-1&&c==-1) break;
        cout<<"w("<<a<<","<<b<<","<<c<<")="<<w(a,b,c)<<endl;
    }
    return 0;
}

by Lhy2021 @ 2023-01-06 14:28:53

弱弱问一句,啥是记忆化


by qwerasdasd1 @ 2023-01-06 14:35:04

@Lhy2021 记忆化搜索


by Hughpig @ 2023-01-06 14:46:24

@Lhy2021 首先,加记忆化。

其次,注意空格。你的输出没加空格。

改完的代码,仅供参考,请勿直接复制:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<stack>
#include<deque>
#include<map>
using namespace std;

long qwq[22][22][22】;

long w(long a,long b,long 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(qwq[a][b][c]) return qwq[a][b][c];
    else if(a<b&&b<c) return qwq[a][b][c]=w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c);
    else return qwq[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()
{
    long a,b,c;
    while(cin>>a>>b>>c)
    {
        if(a==-1&&b==-1&&c==-1) break;
        cout<<"w("<<a<<", "<<b<<", "<<c<<") = "<<w(a,b,c)<<endl;
    }
    return 114514;
}

by Lhy2021 @ 2023-01-06 14:52:51

@Hughpig太感谢了


|