Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //#include <bits/stdc++.h>
- #include <cstdio>
- #include <cstdlib>
- #include <cstring>
- #include <cassert>
- #include <cmath>
- #include <algorithm>
- #include <iostream>
- using namespace std;
- #define db(x) cout << #x " == " << x << endl
- #define _ << ", " <<
- #define fr(a,b,c) for( int a = b ; a < c ; ++a )
- #define rep(a,b) fr(a,0,b)
- #define dbg db
- const int maxn = (int)1e6 + 10;
- char s[maxn];
- int vetor[maxn], n;
- int f[maxn];
- bool read() {
- scanf("%s %d",s,&n);
- rep(i,n) scanf("%d",vetor+i);
- return 1;
- }
- int tot, ini, fim;
- void go(int i, int j, int positivo) {
- if(i == j) {
- assert(ini <= fim);
- if(positivo) {
- //puts("+");
- tot += vetor[fim--];
- }
- else {
- //puts("-");
- tot -= vetor[ini++];
- }
- return;
- }
- if(s[i] == '(') {
- int pos = f[i];
- go(i+1,pos-1,positivo);
- pos++; // pula ')'
- if(pos <= j) {
- if(s[pos] == '+') {
- go(pos+1,j,positivo);
- }
- else if(s[pos] == '-') {
- go(pos+1,j,1 - positivo);
- }
- else assert(0);
- }
- }
- else if(s[i] == 'x') {
- // procurar operador
- go(i,i,positivo);
- int pos = i + 1;
- if(pos <= j) {
- if(s[pos] == '+') {
- go(pos+1,j,positivo);
- }
- else if(s[pos] == '-') {
- go(pos+1,j,1 - positivo);
- }
- else assert(0);
- }
- }
- else assert(0);
- }
- int pilha[maxn], q;
- void process() {
- q = 0;
- int ct = 0;
- for(int i = 0; s[i]; i++) {
- if(s[i] == ')') {
- f[ pilha[q-1] ] = i;
- //printf("f[%d] = %d\n",pilha[q-1],i);
- q--;
- }
- else if(s[i] == '(') {
- pilha[q++] = i;
- }
- }
- assert(q == 0);
- //return;
- sort(vetor,vetor+n);
- ini = 0, fim = n-1, tot = 0;
- go(0,strlen(s)-1,1);
- printf("%d\n",tot);
- }
- int main() {
- /*const int L = 50000;
- printf("1\n");
- rep(i,L) printf("(x+");
- printf("x");
- rep(i,L) printf(")");
- printf("\n");
- printf("%d\n",L+1);
- rep(i,L+1) printf("1 "); printf("\n");
- return 0;
- */
- int t = -1;
- cin >> t;
- while( t-- && read() ) process();
- return 0;
- }
Add Comment
Please, Sign In to add comment