D. Polycarp and Div 3
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Polycarp likes numbers that are divisible by 3.
He has a huge number ss33mmm+1m+133
For example, if the original number is s=3121s=31213|1|213|1|2133
Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.
What is the maximum number of numbers divisible by 33 that Polycarp can obtain?
Input
The first line of the input contains a positive integer ssss112⋅1052⋅105
Output
Print the maximum number of numbers divisible by 33ss
Examples
input
Copy
3121
output
Copy
2
input
Copy
6
output
Copy
1
input
Copy
1000000000000000000000000000000000
output
Copy
33
input
Copy
201920181
output
Copy
4
Note
In the first example, an example set of optimal cuts on the number is 3|1|21.
In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by 33.
In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and 3333 digits 0. Each of the 3333digits 0 forms a number that is divisible by 33.
In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers 00, 99, 201201 and 8181 are divisible by 33.
题意:给出一个字符串,你现在任意分割它,希望分割后的子段尽可能能的被3整除,求最大数目:
思路:记录前缀和sum,并记下当前前缀和%3相同的数字最先出现的位置pos,所以有转移方程dp[i] = max(dp[i-1], dp[pos] + 1)
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <map>
#include <set>
using namespace std;
#define INF 0x3f3f3f3f
const int N = 2e5+10
char s[N];
int first[N], a[N];
int main()
{
scanf("%s", s);
int len = strlen(s);
memset(first, -1, sizeof(first));
int temp = 0;
first[0] = 0;
for(int i = 0 ; i < len ; ++i) {
tmep += s[i] - '0';
if(first[temp] != -1) {
a[i] = max(a[i], a[first[temp]]+1)
}
first[temp] = i;
}
printf("%d\n", a[len-1]);
return 0;
}