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;
}