牛客多校__number

链接:https://ac.nowcoder.com/acm/contest/884/K
来源:牛客网
 

题目描述

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.

输入描述:

A single line consisting a string consisted of characters '0' to '9'.

输出描述:

The number of substrings that are multiples of 300 when considered as decimal integers.

示例1

输入

复制

600

输出

复制

4

说明

'600', '0', '0', '00' are multiples of 300. (Note that '0' are counted twice because it appeared two times)

示例2

输入

复制

123000321013200987000789

输出

复制

55

题意:找出满足被300整除的子串数,允许有前缀0

题解:用动态规划dp,dp[i][j]表示以i为结尾的余数为j的数目,复杂度为O(300*N)

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn = 1e5+9;

char s[maxn];

ll dp[maxn][300];

int main(){
    scanf("%s",s+1);
    int len=strlen(s+1);
    for(int i=1;i<=len;i++){
        int x=s[i]-'0';
        for(int j=0;j<300;j++){
            dp[i][(j*10+x)%300]+=dp[i-1][j];
        }
        dp[i][x]++;
    }
    ll ans=0;
    for(int i=1;i<=len;i++){
        ans+=dp[i][0];
    }
    cout<<ans<<endl;
    return 0;
}

O(n)做法,用sum[i][0],sum[i][1],sum[i][2]先预处理出对于每个i,其后缀有多少个模3等于0,1,2,(0要先把sum[0][0]=1),这样对于每个i,你只需要用sum[i][]-1就可以得出前面有多少个模3等于0了,因为每个模三等于0之间肯定是可以整除三的,而余数为0本身就可以所以要把sum[0][0]=1

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

const int maxn = 1e5+9;

char s[maxn];

int sum[maxn][5];
int pre[maxn];

int main(){
    scanf("%s",s+1);
    int num=0;
    int num0=0;
    sum[0][0]=1;
    for(int i=1;s[i];i++){
        num+=s[i]-'0';
        sum[i][0]=sum[i-1][0];
        sum[i][1]=sum[i-1][1];
        sum[i][2]=sum[i-1][2];
        sum[i][num%3]++;
        pre[i]=num%3;
    }
    ll ans=0;
    int cnt=0;
    for(int i=1;s[i];i++){
        if(s[i]=='0')cnt++;
        else{
            ans+=1ll*(cnt+1)*cnt/2;
            cnt=0;
        }
    }
    if(cnt){
        ans+=1ll*(cnt+1)*cnt/2;
        cnt=0;
    }
    int len=strlen(s+1);
    for(int i=len;i;i--){
        if(s[i]=='0')cnt++;
        else{
            if(cnt>=2){
                ans+=1ll*(cnt-1)*(sum[i][pre[i]]-1);
            }
            cnt=0;
        }
    }
    cout<<ans<<endl;
    return 0;
}







 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值