Polycarp likes numbers that are divisible by 3.
He has a huge number ss. Polycarp wants to cut from it the maximum number of numbers that are divisible by 33. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after mm such cuts, there will be m+1m+1 parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by 33.
For example, if the original number is s=3121s=3121, then Polycarp can cut it into three parts with two cuts: 3|1|213|1|21. As a result, he will get two numbers that are divisible by 33.
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?
The first line of the input contains a positive integer ss. The number of digits of the number ss is between 11 and 2⋅1052⋅105, inclusive. The first (leftmost) digit is not equal to 0.
Print the maximum number of numbers divisible by 33 that Polycarp can get by making vertical cuts in the given number ss.
3121
2
6
1
1000000000000000000000000000000000
33
201920181
4
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 3333 digits 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
题意:给你一串由数字组成的字符串(最长2e5),要你把它分割成一些数字,使得在这些数字中能被3整除的个数最多。
解法:考虑将每个数字模3以后的结果。
如果对于当前数字能被3整除(0、3、6、9)模3结果为0的数,则直接个数加1
如果是两个数字那就有四种可能(1,1) (2, 2) (1, 2) (2, 1)其中后两个组合之和为3能被3整除
如果是三个数字对于之前两个数字的组合只剩下(1, 1)和(2, 2) 那么下个数不管是1还是2都可以组成一个3的整数倍
所以总结一下有三种情况
1.当前数字模3为0
2.现有的数字之和模3为0(当前正在处理的)
3.有三个数字了一定可以做到模3为0
然后一个一个数字处理即可。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int a[N];
map<int,int> mp;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
string s;
cin >> s;
int len = s.length();
int sum = 0, n = 0, cnt = 0;
for(int i = 0; i < len; i++)
{
int temp = (s[i] - '0') % 3;
sum += temp;//计算当前的模
n++;//处理的数字+1
if(n == 3 || sum % 3 == 0 || temp % 3 == 0)//如果已经有3个数字或者sum模3为0或者当前数字是3的倍数
{
sum = n = 0;//n和sum都置0
cnt++;//则个数加一
}
}
cout << cnt << endl;
return 0;
}