luogu P3609 [USACO17JAN]Hoof, Paper, Scissor蹄子剪刀…

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42369449/article/details/82948855

算法:记忆化搜索

难度:NOIP

题解:暴力枚举所有情况,更新dp数组的值,记忆化搜索即可

代码如下:

时间复杂度:O(N*K*3)+常数常数

玄学油画:

1、手写max函数

2、i++改成i++

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#define ll long long 
#define N 100005
using namespace std;
char str[5];
int f[N];
int ans,n,k;
int dp[N][25][5];
int max(int x,int y)
{
    return x>y?x:y;
} 
int dfs(int typ,int chan,int po)
{
    if(po>n||chan>k) return 0;
    if(dp[po][chan][typ]) return dp[po][chan][typ];//记忆化 
    if(chan==k)
    {
        if(typ==1&&f[po]==3) dp[po][chan][typ]=dfs(typ,chan,po+1)+1;
        if(typ==2&&f[po]==1) dp[po][chan][typ]=dfs(typ,chan,po+1)+1;
        if(typ==3&&f[po]==2) dp[po][chan][typ]=dfs(typ,chan,po+1)+1;
        if(typ==1&&f[po]!=3) dp[po][chan][typ]=dfs(typ,chan,po+1);
        if(typ==2&&f[po]!=1) dp[po][chan][typ]=dfs(typ,chan,po+1);
        if(typ==3&&f[po]!=2) dp[po][chan][typ]=dfs(typ,chan,po+1);
    }else
    {
        if(typ==1&&f[po]==3) dp[po][chan][typ]=max(dfs(typ,chan,po+1)+1,max(dfs(3,chan+1,po+1)+1,dfs(2,chan+1,po+1)+1));
        if(typ==2&&f[po]==1) dp[po][chan][typ]=max(dfs(typ,chan,po+1)+1,max(dfs(3,chan+1,po+1)+1,dfs(1,chan+1,po+1)+1));
        if(typ==3&&f[po]==2) dp[po][chan][typ]=max(dfs(typ,chan,po+1)+1,max(dfs(1,chan+1,po+1)+1,dfs(2,chan+1,po+1)+1));
        if(typ==1&&f[po]!=3) dp[po][chan][typ]=max(dfs(typ,chan,po+1),max(dfs(3,chan+1,po+1),dfs(2,chan+1,po+1)));
        if(typ==2&&f[po]!=1) dp[po][chan][typ]=max(dfs(typ,chan,po+1),max(dfs(3,chan+1,po+1),dfs(1,chan+1,po+1)));
        if(typ==3&&f[po]!=2) dp[po][chan][typ]=max(dfs(typ,chan,po+1),max(dfs(1,chan+1,po+1),dfs(2,chan+1,po+1)));
    }
    return dp[po][chan][typ];
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int i = 1;i <= n;++i/*玄学++i优化*/)   //或者手写max! 
    {
        scanf("%s",str+1);
        if(str[1]=='H') f[i]=1;//石头
        else if(str[1]=='P') f[i]=2;//布
        else if(str[1]=='S') f[i]=3;//剪刀 
    }
    ans=max(dfs(1,0,1),max(dfs(2,0,1),dfs(3,0,1)));
    printf("%d\n",ans);
    return 0 ;
}

猜你喜欢

转载自blog.csdn.net/qq_42369449/article/details/82948855