Turtle chess (linear dp)

Preface

Turtle Chess is the original question of the NOIP2010 improvement group and a representative question of a typical linear dp.

Title

Given nnn number, starting from the left and going to the right. Totalmmm cards, divided into4 44 different types, each type of card is marked with1, 2, 3, 4 1, 2, 3, 4One of the four numbers 1 , 2 , 3 , and 4 indicates that the corresponding number of grids will be walked forward after using this card. Every time you go to which grid, you will get the corresponding number, and ask what is the maximum sum of the numbers you get to the end.

data range

1 ≤ m ≤ 350 1 \leq m \leq 350 1m3 5 0
1 ≤ n ≤ 120 1 \ leq n \ leq 1201n1 2 0
Each card has a maximum of40 404 0 sheets.

Ideas

f ( i , j , k , l ) f(i,j,k,l) f(i,j,k,l ) indicates the maximum value of the four cards using several moves.
According to the last step, choose which card is divided into four categories. Take the first type of card as an example, if the last step is1 11 , then the previous state isf (i − 1, j, k, l) f(i-1,j,k,l)f(i1,j,k,l ) .
The state transition equation is:f (i, j, k, l) = max (f (i, j, k, l), f (i − 1, j, k, l) + a [i + j ∗ 2 + k ∗ 3 + l ∗ 4]) f(i,j,k,l) ​​= max(f(i,j,k,l),f(i-1,j,k,l) ​​+ a[i+ j*2+k*3+l*4])f(i,j,k,l)=max(f(i,j,k,l),f(i1,j,k,l)+a[i+j2+k3+l4])

Code

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int N = 360, M = 45;

int n, m;
int a[N];
int f[M][M][M][M];

int main()
{
    
    
    int b[5] = {
    
    0};
    cin >> n >> m;
    for(int i=0;i<n;i++) cin >> a[i];
    for(int i=1;i<=m;i++){
    
    
        int x;
        cin >> x;
        b[x] ++;
    }
    for(int i=0;i<=b[1];i++)
        for(int j=0;j<=b[2];j++)
            for(int k=0;k<=b[3];k++)
                for(int l=0;l<=b[4];l++)
                {
    
    
                    int tot = a[i+j*2+k*3+l*4];
                    f[i][j][k][l] = tot;
                    if(i) f[i][j][k][l] = max(f[i][j][k][l], f[i-1][j][k][l]+tot);
                    if(j) f[i][j][k][l] = max(f[i][j][k][l], f[i][j-1][k][l]+tot);
                    if(k) f[i][j][k][l] = max(f[i][j][k][l], f[i][j][k-1][l]+tot);
                    if(l) f[i][j][k][l] = max(f[i][j][k][l], f[i][j][k][l-1]+tot);
                }
    
    cout << f[b[1]][b[2]][b[3]][b[4]] << endl;;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43634220/article/details/108457354