2019牛客暑期多校训练营(第四场)K number(思维)

传送门
300iq loves numbers who are multiple of 300.
One day he got a string consisted of numbers. He wants to know how many substrings in the string are multiples of 300 when considered as decimal integers.
Note that leading and trailing zeros are allowed (both in original string and substrings you chose) and the same substring appearing in different places can be counted multiple times.

题意:

给一个字符串(由数字‘0’~‘9’组成),问有多少个非空子串是300的倍数

思路:

到每i位时,记录前为的和mod 3的值,放到数组cnt里,记录当前该值出现几次,该值在i这个位置,到前面任意一个出现该值的位置这一段的和mod 3肯定等于0,如果后面再有两个0,就mod 300等于0

代码:

#include <iostream>
#include<algorithm>
#include <stdio.h>
#include <string>
#include <string.h>
#include <map>
#include <math.h>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <deque>
#include <stack>
#include <iostream>
typedef long long ll;
using namespace std;
const int N=1e5+10;
int a[100];
int n;
char ch[N];
ll cnt[4];
int main()
{
    while(scanf("%s",ch)!=-1)
    {
        ll ans=0;
        int x=0;
        int len=strlen(ch);
        cnt[0]=1;
        for(int i=0;i<len;i++)
        {
            if(ch[i]=='0')ans++;
            if(ch[i]=='0'&&ch[i+1]=='0')ans+=cnt[x];
            x=(x+ch[i]-'0')%3;
            cnt[x]++;
        }
        printf("%lld\n",ans);
    }
    return 0;
}
发布了160 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44091178/article/details/104819592