思路
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;
}