题意:给出一种数字的构造,问这个数字(很大)对另一个数字的模等于多少。。
思路:首先(a*b)%c = a%c*b%c,然后根据构造进行dfs,得出结果,需要用快速幂求10^k%m(网上好多网站的题解都是各种复制别的网站的啊- -)
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int maxn=1010;
#define ll long long
char s[maxn];
ll m;
ll fast_mod(ll a,ll k){//cout<<'a';
ll ans = 1;
while(k){
if(k&1)ans = (ans * a) % m;
k >>= 1;
a = (a * a)%m;
}
return ans % m;
}
ll get_kuo(int l,int r,int &len){
ll ans = 0;
len = 0;
for(int i = l+1;i < r-1;i ++){
if(s[i] == '['){
int kuo = 0;//cout<<i<<endl;
for(int j = i;;j ++){
if(s[j] == '[')kuo ++;
if(s[j] == ']')kuo --;
if(kuo == 0){
int len_in;
ll tmp = get_kuo(i,j+1,len_in);
len += len_in;
ans = (ans * fast_mod(10,len_in) % m + tmp)%m;
i = j+1;
break;
}
}
}
else {
len ++;
ans = (ans * 10 % m + s[i] - '0')%m;
}
}
// duo ci cheng
//cout<<len;
ll tmp = ans;
for(int i = 0;i < s[r] - '0' - 1;i ++){//cout<<ans<<endl;
ans = (ans * fast_mod(10,len) % m + tmp) % m;
}
len *= (s[r] - '0');//cout<<' '<<l<<' '<<r<<' '<<ans<<' '<<len<<endl;
//cout<<ans<<endl;
return ans;
}
ll get(int l,int r){//fan wei ,fan hui chang du
ll ans = 0;
for(int i = l;i <= r;i ++){
if(s[i] == '['){
int kuo = 0;
for(int j = i;;j ++){
if(s[j] == '[')kuo ++;
if(s[j] == ']')kuo --;
if(kuo == 0){
int len_in;//cout<<i<<" "<<j+1<<endl;
ll tmp = get_kuo(i,j+1,len_in);
ans = (ans * fast_mod(10,len_in) % m + tmp) % m;
i = j + 1;//cout<<i<<endl;
break;
}
}
}
else {//cout<<ans<<endl;
ans = (ans * 10 + s[i] - '0') % m;
}
}
return ans;
}
int main()
{
//freopen("in.txt","r",stdin);
int T;
cin>>T;
while(T --){
cin>>s>>m;
int l = strlen(s);
int len;
ll ans = 0;
ans = get(0,l-1);
cout<<ans<<endl;
}
return 0;
}