Polycarp and Div 3【Codeforces Round #496 (Div. 3)【D题】】【贪心】

    应该说是今天凌晨的吧,第一次打Code Forces,懵懵懂懂的,不过感觉还是良好,做了几道签到题。难题还是没有那个水准去做......


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, 00701 and 00099 are not valid numbers, but 900 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 ss. The number of digits of the number ss is between 11 and 21052⋅105, inclusive. The first (leftmost) digit is not equal to 0.

Output

Print the maximum number of numbers divisible by 33 that Polycarp can get by making vertical cuts in the given number ss.


        题目的意思是给你一串数字长度为(1~2e5),当然由于它的这一串数字是不打空格的输入,所以我用了string 定义了个字符串然后仅需要对字符串操作即可。题目要求得到的是:给你一串数组,你要找的是这串数组上能有多少段能被3整除的数,譬如3121,可以分成「3」、「1、2」、「1」,但最后的时候由于1不是3的倍数,所以ans=2;再举个有0的例子,100000可以分成「1」、「0」、「0」、「0」、「0」、「0」,ans=5,这里要考虑到的就是0也是3的倍数。

        思路:我们可以看到这样一个现状:

(一)、假如这个数可以被3整除,那么前面的数作废,开始判断后面的数

(二)、假如第一个数不能被三整除,那么考虑第二个数,若是不能被三整除,则看他们两个数的和,他们的与3分别的余数只有「1,1」、「1,2」、「2,2」这么三种情况,若是「1,2」到这就可以停下来,重新开始判断下一个了,否则无论是上述1、3情况下的哪一种都会被第三个一起给3整除掉,举个例子如果下一个数%3=1,遇上情况1,三个数和一定为三的倍数;情况2,第二个数和第三个数一定为三的倍数。所以每个式子长度不过三。


完整代码:

#include 
#include 
#include 
#include 
#include 
using namespace std;
string s;
int a[200005]={0};
int main()
{
    while(cin>>s)
    {
        int ans=0;
        memset(a, 0, sizeof(a));
        int st=0;
        int sum=0;
        int cnt=0;
        while(s[st]=='0')
        {
            st++;
        }
        for(int i=st; i=3 || a[cnt-1]%3==0)
            {
                ans++;
                sum=0;
                cnt=0;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(贪心)