洛谷P2690 [USACO04NOV]Apple Catching G(记忆化搜索)

原题链接

相比于dp,记忆化搜索可能容易想到,更好理解

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define ll long long
#include
using namespace std;
const ll inf = 0x3f3f3f3f;
inline ll read() {
    ll k = 0, f = 1; char ch = getchar();
    while (ch < '0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { k = k * 10 + ch - '0'; ch = getchar(); }return k * f;
}
ll n, m;
ll a[1005];
ll dp[1005][3][35];

ll dfs(ll t, ll loc, ll cnt)
{
    if (dp[t][loc][cnt] != -1)return dp[t][loc][cnt];
    if (t > n)return 0;
    if (cnt >= m)
    {
        dp[t][loc][cnt] = dfs(t + 1, loc, cnt) + (a[t] == loc);
        return dp[t][loc][cnt];
    }
    ll ans1 = 0;
    if (a[t] == loc)ans1 = dfs(t + 1, loc, cnt) + 1;
    else ans1 = max(dfs(t + 1, 3-loc, cnt + 1) + 1, dfs(t + 1, loc, cnt));
    dp[t][loc][cnt] = ans1;
    return ans1;
}
int main()
{
    n = read(), m = read();
    for (int i = 1; i <= n; i++)a[i] = read();
    memset(dp, -1, sizeof(dp));
    cout << dfs(1, 1, 0) << '\n';
}

你可能感兴趣的:(洛谷P2690 [USACO04NOV]Apple Catching G(记忆化搜索))