一、题目
Polycarp and Div3(贪心):题目
Examples
Input
3121
Output
2
Input
201920181
Output
4
二、解题步骤
1.题意
输入一串数字,不断划分,求最多有多少能被3整除的数字
2.思路
贪心,先判断每一位是否能被3整除,如果能就 cnt++;再记录前缀和,判断加起来的数字是不是3的倍数,如果是3的倍数,cnt++;
如果连续三个数都不是3的倍数,那么对前面两个数来说,对3求余只可能是同时余1或同时余2,然后对于第三个数对3取余可能是1或者2,如果是是[111]或[222],那就全部取,如果是[221],那就取后面的两个,如果是[112],那就取后面两个
综上:符合要求的只有三种情况
Source Program
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int t, n, m;
int a[N];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
string s; cin >> s;
n = s.size();
int cnt = 0, ans = 0, sum = 0;
for (int i = 0; i < n; i++)
{
cnt++;
sum += s[i] - '0';
if (cnt == 3 || (s[i] - '0') % 3 == 0 || sum % 3 == 0)//符合要求的三种情况
{
cnt = 0;
sum = 0;
ans++;
}
}
cout << ans << endl;
return 0;
}