Blue Bridge Cup Exams - take the underground palace treasure (dynamic programming)

topic:

Here Insert Picture Description

Here Insert Picture Description

analysis:

The subject is known to use dynamic programming to readily solve a four-dimensional array set dp [55] [55] [ 15] [15], this array for storing the current number of action programs, data range given by the subject can be inferred set the memory array does not explode, dp [i] [j] [k] [c] we defined as to (i, j) at this point, to get k items, and the maximum value is less than the current items c number of programs, it can be speculated that the following situations:

  • When mat [i] [j]> the current maximum value (mat [i] [j] denote located (i, j) coordinate value of the article), that is to say at this time if you want to take away (i, j) coordinate items, it is located (i-1, j) and (i, j-1) is less than the value of the coordinates certainly mat [i] [j], then the time set a TMP1
    TMP1 DP = [. 1-I] [J ] [k-1] [mat [i] [j]] + dp [i] [j-1] [k-1] [mat [i] [j]]

  • Regardless of when the mat [i] [j] is greater than the current maximum value, may choose not to take located (i, J) of the article, when the mat [i] [j] value is less than the current maximum, can not be removed (i , j) of the article, so whether it is larger or smaller than, do not take this situation exists, in which case a set TMP2
    TMP2 DP = [. 1-I] [J] [K] [C] + DP [I] [ j-1] [k] [ c]

Finally dp [i] [j] [ k] [c] = (tmp1% mod + tmp2% mod)% mod the number of the current program to obtain
the final output dp [n] [m] [ k] [13]

Code:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int MOD = 1e9+7;
int mat[55][55];
int dp[55][55][15][15];
int n,m,k,ans;

int main()
{
    scanf("%d%d%d",&n,&m,&k);
    for(int i=1;i<=n;++i)
        for(int j=1;j<=m;++j)
            scanf("%d",&mat[i][j]);
    int tmp1,tmp2;
    for(int i=1;i<=n;++i)
        for(int j=1;j<=m;++j)
            for(int l=0;l<=k;++l)
                for(int c=0;c<=13;++c)
                {
                    tmp1 = 0;
                    if(i==1&&j==1)   //此处表示初始条件
                    {
                        if(l==0) dp[i][j][l][c] = 1;
                        if(l==1&&c>mat[i][j]) dp[i][j][l][c]=1;
                        continue;
                    }
                    if(c>mat[i][j]&&l) tmp1 = dp[i-1][j][l-1][mat[i][j]] + dp[i][j-1][l-1][mat[i][j]];
                    tmp2 = dp[i-1][j][l][c] + dp[i][j-1][l][c];
                    dp[i][j][l][c] = (tmp1%MOD+tmp2%MOD)%MOD;
                }
    printf("%d\n",dp[n][m][k][13]);
    return 0;
}

Published 61 original articles · won praise 7 · views 3640

Guess you like

Origin blog.csdn.net/weixin_42469716/article/details/104569600