四维dp
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<cstdio> 2 #include<cstring> 3 using namespace std; 4 const int N=41; 5 int f[N][N][N][N],g[356],a,b,c,d,n,m; 6 int max(int x,int y){ 7 return x>y?x:y; 8 } 9 int main(){ 10 int tmp; 11 a=b=c=d=0; 12 scanf("%d %d",&n,&m); 13 for (int i=1;i<=n;i++) 14 scanf("%d",&g[i]); 15 for (int i=1;i<=m;i++){ 16 scanf("%d",&tmp); 17 if (tmp==1) a++; 18 if (tmp==2) b++; 19 if (tmp==3) c++; 20 if (tmp==4) d++; 21 } 22 f[0][0][0][0]=g[1]; 23 for (int i=0;i<=a;i++) 24 for (int j=0;j<=b;j++) 25 for (int k=0;k<=c;k++) 26 for (int l=0;l<=d;l++){ 27 tmp=1+i+j*2+k*3+l*4;//** 28 if (i-1>=0) 29 f[i][j][k][l]=max(f[i-1][j][k][l]+g[tmp],f[i][j][k][l]); 30 if (j-1>=0) 31 f[i][j][k][l]=max(f[i][j-1][k][l]+g[tmp],f[i][j][k][l]); 32 if (k-1>=0) 33 f[i][j][k][l]=max(f[i][j][k-1][l]+g[tmp],f[i][j][k][l]); 34 if (l-1>=0) 35 f[i][j][k][l]=max(f[i][j][k][l-1]+g[tmp],f[i][j][k][l]); 36 } 37 printf("%d",f[a][b][c][d]); 38 return 0; 39 }