FZU 2108(dfs模拟,大数取余)
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.
改了下,数据对上了,好像还是wa,先贴上:
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<algorithm> using namespace std; typedef long long LL; LL B; int k; char s[1010]; int dfs(LL& ans, int &i, LL& c){ int len = strlen(s); for(i; i < len;){ if(k == 0)c = 1; if(s[i] == ']'){ i = i + 2; k--; return s[i - 1] - '0'; } else if(s[i] == '['){ LL x = 0; k++; i++; int cnt = dfs(x, i, c); // cout << c << " " << cnt << " " << x << endl; LL temp = 1; while(cnt--){ ans = ans * c % B + x % B; temp = temp * c % B; ans %= B; } c = temp; } else ans = (ans * 10 + s[i] - '0')%B, c = (c * 10)%B, i++; } } int main(){ int T; cin >> T; while(T--){ scanf("%s%lld", s, &B); int i = 0; LL ans = 0; LL c = 1; k = 0; dfs(ans, i, c); printf("%lld\n", ans); } return 0; }
超内存:
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> using namespace std; typedef long long LL; int dfs(string& ans, string s, int &cur){ for(int i = cur; i < s.length();){ if(s[i] == ']'){ cur = i + 2; return s[i + 1] - '0'; } else if(s[i] == '['){ string x; i++; int cnt = dfs(x, s, i); //cout << cnt << endl; while(cnt--){ ans += x; } } else ans += s[i], i++; } } int main(){ int T; string s; LL B; cin >> T; while(T--){ cin >> s; cin >> B; int i = 0; string A; dfs(A, s, i); LL temp = 0; for(int i = 0; i < A.length(); i++){ temp = temp * 10 + A[i] - '0'; if(temp > B){ temp = temp % B; } } printf("%lld\n", temp); } return 0; }