Subsequence divisible by 3 ---------------------------- Thinking (dp)

Insert picture description here
Insert picture description here
Insert picture description here

Analysis:
This linear dp is also a routine problem.
Breakthrough: Dealing with the remainder of 3
f [i] [0 ~ 2]: Representing all cases where the sum of the previous i numbers is% 3 (0 ~ 2)

So we only need to enumerate the state of the remainder

State transition equation: f [i] [j] = f [i-1] [j] + f [i-1] [(j + 3-m)% 3]
f [i-1] [j]: means The i-th number is not selected, and the i-1 number is selected and the remainder is
f [i-1] [(j + 3-m)% 3]: it means that the i-th number is selected because we enumerate j , We need to judge what is the remainder of the i-1th number: (j + 3-m)% 3 only the remainder of the ith number is m, then the contribution to j is (m + (j + 3-m)% 3) % 3 == j

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+100;
const int MOD=1e9+7;
int f[N][3];
string s;
int main()
{
	cin>>s;
	int n=s.size();
	f[0][(s[0]-'0')%3]=1;
	for(int i=1;i<n;i++)
	{
		int m=(s[i]-'0')%3;
		f[i][m]=(f[i][m]+1)%MOD; 
		for(int j=0;j<=2;j++)
		{
			f[i][j]+=(f[i-1][j]+f[i-1][(3+j-m)%3])%MOD;
		}
	}
	cout<<f[n-1][0]<<endl;
}

Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105201942