Codeforces1005D. Polycarp and Div 3

题目链接:http://codeforces.com/problemset/problem/1005/D

题目大意:给一个数字串,问其中有多少个子串能被3整除,每个数字都只能和相邻数字组合且只能组合一次,特别的,0算一种

思路:将数字串中的所有数字都拆成一个个数字,然后依次组合判断,因为被3除得到的余数就只有0,1,2三种,所以组合的数字就只有这些情况(0,12,21,111,222)(前后12省略),然后对这些情况分别判断就行了

代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
char str[30000000];
int s[30000000];
int main()
{
    memset(str,0,sizeof(str));
    scanf("%s", str);
    int len = strlen(str);
    int cnt = 0;
    for(int i = 0; i < len; i++)//字符串转数字串
    {
        s[i] = (str[i]-'0')%3;
    }
    int c1 = 0, c2 = 0;//1的个数,2的个数
    for(int i = 0; i < len; i++)
    {
        if(s[i]==0)
        {
            cnt++;
            c1 = 0;
            c2 = 0;
            continue;
        }else
        {
            if(s[i]==1)c1++;
            if(s[i]==2)c2++;
            if(c1>=1&&c2==1){cnt++,c1=0,c2=0;}
            if(c1==3){cnt++,c1=0,c2=0;}
            if(c2==2&&c1==1){cnt++,c1=0,c2=0;}
            if(c2==3){cnt++,c1=0,c2=0;}
        }
    }
    printf("%d\n", cnt);
    return 0;

}

猜你喜欢

转载自blog.csdn.net/wys5wys/article/details/82859842