Problem Description
Given one non-negative integer A and one positive integer B, it’s very easy for us to calculate A Mod B. Here A Mod B means the remainder of the answer after A is divided by B. For example, 7 Mod 5 = 2, 12 Mod 3 = 0, 0 Mod 3 = 0.
In this problem, we use the following rules to express A.
(1) One non-empty string that only contains {0,1,2,3,4,5,6,7,8,9} is valid.
For example, 123, 000213, 99213. (Leading zeros is OK in this problem)
(2) If w is valid, then [w]x if valid. Here x is one integer that 0<x<10.
For example, [012]2=012012, [35]3[7]1=3535357.
(3) If w and v are valid, then wv is valid.
For example, w=[231]2 and v=1, then wv=[231]21 is valid (which is 2312311).
Now you are given A and B. Here A is express as the rules above and B is simply one integer, you are expected to output the A Mod B.
Input
The first line of the input contains an integer T(T≤10), indicating the number of test cases.
Then T cases, for any case, only two lines.
The first line is one non-empty and valid string that expresses A, the length of the string is no more than 1,000.
The second line is one integer B(0<B<2,000,000,000).
You may assume that the length of number A in decimal notation will less than 2^63.
Output
Sample Input
Sample Output
这题就是对于模运算的理解
比如说[123]2=123123=123*1000+123。那么如果B=11,我们所要计算的就是:
[123]2 % 11 = 123123 % 11 = 123*1000 % 11 + 123 % 11.
接着化简下去,记a = 123 % 11,m = 1000 % 11.
ans = (a * m % 11 + a) % 11.
对于这个m,我们可以用快速幂计算其值,而其他的就剩下简单的分解与累加的问题了,这些都不是难事。
数学上的难题解决了,剩下的就是用深搜把这个数据从字符串还原出来,这就是编码问题了。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define ll __int64
struct node
{
ll val,len;
};
char str[1005];
int t,mod;
ll qmod(ll a,ll b)
{
ll s = 1;
while(b)
{
if(b&1)
s = (s*a)%mod;
a = (a*a)%mod;
b>>=1;
}
return s%mod;
}
node dfs(int l,int r)
{
int i,j,top = 0;
int left,right,k,cnt;
node ans;
ans.val = 0;
ans.len = 0;
for(i = l; i<=r; i++)
{
if(str[i]=='[')
{
if(!top) left=i+1;
++top;
}
else if(str[i]==']')
{
--top;
if(!top)
{
right = i-1;
i++;
cnt = str[i]-'0';
node tem=dfs(left,right);
ll base = qmod(10,tem.len);
ans.len+=cnt*tem.len;
ans.val=(ans.val*qmod(base,cnt))%mod;
ll s=1,bb=base;
while(--cnt)
{
s+=bb;
bb=(bb*base)%mod;
s%=mod;
}
tem.val=(tem.val*s)%mod;
ans.val = (ans.val+tem.val)%mod;
}
}
else if(!top)
{
ans.val=ans.val*10+str[i]-'0';
ans.val%=mod;
ans.len++;
}
}
return ans;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%s%d",str,&mod);
node ans = dfs(0,strlen(str)-1);
printf("%I64d\n",ans.val);
}
return 0;
}