Mod problem FZU - 2108(dfs+模运算)

思路

dfs构造出数字之后取模运算就可以

模运算规则:
模运算与基本四则运算有些相似,但是除法例外。其规则如下:
(a + b) % p = (a % p + b % p) % p
(a – b) % p = (a % p – b % p) % p
(a * b) % p = (a % p * b % p) % p
ab % p = ((a % p)b) % p
结合率:
((a+b) % p + c) % p = (a + (b+c) % p) % p
((a*b) % p * c)% p = (a * (b*c) % p) % p

#include <iostream>
#include <cstring>

using namespace std;

#define ll long long



char str[111111];
ll mod;
ll qpow(ll a,ll b)
{
    ll res=1;
    while(b)
    {
        if(b&1) res=(res*a)%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return res;
}

ll getpow(ll a,ll b)
{
    ll res=0;
    for(int i=0,j=0;i<a;i++,j+=b)
    {
        res=(res%mod+qpow(10,j)%mod)%mod;
    }
    return res;
}

#define pii pair<long long,long long >
pii dfs(int l,int r)
{
    ll nowres=0,nowlen=0;
    for(int i=l;i<=r;i++)
    {
        if(str[i]=='[')
        {
            int cont=1;
            int j=i+1;
            for(;cont!=0;j++)
            {
                if(str[j]=='[') cont++;
                else if(str[j]==']') cont--;
            }
            pii temp=dfs(i+1,j-2);
            int k=str[j]-'0';
            nowres=(nowres*qpow(10,temp.first*k)%mod+temp.second*getpow(k,temp.first)%mod)%mod;
            nowlen+=temp.first*k;
            i=j;
        }
        else
        {
            nowres=(nowres*10%mod+(str[i]-'0')%mod)%mod;
            nowlen++;
        }
    }
    return pii(nowlen,nowres);
}
int main()
{
    int T;cin>>T;
    while(T--)
    {
        scanf("%s%lld",str,&mod);
        int n=strlen(str);
        printf("%lld\n",dfs(0,n-1).second);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值