【CodeForces 1005D --- Polycarp and Div 3】DP+同余贪心

【CodeForces 1005D --- Polycarp and Div 3】DP+同余贪心

题目来源:点击进入【CodeForces 1005D — Polycarp and Div 3】

Description

Polycarp likes numbers that are divisible by 3.

He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by 3.

For example, if the original number is s=3121, then Polycarp can cut it into three parts with two cuts: 3|1|21. As a result, he will get two numbers that are divisible by 3.

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 3 that Polycarp can obtain?

Input

The first line of the input contains a positive integer s. The number of digits of the number s is between 1 and 2⋅105, inclusive. The first (leftmost) digit is not equal to 0.

Output

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

Sample Input

3121

Sample Output

2

解题思路

通过dp[i]来记录前i个字符能分成多少段符合题意。
通过前缀和来得到前i个字符所对应数字之和,然后取余。
那么dp[i]所对应的值只有两种情况:

  1. 加上当前字符没法形成符合条件的段。所以dp[i]=dp[i-1];
  2. 加上当前字符可以形成符合条件的段。但是不是dp[i-1]+1。而是找到上一个相同余数所在位置x。dp[i]=dp[x]+1;(余数相同代表x+1-i可以形成符合条件的段)

所以转移方程就是dp[i]=max(dp[i-1],dp[x]+1);

那么怎么记录上个相同余数所在位置呢?
我们只需使用一个last[4]数组,存储每次通过前缀和来得到前i个字符所对应数字之和取余后的数。

AC代码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
const int inf = 0x3f3f3f;
const int MAXN = 2e5+5;
int last[4],dp[MAXN];

int main()
{
    SIS;
    string s;
    memset(last,-1,sizeof(last));
    last[0]=0;
    cin >> s;
    int len=s.size(),sum=0;
    for(int i=0;i<len;i++)
    {
        if(i!=0) dp[i]=dp[i-1];
        sum+=s[i]-'0';
        sum%=3;
        if(last[sum]!=-1) dp[i]=max(dp[i],dp[last[sum]]+1);
        last[sum]=i;
    }
    cout << dp[len-1] << endl;
    return 0;
}
发布了412 篇原创文章 · 获赞 135 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41879343/article/details/104100969
今日推荐