Guest User

Untitled

a guest
Nov 20th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. //#include <bits/stdc++.h>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cstring>
  5. #include <cassert>
  6.  
  7. #include <cmath>
  8. #include <algorithm>
  9. #include <iostream>
  10.  
  11. using namespace std;
  12.  
  13. #define db(x) cout << #x " == " << x << endl
  14. #define _ << ", " <<
  15. #define fr(a,b,c) for( int a = b ; a < c ; ++a )
  16. #define rep(a,b) fr(a,0,b)
  17. #define dbg db
  18.  
  19. const int maxn = (int)1e6 + 10;
  20.  
  21. char s[maxn];
  22. int vetor[maxn], n;
  23. int f[maxn];
  24.  
  25. bool read() {
  26. scanf("%s %d",s,&n);
  27. rep(i,n) scanf("%d",vetor+i);
  28. return 1;
  29. }
  30.  
  31. int tot, ini, fim;
  32.  
  33. void go(int i, int j, int positivo) {
  34. if(i == j) {
  35.  
  36. assert(ini <= fim);
  37.  
  38. if(positivo) {
  39. //puts("+");
  40. tot += vetor[fim--];
  41. }
  42. else {
  43. //puts("-");
  44. tot -= vetor[ini++];
  45. }
  46.  
  47. return;
  48. }
  49.  
  50. if(s[i] == '(') {
  51. int pos = f[i];
  52.  
  53. go(i+1,pos-1,positivo);
  54.  
  55. pos++; // pula ')'
  56.  
  57. if(pos <= j) {
  58. if(s[pos] == '+') {
  59. go(pos+1,j,positivo);
  60. }
  61. else if(s[pos] == '-') {
  62. go(pos+1,j,1 - positivo);
  63. }
  64. else assert(0);
  65. }
  66. }
  67. else if(s[i] == 'x') {
  68. // procurar operador
  69. go(i,i,positivo);
  70.  
  71. int pos = i + 1;
  72.  
  73. if(pos <= j) {
  74. if(s[pos] == '+') {
  75. go(pos+1,j,positivo);
  76. }
  77. else if(s[pos] == '-') {
  78. go(pos+1,j,1 - positivo);
  79. }
  80. else assert(0);
  81. }
  82.  
  83. }
  84. else assert(0);
  85.  
  86. }
  87.  
  88. int pilha[maxn], q;
  89.  
  90. void process() {
  91.  
  92. q = 0;
  93.  
  94. int ct = 0;
  95. for(int i = 0; s[i]; i++) {
  96. if(s[i] == ')') {
  97. f[ pilha[q-1] ] = i;
  98.  
  99. //printf("f[%d] = %d\n",pilha[q-1],i);
  100.  
  101. q--;
  102. }
  103. else if(s[i] == '(') {
  104. pilha[q++] = i;
  105. }
  106. }
  107.  
  108. assert(q == 0);
  109.  
  110. //return;
  111.  
  112.  
  113. sort(vetor,vetor+n);
  114. ini = 0, fim = n-1, tot = 0;
  115. go(0,strlen(s)-1,1);
  116. printf("%d\n",tot);
  117. }
  118.  
  119. int main() {
  120.  
  121. /*const int L = 50000;
  122. printf("1\n");
  123. rep(i,L) printf("(x+");
  124. printf("x");
  125. rep(i,L) printf(")");
  126. printf("\n");
  127. printf("%d\n",L+1);
  128. rep(i,L+1) printf("1 "); printf("\n");
  129. return 0;
  130. */
  131.  
  132. int t = -1;
  133. cin >> t;
  134. while( t-- && read() ) process();
  135. return 0;
  136. }
Add Comment
Please, Sign In to add comment