Subsequence Problem Report Divisible by 3

Question link to the main
idea of ​​the question.
Give you a number string of length 50, and ask you how many subsequences constitute a number that can be divisible by 3. The
answer is 1 e 9 + 7 1e^9+71e9+7 Modulo
input description
Input a string consisting of numbers, the length is less than or equal to 50
Output description
Output an integer
input example

132

Sample output

3

Dynamic programming linear dp
1. Determine the state f [i] [j] f[i][j]f [ i ] [ j ] :s [i] s [i]The remainder at the end of s [ i ] isjjj , the attribute represents the number of schemes.
2. State transitionf [i + 1] [j] = f [i + 1] [j] + f [i] [j] f[i+1][j] = f[i+1][j] + f[i][j]f[i+1][j]=f[i+1][j]+f[i][j]

Take a millet, take the sample as an example. First, the subsequence of 132 has 1, 3, 13, 2, 12, 32, 132. There is a conclusion that a number can be divisible by a certain number, then the sum of the numbers at all positions can be divisible by this number , ending in 2. The data is 2, 12, 32, 132. 12 can be regarded as f ["12"] [mod] = f ["12"] [(mod + "2")% mod] + f ["1"] [mod] f["12"][mod] = f["12"][(mod+"2")\%mod] + f["1"][mod]f["12"][mod]=f["12"][(mod+"2")%mod]+f [ " 1 " ] [ m o d ] and so on.
3. Coding implementation

1      dp[1][1] = 1;
03     dp[2][0] = 1;
002    dp[3][2] = 1;

112  
13132 ⇒ dp[3][(j+2)%3] = (dp[2][j] + dp[3][(j+2)%3])
2
332

for(int i = 1; i <= len; i++)
    for(int j = 0; j < 3; j++)
        for(int k = i+1; k <= len; k++)
            f[k][(s[k]+j-'0')%3] =(f[k][(s[k]+j-'0')%3]+ f[i][j])%mod;
#include <cstdio>
#include <cstring>
using namespace std;
const int mod = 1e9 + 7;
char s[55];
int f[55][3];
int main()
{
    
    
    scanf("%s",s+1);
    int len = strlen(s+1);
    for(int i = 1; i <= len; i++) f[i][(s[i]-'0')%3] = 1;
    
    for(int i = 1; i <= len; i++)
        for(int j = 0; j < 3; j++)
            for(int k = i+1; k <= len; k++)
                f[k][(s[k]+j-'0')%3] =(f[k][(s[k]+j-'0')%3]+ f[i][j])%mod;
       
    int ans = 0;
    for(int i = 1; i <= len; i++) ans = (ans + f[i][0])%mod;
    printf("%d\n",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/Edviv/article/details/110931489