参考这里:http://blog.csdn.net/q775968375/article/details/8828952
大神说的没错,这跟建树没有半毛线的关系,就是一DFS。。。
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 5 #define LL long long int 6 7 const int MAXN = 1010; 8 9 struct node 10 { 11 LL val, BitWide; 12 node(): val(0), BitWide(0) { } 13 }; 14 15 char str[MAXN]; 16 int MOD; 17 18 LL Qmod( LL a, LL k ) //快速幂模板 19 { 20 LL v = 1; 21 while ( k ) 22 { 23 if ( k & 1 ) v = ( v * a ) % MOD; 24 a = ( a * a ) % MOD; 25 k >>= 1; 26 } 27 return v % MOD; 28 } 29 30 node DFS( int l, int r ) 31 { 32 node ans; //本层括号的数值 33 34 int left, right, cnt; 35 int top = 0; //括号配对专用栈顶指针 36 for ( int i = l; i <= r; ++i ) 37 { 38 if ( str[i] == '[' ) 39 { 40 if ( !top ) left = i + 1; 41 ++top; 42 } 43 else if ( str[i] == ']' ) 44 { 45 --top; 46 if ( !top ) //找到一对配对括号 47 { 48 right = i - 1; 49 ++i; 50 cnt = str[i] - '0'; //本括号内的内容的重复次数 51 node temp = DFS( left, right ); //求得本括号内的数的值,以及位数(10进制下) 52 53 LL base = Qmod( 10, temp.BitWide ); //括号内的数是10的多少次方 54 55 ans.BitWide += cnt * temp.BitWide; //位数加上 56 ans.val = ( ans.val * Qmod( base, cnt ) ) % MOD; //此括号的重复次数是10的多少次方 57 58 LL st = 1, BB = base; 59 60 while ( --cnt ) //这里不好解释,我费解了半天,等等画个图贴上来 61 { 62 st += BB; 63 BB = ( BB * base ) % MOD; 64 st %= MOD; 65 } 66 67 temp.val = (temp.val * st) % MOD; 68 ans.val = ( ans.val + temp.val ) % MOD; 69 } 70 } 71 else if ( !top ) 72 { 73 ans.val = ans.val * 10 + str[i] - '0'; 74 ans.val %= MOD; 75 ++ans.BitWide; 76 } 77 } 78 79 return ans; 80 } 81 82 int main() 83 { 84 int T; 85 scanf( "%d", &T ); 86 while ( T-- ) 87 { 88 scanf( "%s%lld", str, &MOD ); 89 node ans = DFS( 0, strlen(str) - 1 ); 90 printf("%lld\n", ans.val ); 91 } 92 return 0; 93 }