FZU 2108 MOD problem

该说是字符串题目呢还是数论题目呢。

这题因为有字符串嵌套,所以最好还是拿递归来写。在构思递归的时候考虑到了要传什么参数的问题,每个递归函数传两个参数,对应的字符串长度,以及这一段的值。一开始估计错了数据范围,计算值的时候直接无脑乘积的,然后就TLE了。。。后来换了快速幂来实现,才AC。

#include "cstdio"
#include "cstring"
#define LL long long
char s[1111];
LL m;
struct node{
    int len;
    LL v;
};

LL mul_mod(LL a,LL b,LL c)
{
    LL ret=0,tmp=a%c;
    while(b)
    {
        if(b&0x1)if((ret+=tmp)>=c)ret-=c;
        if((tmp<<=1)>=c)tmp-=c;
        b>>=1;
    }
    return ret;
}

LL pow_mod(LL a,LL p,LL n){
    if(p==0)  return 1%n;
    LL ans=pow_mod(a,p/2,n);
    ans=mul_mod(ans, ans, n);
    if(p%2==1)  ans=mul_mod(ans, a, n);
    return ans%n;
}

node solve(int start,int end){
    node ans;
    LL base=0;
    int len=0;
    int cnt;
    int flag1,flag2;
    for(int i=start;i<=end;)
    {
        if(s[i]!='['){
            base=(10*base+s[i]-'0')%m;
            len++;
            i++;
        }
        else{
            cnt=1;
            for(int j=i+1;;j++){
                if(s[j]=='[')  cnt++;
                else{
                    if(s[j]==']')  cnt--;
                }
                if(cnt==0){
                    flag1=j-1;
                    flag2=s[j+1]-'0';
                    break;
                }
            }
            node res=solve(i+1,flag1);
            
            for(int k=0;k<flag2;k++){
                base=base*pow_mod(10,res.len,m);
                base=(base+res.v)%m;
            }
            
            i=flag1+3;
            len+=res.len*flag2;
        }
    }
    base=(base+m)%m;
    ans.len=len,ans.v=base;
    return ans;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%s%lld",s,&m);
        int len=(int)strlen(s);
        node ans=solve(0,len-1);
        printf("%lld\n",(ans.v+m)%m);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值