luogu 4401 矿工配餐 多维dp

时间:2022-06-29 07:22:04

五维dp,记忆化搜索会MLE超内存,所以用滚动数组,十分经典

五维dp

#include <bits/stdc++.h>

using namespace std;
const int maxn=;
int n,tp[maxn],now[][][][],last[][][][];
char s[maxn];
int trans(char c){
if(c=='M')return ;
if(c=='F')return ;
if(c=='B')return ;
return -;
}
int judge(int a,int b,int c){
if(!a && !b) return ;
if(!a )return (b!=c)+;
if(a==b && b==c)return ;
return (a!=b)+(b!=c)+(c!=a);
}
int main(){
//freopen("77.in","r",stdin);
//freopen("77.out","w",stdout);
scanf("%d",&n);
scanf("%s",s);
for(int i=;i<=n;i++)
tp[i]=trans(s[i-]);
for(int i=n;i>=;i--){
memset(now,,sizeof now);
int p1,p2;
for(int a1=;a1<=;a1++)
for(int a2=;a2<=;a2++)
for(int b1=;b1<=;b1++)
for(int b2=;b2<=;b2++){
p1=judge(a1,a2,tp[i]),p2=judge(b1,b2,tp[i]);
now[a1][a2][b1][b2]=max(last[a2][tp[i]][b1][b2]+p1,last[a1][a2][b2][tp[i]]+p2);
}swap(now,last);
}
printf("%d",last[][][][]);
return ;
}

记忆化搜索

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=;
int n,tp[maxn],f[maxn][][][][]; int trans(char c){
if(c=='M')return ;
if(c=='F')return ;
if(c=='B')return ;
return -;
}
int judge(int a,int b,int c){
if(!a && !b) return ;
if(!a )return (b!=c)+;
if(a==b && b==c)return ;
return (a!=b)+(b!=c)+(c!=a);
}
int dp(int now,int a1,int a2,int b1,int b2){
if(now>n) return ;
if(f[now][a1][a2][b1][b2]) return f[now][a1][a2][b1][b2];
f[now][a1][a2][b1][b2]=max( dp(now+,a2,tp[now],b1,b2)+judge(a1,a2,tp[now]),dp(now+,a1,a2,b2,tp[now])+judge(b1,b2,tp[now]) );
return f[now][a1][a2][b1][b2];
}
char s[maxn];
int main(){
freopen("77.in","r",stdin);
freopen("77.out","w",stdout);
scanf("%d",&n);
scanf("%s",s);
for(int i=;i<=n;i++){
int t=trans(s[i-]);
tp[i]=t;
}printf("%d\n",dp(,,,,));
return ;
}

用于复习了