P1541 [NOIP2010 提高组] 乌龟棋
思路:因为题中说了正好用完m张卡片,我们考虑用f[a][b][c][d]来表示我移动1,2,3,4距离次数为,a,b,c,d,那么我们能够知道当我们枚举到a,b,c,d时,对应的以为数组的位置为k=1+a+2*b+3*c+4*d,而对于该位置有四种转移状态,a-1,b,c,d、a,b-1,c,d、a,b,c-1,d、a,b,c,d-1,所以我们只需要判断在满足边界条件的情况下,这四个的最大值加上w[ k ],然后更新一下当前的位置,最后f[st1][st2][st3][st4]就是答案
#include<iostream>
#include<cstring>
#include<string>
#include<sstream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<map>
#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
const double eps=1e-7;
const int N=5e5+7 ,M=2e5+7, INF=0x3f3f3f3f,mod=1e9+7;
const long long int llINF=0x3f3f3f3f3f3f3f3f;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
bool cmp0(int a,int b) {return a>b;}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
void hack() {printf("\n----------------------------------\n");}
int T,hackT;
int n,m,k;
int w[N];
int f[41][41][41][41];
int st[5];
void solve() {
n=read(),m=read();
for(int i=1;i<=n;i++) w[i]=read();
for(int i=1;i<=m;i++) {
int c=read();
st[c]++;
}
f[0][0][0][0]=w[1];
for(int a=0;a<=st[1];a++) {
for(int b=0;b<=st[2];b++) {
for(int c=0;c<=st[3];c++) {
for(int d=0;d<=st[4];d++) {
if(a==0&&b==0&&c==0&&d==0) continue;
int k=1+a*1+b*2+c*3+d*4;
if(a>=1) f[a][b][c][d]=max(f[a][b][c][d],f[a-1][b][c][d]+w[k]);
if(b>=1) f[a][b][c][d]=max(f[a][b][c][d],f[a][b-1][c][d]+w[k]);
if(c>=1) f[a][b][c][d]=max(f[a][b][c][d],f[a][b][c-1][d]+w[k]);
if(d>=1) f[a][b][c][d]=max(f[a][b][c][d],f[a][b][c][d-1]+w[k]);
}
}
}
}
printf("%d\n",f[st[1]][st[2]][st[3]][st[4]]);
}
int main() {
// init();
// stin();
// scanf("%d",&T);
T=1;
while(T--) hackT++,solve();
return 0;
}