Problem:
Problem F
Trim It Step by Step
The intelligence agency of the Kingdom uses a unique encryption method;
a nonempty message consisting only of lowercase letters is encrypted into an expression <expr> complying with the grammar described by the following BNF.
<expr>
::=
<char> | <expr><expr> |
?(
<expr>
)
<char>
::=
a
|
b
|
c
|
d
|
e
|
f
|
g
|
h
|
i
|
j
|
k
|
l
|
m
|
n
|
o
|
p
|
q
|
r
|
s
|
t
|
u
|
v
|
w
|
x
|
y
|
z
The original message before encryption is the string appearing first in the lexicographic order among the possible results of applying the procedure described below to the encrypted message.
Procedure:
Repeat the following operation while
?
remains in the expression.
Choose any occurrence of a contiguous substring of the form
?(
s
)
(possibly the whole expression) such that
s
does not contain any symbols
?
,
(
, or
)
.
If
s
is empty, simply remove the chosen occurrence of
?()
.
Otherwise, replace the chosen occurrence of
?(
s
)
with the string obtained from
s
by deleting either the first or the last character.
For example, consider the expression
?(?(icp)c)
.
Then,
?(icp)
is the only occurrence that can be chosen, and this part is replaced with either
cp
or
ic
.
Thus, the whole expression becomes either
?(cpc)
or
?(icc)
.
After that, by choosing the whole expressions and replace them, there are four possible results,
pc
,
cp
,
cc
, and
ic
.
The original message is
cc
, which appears first in the lexicographic order among them.
You, an intelligence agent of the Republic, hostile to the Kingdom, have succeeded in obtaining an encrypted message, that is, an expression described above.
Find the original message.
Input
The input consists of multiple datasets.
The first line of the input consists only of the number
n
of the datasets, where
n
does not exceed 50.
The following
n
lines give the datasets, one in each line.
Each dataset is given in a single line consisting only of an expression <expr> complying with the grammar described by the BNF in the problem statement, and the expression consists of at most 1000 characters including symbols.
Output
For each dataset, output in a line the string appearing first in the lexicographic order among the possible results of applying to it the procedure in the problem statement.
It is guaranteed that the correct output is never an empty string.
Sample Input
6
?(icpc)
?(?(icpc))
?(ic)?(pc)
?(?(icp)c)
?(i?(?(c))pc)
?(bca)?(?(bca))
Output for the Sample Input
cpc
cp
cc
cc
ip
bca

Submitted solutions:

code_snippet: #include <bits/stdc++.h>

using namespace std;

void solve() {
    string s; cin >> s;
    int n = ssize(s);
    vector<int> closing(n, -1);
    stack<int> stk;
    for(int i = 0; i < n; i++) {
        if(s[i] == '?') stk.push(i);
        else if(s[i] == ')') {
            closing[stk.top()] = i;
            stk.pop();
        }
    }
    assert(stk.empty());
    auto expr = [&](auto&& self, int l, int r) -> vector<string> {
        vector<string> dp(1);
        auto merge = [&](const vector<string>& dpr) {
            vector<string> res(ssize(dp) + ssize(dpr) - 1);
            for(int i = 0; i < ssize(dp)-1; i++) {
                res[i] = dp[i] + dpr[0];
            }
            for(int i = ssize(dp)-1; i < ssize(res); i++) {
                res[i] = dpr[i-(ssize(dp)-1)];
            }
            dp.swap(res);
        };
        auto eraseone = [&](const vector<string>& cur) -> vector<string> {
            if(ssize(cur) == 1) return cur;
            vector<string> res(ssize(cur)-1);
            for(int i = 0; i < ssize(cur)-1; i++) {
                res[i] = min(cur[i+1], cur[i].substr(0, ssize(cur[i])-1));
            }
            return res;
        };
        for(int i = l; i < r; i++) {
            if(s[i] == '?') {
                vector<string> tmp = self(self, i+2, closing[i]);
                merge(eraseone(tmp));
                i = closing[i];
            } else {
                merge(vector<string>{""s + s[i], ""s});
            }
        }
        return dp;
    };
    cout << expr(expr, 0, n)[0] << '\n';
}

int main() {
    int t; cin >> t;
    while(t--) solve();
}
accuracy: 1
time_ms: 130
memory_kb: 5248
final_rank: 4

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double x) {
    wt_real(x);
}

template <class T, class U> void wt(const pair<T, U> val) {
    wt(val.first);
    wt(' ');
    wt(val.second);
}
template <size_t N = 0, typename T> void wt_tuple(const T t) {
    if constexpr (N < std::tuple_size<T>::value) {
        if constexpr (N > 0) {
            wt(' ');
        }
        const auto x = std::get<N>(t);
        wt(x);
        wt_tuple<N + 1>(t);
    }
}
template <class... T> void wt(tuple<T...> tpl) {
    wt_tuple(tpl);
}
template <class T, size_t S> void wt(const array<T, S> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}
template <class T> void wt(const vector<T> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}

void print() {
    wt('\n');
}
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    wt(head);
    if (sizeof...(Tail))
        wt(' ');
    print(forward<Tail>(tail)...);
}
void __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

string S;
int N;
char CINF = 'z'+1;

void Trim(vector<string>& A) {
    int L = A.size();
    if (L <= 1) {
        A = {};
        return;
    }
    string SINF = "";
    rep(i,0,L) SINF += CINF;
    vector<string> Ret(L-1,SINF);
    rep(i,0,L) {
        if (i != 0) chmin(Ret[i-1],A[i].substr(1,L-1));
        if (i != L-1) chmin(Ret[i], A[i].substr(0,L-1));
    }
    A = Ret;
    return;
}

void Join(vector<string>& A, vector<string> B) {
    int L = A.size(), M = B.size();
    if (L == 0) {
        A = B;
        return;
    }
    if (M == 0) {
        return;
    }
    vector<string> Ret(L+M);
    string BMIN = B[0];
    rep(i,1,M) chmin(BMIN, B[i]);
    rep(i,0,L) Ret[i] = A[i] + BMIN;
    string Temp = "";
    rep(i,0,L) Temp += CINF;
    rep(i,0,M) Ret[i+L] = Temp + B[i];
    A = Ret;
    return;
}

int main() {
int _;
cin >> _;
rep(__,0,_) {
    cin >> S;
    N = S.size();
    vector<vector<string>> DP(N);
    int Cur = 0;
    rep(i,0,N) {
        if (S[i] == '?') {
            i++;
            Cur++;
        }
        else if (S[i] == ')') {
            vector<string> A = DP[Cur];
            DP[Cur] = {};
            Cur--;
            Trim(A);
            Join(DP[Cur],A);
        }
        else {
            Join(DP[Cur],{S.substr(i,1)});
        }
    }
    cout << DP[0][0] << endl;
}
}
accuracy: 1
time_ms: 380
memory_kb: 6864
final_rank: 10

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef vector<vvb> vvvb;
typedef vector<vvvb> vvvvb;
typedef pair<ll,ll> pi;
typedef pair<ll,pi> ppi;
#define FOR(i,l,r) for(ll i=l;i<r;i++)
#define REP(i,n) FOR(i,0,n)
#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)
#define RREP(i,n) RFOR(i,0,n)
#define sz(A) (ll)(A.size())
#define ALL(A) A.begin(),A.end()
#define LB(A,x) (ll)(lower_bound(ALL(A),x)-A.begin())
#define UB(A,x) (ll)(upper_bound(ALL(A),x)-A.begin())
#define COU(A,x) (UB(A,x)-LB(A,x))
#define F first
#define S second
template<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;
template<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.F<<" "<<p.S;return os;}
template<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.F>>p.S;return is;}
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){REP(i,sz(v))os<<v[i]<<(i+1!=sz(v)?" ":"");return os;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}
template<class T>bool chmax(T&a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T>bool chmin(T&a,T b){if(b<a){a=b;return 1;}return 0;}
const ll mod=998244353;
template<const long long int mod=998244353>
struct modint{
  using mint=modint<mod>;
  long long int x;
  modint(long long int _x=0):x(_x%mod){if(x<0)x+=mod;}
  long long int val(){return x;}
  mint&operator=(const mint&a){x=a.x;return *this;}
  mint&operator+=(const mint&a){x+=a.x;if(x>=mod)x-=mod;return *this;}
  mint&operator-=(const mint&a){x-=a.x;if(x<0)x+=mod;return *this;}
  mint&operator*=(const mint&a){x*=a.x;x%=mod;return *this;}
  friend mint operator+(const mint&a,const mint&b){return mint(a)+=b;}
  friend mint operator-(const mint&a,const mint&b){return mint(a)-=b;}
  friend mint operator*(const mint&a,const mint&b){return mint(a)*=b;}
  mint operator-()const{return mint(0)-*this;}
  mint pow(long long int n){
    if(!n)return 1;
    mint a=1;
    mint _x=x;
    while(n){
      if(n&1)a*=_x;
      _x=_x*_x;n>>=1;
    }
    return a;
  }
  mint inv(){return pow(mod-2);}
  mint&operator/=(mint&a){return *this*=a.inv();}
  friend mint operator/(const mint&a,mint b){return mint(a)/=b;}
};
using mint=modint<998244353>;
int main(){
    ll _;cin>>_;
    while(_--){
        string S;cin>>S;
        ll N=sz(S);
        vector<vector<vector<string>>>DP(N+1,vector<vector<string>>(N+1));
        vi right(N);
        {
            stack<ll>st;
            REP(i,N){
                if(S[i]=='(')st.emplace(i);
                if(S[i]==')'){right[st.top()]=i;st.pop();}
            }
        }
        function<void(ll,ll)>f=[&](ll l,ll r){
            if(S[l]=='?'&&right[l+1]==r-1){
                f(l+2,r-1);
                ll L=sz(DP[l+2][r-1]);
                if(!L)return;
                DP[l][r].resize(L-1);
                REP(i,L-1)DP[l][r][i]=min(DP[l+2][r-1][i+1],DP[l+2][r-1][i].substr(0,sz(DP[l+2][r-1][i])-1));
                return;
            }
            vector<pi>P;
            FOR(i,l,r){
                if(S[i]=='?'){
                    ll j=right[i+1];
                    f(i,j+1);
                    P.emplace_back(pi(i,j+1));
                    i=j;
                }
                else{
                    ll j=i;
                    while(i<r&&S[i]!='?')i++;
                    DP[j][i].resize(i-j);
                    DP[j][i][0]=S.substr(j,i-j);
                    FOR(k,1,i-j)DP[j][i][k]=S.substr(j+k,i-j-k);
                    P.emplace_back(pi(j,i));
                    i--;
                }
            }
            ll L=0;
            for(auto[i,j]:P)L+=sz(DP[i][j]);
            DP[l][r].resize(L);
            string s;
            RREP(i,sz(P)){
                ll x=P[i].F,y=P[i].S;
                FOR(j,L-sz(DP[x][y]),L)DP[l][r][j]=DP[x][y][j-L+sz(DP[x][y])]+s;
                if(sz(DP[x][y]))s=DP[x][y][0]+s;
                L-=sz(DP[x][y]);
            }
        };
        f(0,N);
        cout<<DP[0][N][0]<<endl;
    }
    return 0;
}
accuracy: 1
time_ms: 220
memory_kb: 54236
final_rank: 13

code_snippet: /// 生成AI不使用 / Not using generative AI

// #pragma GCC target ("avx")
// #pragma GCC optimize("Ofast")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#ifdef MARC_LOCAL
#define _GLIBCXX_DEBUG
#endif

#ifdef ATCODER
#include <atcoder/all>
using namespace atcoder;
#endif

#include <bits/stdc++.h>
using namespace std;

//#define int long long
using ll = long long; using vll = vector<ll>; using vvll = vector<vll>; using vvvll = vector<vvll>; using vvvvll = vector<vvvll>;
using vi = vector<int>; using vvi = vector<vi>; using vvvi = vector<vvi>; using vvvvi = vector<vvvi>;
using ld = long double; using vld = vector<ld>; using vvld = vector<vld>; using vd = vector<double>;
using vc = vector<char>; using vvc = vector<vc>; using vs = vector<string>;
using vb = vector<bool>; using vvb = vector<vb>; using vvvb = vector<vvb>;
using pii = pair<int, int>; using pcc = pair<char, char>; using pll = pair<ll, ll>; using pli = pair<ll, int>; using pdd = pair<double, double>; using pldld = pair<ld,ld>;
using vpii = vector<pii>; using vvpii = vector<vpii>; using vpll = vector<pll>; using vvpll = vector<vpll>; using vpldld = vector<pldld>;
using ui = unsigned int; using ull = unsigned long long;
using i128 = __int128; using f128 = __float128;
template<class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) vector<vector<type> > name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...) vector<vector<vector<type> > > name(h, vector<vector<type> >(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) vector<vector<vector<vector<type> > > > name(a, vector<vector<vector<type> > >(b, vector<vector<type> >(c, vector<type>(__VA_ARGS__))))

#define overload4(a,b,c,d,name,...) name
#define rep1(n) for(ll i = 0; i < (ll)n; i++)
#define rep2(i,n) for(ll i = 0; i < (ll)n; i++)
#define rep3(i,a,b) for (ll i = a; i < (ll)b; i++)
#define rep4(i,a,b,c) for (ll i = a; i < (ll)b; i += (ll)c)
#define rep(...) overload4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)
#define repback1(n) for (ll i = (ll)n-1; i >= 0; i--)
#define repback2(i,n) for (ll i = (ll)n-1; i >= 0; i--)
#define repback3(i,a,b) for (ll i = (ll)b-1; i >= (ll)a; i--)
#define repback4(i,a,b,c) for (ll i = (ll)b-1; i >= (ll)a; i -= (ll)c)
#define repback(...) overload4(__VA_ARGS__,repback4,repback3,repback2,repback1)(__VA_ARGS__)
#define all(x) (x).begin(), (x).end()
#define include(y, x, H, W) (0 <= (y) && (y) < (H) && 0 <= (x) && (x) < (W))
#define inrange(x, down, up) ((down) <= (x) && (x) <= (up))
#define pb push_back
#define eb emplace_back
#define fir first
#define sec second
#define TIMER_START TIME_START = clock()
#ifdef MARC_LOCAL
// https://trap.jp/post/1224/
#define debug1(x) cout << "debug L" << __LINE__ <<": " << (#x) << ": " << (x) << endl
#define debug2(x, y) cout << "debug L" << __LINE__ <<": " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << endl
#define debug3(x, y, z) cout << "debug L" << __LINE__ <<": " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << endl
#define debug4(x, y, z, w) cout << "debug L" << __LINE__ <<": " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << ", " << (#w) << ": " << (w) << endl
#define debug5(x, y, z, w, v) cout << "debug L" << __LINE__ <<": " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << ", " << (#w) << ": " << (w) << ", " << (#v) << ": " << (v) << endl
#define debug6(x, y, z, w, v, u) cout << "debug L" << __LINE__ <<": " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << ", " << (#w) << ": " << (w) << ", " << (#v) << ": " << (v) << ", " << (#u) << ": " << (u) << endl
#define overload6(a, b, c, d, e, f, g,...) g
#define debug(...) overload6(__VA_ARGS__, debug6, debug5, debug4, debug3, debug2, debug1)(__VA_ARGS__)
#define debuga cerr << __LINE__ << endl
#define debugnl cout << endl
#define Case(i) cout << "Case #" << (i) << ": "
#define TIMECHECK cerr << 1000.0 * static_cast<double>(clock() - TIME_START) / CLOCKS_PER_SEC << "ms" << endl
#define LOCAL 1
#else
#define debug1(x) void(0)
#define debug2(x, y) void(0)
#define debug3(x, y, z) void(0)
#define debug4(x, y, z, w) void(0)
#define debug5(x, y, z, w, v) void(0)
#define debug6(x, y, z, w, v, u) void(0)
#define debug(...) void(0)
#define debuga void(0)
#define debugnl void(0)
#define Case(i) void(0)
#define TIMECHECK void(0)
#define LOCAL 0
#endif

//mt19937_64 rng(0);
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
clock_t TIME_START;
const long double pi = 3.141592653589793238462643383279L;
const long long INFL = 1000000000000000000ll;
const long long INFLMAX = numeric_limits< long long >::max(); // 9223372036854775807
const int INF = 1000000000;
const int INFMAX = numeric_limits< int >::max(); // 2147483647
const long double INFD = numeric_limits<ld>::infinity();
const long double EPS = 1e-10;
const int mod1 = 1000000007;
const int mod2 = 998244353;
const vi dx1 = {1,0,-1,0};
const vi dy1 = {0,1,0,-1};
const vi dx2 = {0, 1, 1, 1, 0, -1, -1, -1};
const vi dy2 = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr char nl = '\n';
constexpr char bl = ' ';

std::ostream &operator<<(std::ostream &dest, __int128_t value) { std::ostream::sentry s(dest); if (s) {__uint128_t tmp = value < 0 ? -value : value; char buffer[128]; char *d = std::end(buffer); do {--d;*d = "0123456789"[tmp % 10];tmp /= 10;} while (tmp != 0);if (value < 0) {--d;*d = '-';}int len = std::end(buffer) - d;if (dest.rdbuf()->sputn(d, len) != len) {dest.setstate(std::ios_base::badbit);}}return dest; }
__int128 parse(string &s) { __int128 ret = 0; for (int i = 0; i < (int)s.length(); i++) if ('0' <= s[i] && s[i] <= '9') ret = 10 * ret + s[i] - '0'; return ret; } // for __int128 (https://kenkoooo.hatenablog.com/entry/2016/11/30/163533)
template<class T> ostream& operator << (ostream& os, vector<T>& vec) { os << "["; for (int i = 0; i<(int)vec.size(); i++) { os << vec[i] << (i + 1 == (int)vec.size() ? "" : ", "); } os << "]"; return os; } /// vector 出力
template<class T, class U> ostream& operator << (ostream& os, pair<T, U>& pair_var) { os << "(" << pair_var.first << ", " << pair_var.second << ")"; return os; } // pair 出力
template<class T, class U> ostream& operator << (ostream& os, map<T, U>& map_var) { os << "{"; for (auto itr = map_var.begin(); itr != map_var.end(); itr++) { os << "(" << itr->first << ", " << itr->second << ")"; itr++; if(itr != map_var.end()) os << ", "; itr--; } os << "}"; return os; } // map出力
template<class T> ostream& operator << (ostream& os, set<T>& set_var) { os << "{"; for (auto itr = set_var.begin(); itr != set_var.end(); itr++) { os << *itr; ++itr; if(itr != set_var.end()) os << ", "; itr--; } os << "}"; return os; } /// set 出力

bool equals(long double a, long double b) { return fabsl(a - b) < EPS; }
template<class T> int sign(T a) { return equals(a, 0) ? 0 : a > 0 ? 1 : -1; }
long double radian_to_degree(long double r) { return (r * 180.0 / pi); }
long double degree_to_radian(long double d) { return (d * pi / 180.0); }

int popcnt(unsigned long long a){ return __builtin_popcountll(a); } // ll は 64bit対応！
int MSB1(unsigned long long x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); } // MSB(1), 0-indexed ( (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2) )
int LSB1(unsigned long long x) { return (x == 0 ? -1 : __builtin_ctzll(x)); } // LSB(1), 0-indexed ( (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2) )
long long maskbit(int n) { return (1LL << n) - 1; }
bool bit_is1(long long x, int i) { return ((x>>i) & 1); }
string charrep(int n, char c) { return std::string(n, c); }
template<class T> T square(T x) { return (x) * (x); }
template<class T>void UNIQUE(T& A) {sort(all(A)); A.erase(unique(all(A)), A.end());}
template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }
template<class T, class U> bool chmin(T& a, const U& b){ return chmin(a, (T)b); }
template<class T, class U> bool chmax(T& a, const U& b){ return chmax(a, (T)b); }
void YESNO(bool b) {if(b){cout<<"YES"<<'\n';} else{cout<<"NO"<<'\n';}} void YES() {YESNO(true);} void NO() {YESNO(false);}
void yesno(bool b) {if(b){cout<<"yes"<<'\n';} else{cout<<"no"<<'\n';}} void yes() {yesno(true);} void no() {yesno(false);}
void YesNo(bool b) {if(b){cout<<"Yes"<<'\n';} else{cout<<"No"<<'\n';}} void Yes() {YesNo(true);} void No() {YesNo(false);}
void POSIMPOS(bool b) {if(b){cout<<"POSSIBLE"<<'\n';} else{cout<<"IMPOSSIBLE"<<'\n';}}
void PosImpos(bool b) {if(b){cout<<"Possible"<<'\n';} else{cout<<"Impossible"<<'\n';}}
void posimpos(bool b) {if(b){cout<<"possible"<<'\n';} else{cout<<"impossible"<<'\n';}}
void FIRSEC(bool b) {if(b){cout<<"FIRST"<<'\n';} else{cout<<"SECOND"<<'\n';}}
void firsec(bool b) {if(b){cout<<"first"<<'\n';} else{cout<<"second"<<'\n';}}
void FirSec(bool b) {if(b){cout<<"First"<<'\n';} else{cout<<"Second"<<'\n';}}
void AliBob(bool b) {if(b){cout<<"Alice"<<'\n';} else{cout<<"Bob"<<'\n';}}
void TakAok(bool b) {if(b){cout<<"Takahashi"<<'\n';} else{cout<<"Aoki"<<'\n';}}
int GetTime() {return 1000.0*static_cast<double>(clock() - TIME_START) / CLOCKS_PER_SEC;}
ll myRand(ll B) {return (unsigned long long)rng() % B;}
template<class T> void print(const T& x, const char endch = '\n') { cout << x << endch; }

template<class T> T ceil_div(T x, T y) { assert(y); return (x > 0 ? (x + y - 1) / y : x / y); }
template<class T> T floor_div(T x, T y) { assert(y); return (x > 0 ? x / y : (x - y + 1) / y); }
template<class T> pair<T, T> divmod(T x, T y) { T q = floor_div(x, y); return {q, x - q * y}; } /// (q, r) s.t. x = q*y + r 
ll GCD(ll a, ll b) { if(a < b) swap(a, b); if(b == 0) return a; if(a%b == 0) return b; else return GCD(b, a%b); }
ll LCM(ll a, ll b) { assert(GCD(a,b) != 0); return a / GCD(a, b) * b; }
ll MOD(ll &x, const ll P) { ll ret = x%P; if(ret < 0) ret += P; return x = ret; } /// x % P を非負整数に直す
ll mpow(ll x, ll n, const ll mod) { x %= mod; ll ret = 1; while(n > 0) { if(n & 1) ret = ret * x % mod; x = x * x % mod; n >>= 1; } return ret; } /// x^n % mod を計算
ll lpow(ll x, ll n) { ll ret = 1; while(n > 0){ if(n & 1) ret = ret * x; x = x * x; n >>= 1; } return ret; } /// x^nを計算
string toBinary(ll n) { if(n == 0) return "0"; assert(n > 0); string ret; while (n != 0){ ret += ( (n & 1) == 1 ? '1' : '0' ); n >>= 1; } reverse(ret.begin(), ret.end()); return ret; } /// 10進数(long long) -> 2進数(string)への変換
ll toDecimal(string S) { ll ret = 0; for(int i = 0; i < (int)S.size(); i++){ ret *= 2LL; if(S[i] == '1') ret += 1; } return ret; } /// 2進数(string)　→　10進数(long long)への変換
int ceil_pow2(ll n) { int x = 0; while ((1ll << x) < n) x++; return x;} /// return minimum non-negative `x` s.t. `n <= 2**x`
int floor_pow2(ll n) { int x = 0; while ((1ll << (x+1)) <= n) x++; return x;} /// return maximum non-negative `x` s.t. `n >= 2**x`



// ############################
// #                          #
// #    C O D E  S T A R T    #
// #                          #
// ############################

typedef string::const_iterator State;


/// ParseErrorが発生したときのエラー情報用
// TODO : 使いやすいよう設定し直す
class ParseError : public std::exception {
    public:
        // デフォルトコンストラクタ
        ParseError() : message("Parse error") {}

        // コンストラクタ：カスタムエラーメッセージを持つ
        ParseError(const std::string& msg, int line = -1, int column = -1)
            : message(msg), line(line), column(column) {
            buildFullMessage();
        }

        // コンストラクタ：行と列情報を含む
        ParseError(int line, int column)
            : message("Parse error"), line(line), column(column) {
            buildFullMessage();
        }

        // エラーメッセージを取得するメンバ関数
        const char* what() const noexcept override {
            return fullMessage.c_str();
        }

        // 行番号を取得するメンバ関数
        int getLine() const {
            return line;
        }

        // 列番号を取得するメンバ関数
        int getColumn() const {
            return column;
        }

    private:
        std::string message;
        std::string fullMessage;
        int line;
        int column;

        // エラーメッセージを構築するプライベート関数
        void buildFullMessage() {
            std::ostringstream oss;
            oss << message;
            if (line >= 0) {
                oss << " at line " << line;
            }
            if (column >= 0) {
                oss << ", column " << column;
            }
            fullMessage = oss.str();
        }
};


/// begin が 期待される文字 expectedを指していたらbeginを一つ進める（期待する文字でなければエラー発生）
// assertのようなイメージ、デバッグ用（使用例: 式の最後に=が来るのであれば、consume(begin, '=')として最後まで到達してることを確認できる）
void consume(State& begin, const char expected) {
    if (*begin == expected) {
        begin++;
    }
    else {
        cerr << "Expected char is '" << expected << "' but got '" << *begin << "'" << endl;
        cerr << "Rest string is '";
        while (*begin) {
            cerr << *begin++;
        }
        cerr << "'" << endl;
        throw ParseError();
    }
}

struct Node {
    int lch = -1; // 左の子のidx 
    int rch = -1; // 右の子のidx
    int type; // どの生成規則を適用したか？ (連接: 0, 削減: 1, 文字列: 2)
    int len; // そのノードから生成される文字列の最終的な長さ
    string S; // 葉の場合のみ使用
};

vector<Node> tree; // 構文木 -> 構文木上でdpすることを意識

// chomsky 標準形的な感じで、
//  ・expr1 -> expr2 expr1 | expr2
//  ・expr2 -> char | ?(expr1)
//  ・char  -> [a~z]*
// と書き換え

int expr2(State& it);
int expr1(State& it) {
    int idx = expr2(it);
    
    while(*it != ')' && *it != '#') {
        Node node;
        node.lch = idx;
        node.rch = expr1(it);
        node.len = tree[node.lch].len + tree[node.rch].len;
        node.type = 0;

        idx = tree.size();
        tree.eb(node);
    }

    return idx;
}

string str(State& it);
int expr2(State& it) {
    int idx;

    if(*it == '?') {
        consume(it, '?');
        consume(it, '(');

        Node node;
        node.lch = expr1(it);
        node.len = max(0,tree[node.lch].len - 1); // 削られるので引く必要
        node.type = 1;

        idx = tree.size();
        tree.eb(node);
        consume(it, ')');
    }
    else {
        Node node;
        node.S = str(it);
        node.len = node.S.size();
        node.type = 2;

        idx = tree.size();
        tree.eb(node);
    }

    return idx;
}

string str(State& it) {
    string ret;
    while(*it != '?' && *it != ')' && *it != '#') {
        ret += *it;
        it++;
    }
    return ret;
}



void solve() {
    tree.clear();
    string S; cin >> S;
    S += '#';
    State it = S.begin();

    int root = expr1(it);
    int M = tree.size();

    vector<map<int,string> > dp(M); // dp[i][j]:= 頂点iを根とする部分木に関して、その祖先によって左からj文字削られている時の、辞書順最小の文字列 -> 右から削られている場合に関しては、prefixを取れば良い
    auto dfs = [&](auto dfs, int v, int l)->string{
        string ret = "";
        if(dp[v].find(l) != dp[v].end()) {
            return dp[v][l];
        }


        if(tree[v].type == 0) {
            int lidx = tree[v].lch;
            int ridx = tree[v].rch;

            if(tree[lidx].len > l) {
                ret = dfs(dfs, lidx, l) + dfs(dfs, ridx, 0);
            }
            else {
                ret = dfs(dfs, ridx, l-tree[lidx].len);
            }
        }
        else if(tree[v].type == 1) {
            int lidx = tree[v].lch;
            // 右消去
            ret = dfs(dfs, lidx, l);
            if(ret.size()) ret.pop_back();

            // 左消去
            chmin(ret, dfs(dfs, lidx, l+1));
        }
        else {
            if(tree[v].len <= l) {
                ret = "";
            }
            else {
                ret = tree[v].S.substr(l);
            }
        }

        return dp[v][l] = ret;
    };
    debug(dp);

    cout << dfs(dfs, root, 0) << nl;

}



signed main() {
    cin.tie(0); ios_base::sync_with_stdio(false);
    TIMER_START;
    //cout << fixed << setprecision(15);
    

    int tt = 1;
    cin >> tt;
    while(tt--){
        solve();
    }

    TIMECHECK;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 7964
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
void solve() {
    auto operate = [](vector<string>& dp) {
        int n = dp.size();
        if (n == 0) return;
        int k = dp[0].size();
        if (k == 0) return;
        // dp[i]:=前からi文字消すことになった時のmin (予定調和dp)
        for (int i = 0; i < n; i++) {
            dp[i] = dp[i].substr(0, k - 1);
            if (i < n - 1) dp[i] = min(dp[i], dp[i + 1].substr(1));
        }
        dp.pop_back();
    };
    auto merge = [](vector<string>& l, vector<string> r) {
        int L = l.size(), R = r.size();
        if (R == 0) return;
        if (L == 0) return swap(l, r);
        string min_r = *min_element(r.begin(), r.end());
        int k = l[0].size();
        for (int i = 0; i < L; i++) l[i] += min_r;
        // 先頭からk文字消さないとペナルティINF
        for (int i = 0; i < R; i++) l.push_back(string(k, 'z' + 1) + r[i]);
        return;
    };
    string s;
    cin >> s;
    vector<vector<string>> dp(s.size());
    int cur = 0;
    for (char c : s) {
        if (c == '?') continue;
        if (c == '(') {
            cur++;
        } else if (c == ')') {
            operate(dp[cur]);
            merge(dp[cur - 1], dp[cur]);
            dp[cur].clear();
            cur--;
        } else {
            merge(dp[cur], {string(1, c)});
        }
    }
    cout << *min_element(dp[0].begin(), dp[0].end()) << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while (t--) solve();
}
accuracy: 1
time_ms: 80
memory_kb: 6508
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
void solve() {
    auto operate = [](vector<string>& dp) {
        int n = dp.size();
        // 消し方がn通り
        if (n == 0) return;  // 空文字列なので
        int k = dp[0].size();
        if (k == 1) return dp.clear();  // 空文字列になるので
        // dp
        // if 必ず空文字列 : empty
        // otherwise : dp[i]:=前からi文字消すことになった時のmin
        for (int i = 0; i < n; i++) {
            dp[i] = dp[i].substr(0, k - 1);
            if (i < n - 1) dp[i] = min(dp[i], dp[i + 1].substr(1));
        }
        dp.pop_back();
    };
    auto merge = [](vector<string>& l, vector<string> r) {
        int L = l.size(), R = r.size();
        if (R == 0) return;
        if (L == 0) return swap(l, r);
        string min_r = *min_element(r.begin(), r.end());
        int k = l[0].size();
        for (int i = 0; i < L; i++) l[i] += min_r;
        // 先頭から消さないといけないことにする
        for (int i = 0; i < R; i++) l.push_back(string(k, 'z' + 1) + r[i]);
        return;
    };
    string s;
    cin >> s;
    vector<vector<string>> dp(s.size());
    int cur = 0;
    for (char c : s) {
        if (c == '?') continue;
        if (c == '(') {
            cur++;
        } else if (c == ')') {
            operate(dp[cur]);
            merge(dp[cur - 1], dp[cur]);
            dp[cur].clear();
            cur--;
        } else {
            merge(dp[cur], {string(1, c)});
        }
    }
    cout << *min_element(dp[0].begin(), dp[0].end()) << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while (t--) solve();
}
accuracy: 1
time_ms: 90
memory_kb: 6592
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
void solve() {
    auto operate = [](vector<string>& dp) {
        int n = dp.size();
        // 消し方がn通り
        if (n == 0) return;  // 空文字列なので
        int k = dp[0].size();
        if (k == 1) return dp.clear();  // 空文字列になるので
        // dp
        // if 必ず空文字列 : empty
        // otherwise : dp[i]:=前からi文字消すことになった時のmin
        for (int i = 0; i < n; i++) {
            dp[i] = dp[i].substr(0, k - 1);
            if (i < n - 1) dp[i] = min(dp[i], dp[i + 1].substr(1));
        }
        dp.pop_back();
    };
    auto merge = [](vector<string>& l, vector<string> r) {
        int L = l.size(), R = r.size();
        if (R == 0) return;
        if (L == 0) return swap(l, r);
        string min_r = *min_element(r.begin(), r.end());
        int k = l[0].size();
        for (int i = 0; i < L; i++) l[i] += min_r;
        // 先頭から消さないといけないことにする
        for (int i = 0; i < R; i++) l.push_back(string(L, 'z' + 1) + r[i]);
        return;
    };
    string s;
    cin >> s;
    vector<vector<string>> dp(s.size());
    int cur = 0;
    for (char c : s) {
        if (c == '?') continue;
        if (c == '(') {
            cur++;
        } else if (c == ')') {
            operate(dp[cur]);
            merge(dp[cur - 1], dp[cur]);
            dp[cur].clear();
            cur--;
        } else {
            merge(dp[cur], {string(1, c)});
        }
    }
    cout << *min_element(dp[0].begin(), dp[0].end()) << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while (t--) solve();
}
accuracy: 1
time_ms: 90
memory_kb: 6512
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
#define rep(i,n) for(ll i=0;i<ll(n);i++)
#define all(A) A.begin(),A.end()
template <class T>
void chmax(T& p, T q) { p = max(p, q); };
template <class T>
void chmin(T& p, T q) { p = min(p, q); };

const char INF = 'z' + 1;
string BASESTR="{";
vector<string> trim(vector<string>& S) {

    ll SN = S.size();
    if (SN <= 1)return {};
    ll N = S[0].size();
    BASESTR="";
    rep(i,SN-1)BASESTR.push_back(INF);
    vector<string> R(SN - 1,BASESTR);
    rep(i, SN) {
        if(i!=0)chmin(R[i-1],S[i].substr(1, N - 1));
        if(i!=SN-1)chmin(R[i],S[i].substr(0, N - 1));
    }
    return R;
}

vector<string> merge(vector<string>& A, vector<string> B) {
    ll AN = A.size();
    ll BN = B.size();
    if (AN == 0) {
        A = B;
        return B;
    }
    if (BN == 0)return A;
    vector<string> R(AN + BN);
    string BM = B[0];
    rep(i, BN)chmin(BM, B[i]);
    rep(i, AN) {
        R[i] = A[i] + BM;
    }
    string BASE;
    rep(i, AN)BASE.push_back(INF);
    rep(i, BN) {
        R[i + AN] = BASE + B[i];
    }
    A = R;
    return R;
}

void solve(string S) {
    ll N = S.size();
    stack<vector<string>> ST;
    vector<vector<string>> STT(N);
    ll cnt = 0;
    rep(i, N) {
        if (S[i] == '?') {
            i++;
            cnt++;
        }
        else if (S[i] == ')') {
            auto A = STT[cnt];
            STT[cnt] = {};
            A = trim(A);
            cnt--;
            merge(STT[cnt], A);
        }
        else {
            string NW = "";
            NW.push_back(S[i]);
            merge(STT[cnt], { NW });
        }
    }
    auto AN = STT[0];
    for (auto v : AN)chmin(AN[0], v);
    cout << AN[0] << endl;
}


int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);


    ll N;
    cin >> N;
    rep(i, N) {
        string S;
        cin >> S;
        solve(S);
    }


}
accuracy: 1
time_ms: 410
memory_kb: 6820
final_rank: 11

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

string s;
int n;

vector<string> solve(int L, int R) { 
    vector<string> ans = {};
    vector<int> stack;
    for(int i : rep(L, R)) {
        if(s[i] == '?') {

        } else if(s[i] == '(') {
            stack.push_back(i);
        } else if(s[i] == ')') {
            int p = stack.back() + 1; stack.pop_back();
            if(stack.empty()) {
                vector<string> a = solve(p, i);
                const int m = a.size();
                if(m <= 1) continue;
                vector<string> b(m - 1);
                for(int k : rep(m - 1)) {
                    b[k] = min(a[k].substr(0, a[k].size() - 1), a[k + 1]);
                }
                for(string& x : ans) x += b[0];
                ans.insert(ans.end(), b.begin(), b.end());
            }
        } else {
            if(stack.empty()) {
                for(string& x : ans) x += s[i];
                ans.push_back(""s + s[i]);
            }
        }
    }
    return ans;
}

int main() {
    int t = in();
    for(int t_ : rep(t)) {
        cin >> s;
        n = s.size();
        print(solve(0, n)[0]);
    }
}
accuracy: 1
time_ms: 70
memory_kb: 4216
final_rank: 2

code_snippet: #include <bits/stdc++.h>

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)
#define all(v) v.begin(), v.end()

using ll = long long;
using ld = long double;
using ull = unsigned long long;

template <typename T> bool chmin(T &a, const T &b) {
    if (a <= b) return false;
    a = b;
    return true;
}
template <typename T> bool chmax(T &a, const T &b) {
    if (a >= b) return false;
    a = b;
    return true;
}

#define debug(...)                                                     \
    std::cerr << "LINE: " << __LINE__ << " [" << #__VA_ARGS__ << "]:", \
        debug_out(__VA_ARGS__)

void debug_out() {
    std::cerr << std::endl;
}

template <typename Head, typename... Tail> void debug_out(Head h, Tail... t) {
    std::cerr << " " << h;
    if (sizeof...(t) > 0) std::cerr << " :";
    debug_out(t...);
}

template <typename T1, typename T2>
std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &pa) {
    return os << pa.first << " " << pa.second;
}

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec) {
    for (std::size_t i = 0; i < vec.size(); i++)
        os << vec[i] << (i + 1 == vec.size() ? "" : " ");
    return os;
}

typedef std::string::const_iterator State;

bool expect(State &begin, char expected) {
    return *begin == expected;
}

void consume(State &begin, char expected) {
    assert(*begin == expected);
    begin++;
}

bool isdigit(char c) {
    return '0' <= c && c <= '9';
}

bool isAlpha(char c) {
    return 'A' <= c && c <= 'Z';
}

bool isalpha(char c) {
    return 'a' <= c && c <= 'z';
}

struct Node {
    int lch = -1, rch = -1;
    int type;  // 0: merged type, 1: ?() type, 2: string type;
    int len = 0;
    std::string s = "";
};

std::vector<Node> tree;

int Stmt(State &);
int Expr(State &);
int Char(State &);

int Stmt(State &begin) {
    int now = Expr(begin);
    while (!expect(begin, ')') && !expect(begin, ';')) {
        Node node;
        node.type = 0;
        node.lch = now;
        node.rch = Expr(begin);
        node.len = tree[node.lch].len + tree[node.rch].len;
        now = tree.size();
        tree.emplace_back(node);
    }
    return now;
}

int Expr(State &begin) {
    if (expect(begin, '?')) {
        Node node;
        node.type = 1;
        consume(begin, '?');
        consume(begin, '(');
        node.lch = Stmt(begin);
        consume(begin, ')');
        int idx = tree.size();
        chmax(node.len, tree[node.lch].len - 1);
        tree.emplace_back(node);
        return idx;
    } else {
        return Char(begin);
    }
}

int Char(State &begin) {
    assert(isalpha(*begin));
    Node node;
    node.type = 2;
    while (isalpha(*begin)) {
        node.s += *begin;
        consume(begin, node.s.back());
    }
    node.len = node.s.size();
    int idx = tree.size();
    tree.emplace_back(node);
    return idx;
}

void solve() {
    tree.clear();
    std::string s;
    std::cin >> s;
    s += ';';
    State begin = s.begin();
    int root = Stmt(begin);
    consume(begin, ';');
    int n = tree.size();
    std::vector<std::map<int, std::string>> dp(n);
    auto update = [&](int idx, int l, const std::string &t) -> void {
        if(dp[idx].find(l) == dp[idx].end()) dp[idx][l] = t;
        else if(t < dp[idx][l]) dp[idx][l] = t;
    };
    auto dfs = [&](auto &&self, int v, int l) -> void {
        if(dp[v].find(l) != dp[v].end()) {
            return;
        }
        if(tree[v].type == 0) {
            int lch = tree[v].lch;
            int rch = tree[v].rch;
            assert(lch != -1 && rch != -1);
            if(l < tree[lch].len) {
                self(self, lch, l);
                self(self, rch, 0);
                dp[v][l] = dp[lch][l] + dp[rch][0];
            }
            else {
                int nl = l - tree[lch].len;
                self(self, rch, nl);
                dp[v][l] = dp[rch][nl];
            }
        }
        else if(tree[v].type == 1) {
            int nv = tree[v].lch;
            assert(tree[v].rch < 0);
            {
                self(self, nv, l);
                std::string t = dp[nv][l];
                if(!t.empty()) t.pop_back();
                update(v, l, t);
            }
            {
                self(self, nv, l+1);
                update(v, l, dp[nv][l+1]);
            }
        }
        else if(tree[v].type == 2) {
            if(int(tree[v].s.size()) <= l) {
                dp[v][l] = "";
                return;
            }
            dp[v][l] = tree[v].s.substr(l);
            return;
        }
        else {
            assert(0);
        }
    };
    dfs(dfs, root, 0);
    std::cout << dp[root][0] << '\n';
}

int main() {
    int n;
    std::cin >> n;
    while (n--) {
        solve();
    }
}
accuracy: 1
time_ms: 10
memory_kb: 8420
final_rank: 9

code_snippet: #include <bits/stdc++.h>

using namespace std;

char S[1001];

vector<string> dfs(int l, int r) {
    bool f = true;
    int cc = 1;
    for (int i=l+2; i<r-1; i++) {
        cc += (S[i] == '(') - (S[i] == ')');
        f &= cc > 0;
    }
    if (f && S[l] == '?' && S[r-1] == ')') {
        if (r-l <= 3) return {""};
        auto p = dfs(l+2, r-1);
        for (int i=0; i+1<p.size(); i++) {
            p[i] = min(p[i].substr(0, p[i].size()-1), p[i+1]);
        }
        if (p.size()) p.pop_back();
        if (p.empty()) p.push_back("");
        return p;
    }
    bool pure = true;
    for (int i=l; i<r; i++) pure &= !!islower(S[i]);
    if (pure) {
        vector<string> res;
        string t = "";
        for (int i=l; i<r; i++) t += S[i];
        for (int i=0; i<=r-l; i++) {
            res.push_back(t.substr(i, t.size()-i));
        }
        return res;
    }

    vector<string> res;
    auto update = [&](vector<string> &X) {
        if (res.empty()) {
            res = X;
            return;
        }

        vector<string> temp;

        for (auto &item : res) temp.push_back(item + X[0]);
        for (int i=0; i<X.size(); i++) {
            int t = i + res[0].size();
//            cerr << "res[0]:" << res[0] << "+" << X[i] << "=>" << t << "(" << temp[t] << ")" << endl;
            if (t < temp.size()) {
                temp[t] = min(temp[t], X[i]);
            } else {
                assert(temp.size() == t);
                temp.push_back(X[i]);
            }
        }
        res = temp;
    };

    //split
    int sl = l, c = 0;
    for (int i=l; i<=r; i++) {
        if ((S[i] == '?' && c == 0 && sl < i) || (i == r && sl < i)) {
            auto r = dfs(sl, i);
            update(r);
            sl = i;
        } else if (S[i] == '(') {
            c++;
        } else if (S[i] == ')') {
            c--;
            if (c == 0) {
                auto r = dfs(sl, i+1);
                update(r);
                sl = i+1;
            }
        }
    }

    return res;
}

void solve() {
     scanf("%s", S);
     int N = strlen(S);

     auto r = dfs(0, N);

     cout << r[0] << endl;
}

int main() {
    int T;
    scanf("%d", &T);
    while(T--) solve();
}
accuracy: 1
time_ms: 50
memory_kb: 4188
final_rank: 1

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

map<pair<int,pair<int,int>>,string> dp;

// exprの初期位置,前から後ろから何文字取り除くか
string parse(string &s,int idx,int pr,int ba){
    // cerr << s << " " << idx << " " << pr << " " << ba << endl;
    if(dp.find({idx,{pr,ba}}) != dp.end()){
        return dp[{idx,{pr,ba}}];
    }
    if(s[idx] != '('){
        string res = ""; res += s[idx];
        if(pr+ba >= 1) res = "";
        return res;
    }
    // 前から取り除くか後ろから取り除くかの選択が求められる
    // 開始位置,個数を持つ
    // 0のは除いてしまって良さそう
    vector<pair<int,int>> v;
    int cnt = 0;
    // idx++;

    for(int i=idx+1;i<s.size();){
        if(s[i] != '(' and s[i] != ')'){
            v.push_back({i,1});
            i++;
        }
        else if(s[i] == '('){
            int j = i;
            cnt++;
            i++;
            vector<char> uuuu;
            uuuu.push_back('(');
            while(i<s.size()){
                if(s[i] == '('){
                    uuuu.push_back('(');
                    cnt++;
                }
                else if(s[i] == ')'){
                    if(uuuu.back() != '('){
                        uuuu.pop_back();
                    }
                    for(int j=uuuu.size()-1;j>=0;j--){
                        if(uuuu[j] == '('){
                            swap(uuuu[j],uuuu.back());
                            uuuu.pop_back();
                            break;
                        }
                    }
                    cnt--;
                }
                else uuuu.push_back(s[i]);
                i++;
                if(cnt == 0) break;
            }
            if(uuuu.size() > 0){
                v.push_back({j,uuuu.size()});
            }
        }
        else if(s[i] == ')') break;
    }

    string r1,r2;

    int sum = 0;
    for(auto p:v){
        sum += p.second;
    }
    if(sum <= 1+pr+ba){
        dp[{idx,{pr,ba}}] = "";
        return "";
    }
    else{
        // 前から
        {
            pr++;
            string r = "";
            int P = pr, B = ba;
            for(int i=0;i<v.size();i++){
                if(v[i].second <= P){
                    P -= v[i].second;
                }
                else{
                    int j = v.size()-1;
                    while(1){
                        if(v[j].second <= B){
                            B -= v[j].second;
                            j--;
                        }
                        else break;
                    }
                    if(i == j){
                        r += parse(s,v[i].first,P,B);
                    }
                    else{
                        r += parse(s,v[i].first,P,0);
                        for(int k=i+1;k<j;k++){
                            r += parse(s,v[k].first,0,0);
                        }
                        r += parse(s,v[j].first,0,B);
                    }
                    break;
                }
            }
            r1 = r;
            pr--;
        }
        {
            ba++;
            string r = "";
            int P = pr, B = ba;
            for(int i=0;i<v.size();i++){
                if(v[i].second <= P){
                    P -= v[i].second;
                }
                else{
                    int j = v.size()-1;
                    while(1){
                        if(v[j].second <= B){
                            B -= v[j].second;
                            j--;
                        }
                        else break;
                    }
                    if(i == j){
                        r += parse(s,v[i].first,P,B);
                    }
                    else{
                        r += parse(s,v[i].first,P,0);
                        for(int k=i+1;k<j;k++){
                            r += parse(s,v[k].first,0,0);
                        }
                        r += parse(s,v[j].first,0,B);
                    }
                    break;
                }
            }
            r2 = r;
            ba--;
        }
    }
    string res = min(r1,r2);
    dp[{idx,{pr,ba}}] = res;
    return res;
}

string solve(string s){
    dp.clear();
    return parse(s,0,0,0);
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int q; cin >> q;
    while(q--){
        string s; cin >> s;
        string t = "";
        for(char c:s){
            if(c != '?') t += c;
        }
        string res = "";
        for(int i=0;i<t.size();){
            if(t[i] == '('){
                int j = i;
                int cnt = 1; i++;
                while(i<t.size()){
                    if(t[i] == '(') cnt++;
                    else if(t[i] == ')') cnt--;
                    i++;
                    if(cnt == 0) break;
                }
                res += solve(t.substr(j,i-j));
            }
            else{
                res += t[i]; i++;
            }
        }
        cout << res << endl;
    }
}
accuracy: 1
time_ms: 3010
memory_kb: 56884
final_rank: 14

code_snippet: #if 1
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <array>
#include <deque>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <numeric>
#include <assert.h>
#include <bitset>
#include <list>
#include <cmath>
#include <stdio.h>

auto& in = std::cin;
auto& out = std::cout;
#define all_range(C) std::begin(C), std::end(C)
const double PI = 3.141592653589793238462643383279502884197169399375105820974944;


template<typename T, typename U>
std::enable_if_t<std::rank<T>::value == 0> fill_all(T& arr, const U& v) {
    arr = v;
}
template<typename ARR, typename U>
std::enable_if_t<std::rank<ARR>::value != 0> fill_all(ARR& arr, const U& v) {
    for (auto& i : arr) {
        fill_all(i, v);
    }
}


//先頭か末尾を取り除く
std::string_view get_minpop(std::string_view base) {
    return std::min(base.substr(1), base.substr(0, base.size()-1));
}

std::string S;
std::unordered_map<int, std::unordered_map<int, std::pair<std::string, int>>> dp;
//std::vector<int> next_q[1000];
int end_q[1000];
//先頭から追加でpop_front文字消去したときの?(S)の辞書順最小
std::pair<std::string, int> func(const int i, const int pop_front) {

    assert(pop_front >= 0);
    if (dp.count(i)>0 && dp[i].count(pop_front)>0) {
        return dp[i][pop_front];
    }
    auto& memo = dp[i][pop_front];

    assert(S[i] == '?');
    assert(S[i + 1] == '(');

    //if (next_q[i].empty()) {
    //
    //    auto len = end_q[i] - (i + 2);
    //    if (len - 1 <= pop_front) {
    //        return memo = { "", pop_front - (len - 1) };
    //    }
    //    std::string_view poped(S);
    //    poped = poped.substr(i+2, len).substr(pop_front);
    //
    //    assert(poped.find(')') == -1);
    //
    //    assert(get_minpop(poped).size() == len - 1 - pop_front);
    //    return memo = { std::string(get_minpop(poped)), 0};
    //}

    auto work = [i](int pop_f)->std::pair<std::string, int> {
        std::string res = "";
        auto index = i + 2;

        bool char_found = false;

        while (index < end_q[i]) {
            assert(index < S.size());
            assert(pop_f >= 0);
            assert(S[index] != '(');
            assert(S[index] != ')');
            if (S[index] == '?') {

                auto&& tmp = func(index, pop_f);
                if (!tmp.first.empty()) {
                    char_found = true;
                }
                if (tmp.first.empty()) {
                    assert(tmp.second >= 0);
                    if (pop_f != tmp.second) {
                        char_found = true;
                    }
                    pop_f = tmp.second;
                }
                else {
                    if (pop_f != 0) {
                        char_found = true;
                    }
                    pop_f = 0;
                    res += (tmp.first);
                }

                index = end_q[index];
                assert(S[index] == ')');
            }
            else if (pop_f > 0) {
                char_found = true;
                --pop_f;
            }
            else {
                char_found = true;
                res += S[index];
            }
            ++index;
        }
        assert(S[index] == ')');

        if (!char_found) {
            return { "", -1 };
        }
        assert(res.empty() || pop_f==0);
        return { res, pop_f };
    };

    auto pf = work(pop_front + 1);
    auto pb = work(pop_front);
    if (pb.first.empty()) {
        assert(pf.first.empty());
        if (pb.second == -1) {
            assert(pf.second == -1);
            return memo = { "", pop_front };
        }
        assert(pb.second + 1 == pf.second );
        assert(pb.second + 1 <= pop_front);
        return memo = { "", pb.second + 1 };
    }
    pb.first.pop_back();

    return memo = { std::min(pf.first,pb.first), 0 };
}

int func_q(int i) {
    //if (!next_q[i].empty()) { return end_q[i]; }
    if (end_q[i] != 0) { return end_q[i]; }
    
    assert(S[i] == '?');
    assert(S[i+1] == '(');

    //auto& next_qi = next_q[i];
    auto& end_qi = end_q[i];

    i += 2;
    while (S[i] != ')') {
        if (S[i] == '?') {
            //next_qi.push_back(i);
            i = func_q(i);
        }
        ++i;
    }
    return end_qi = i;
}

//std::string minres = { 'z' + 1,'a','a' ,'a' ,'a' ,'a' ,'a' ,'a' ,'a' ,'a' ,'a' ,'a' };
//std::map<int, bool> is_pop_front;
//std::string all_s(int i)
//{
//    assert(S[i] == '?');
//    assert(S[i + 1] == '(');
//
//    auto& next_qi = next_q[i];
//    auto& end_qi = end_q[i];
//    bool pop_F = is_pop_front[i];
//
//    std::string res = "";
//    i += 2;
//    while (S[i] != ')') {
//        if (S[i] == '?') {
//            res += all_s(i);
//            i = end_q[i];
//        }
//        else {
//            res += S[i];
//        }
//        ++i;
//    }
//    if (pop_F) { res = res.substr(1); }
//    else { res.pop_back(); }
//    return res;
//}
//std::string all_ss() {
//
//}

int main()
{
    using std::endl;
    in.sync_with_stdio(false);
    out.sync_with_stdio(false);
    in.tie(nullptr);
    out.tie(nullptr);

    int q;
    in >> q;
    while (q-- > 0) {
        in >> S;
        
        dp.clear();
        //for (auto& v : next_q) { v.clear(); }
        fill_all(end_q, 0);

        for (int i = 0; i < S.size(); i++)
        {
            if (S[i]=='?') {
                func_q(i);
            }
        }

        //for (size_t i = 0; i < S.size(); i++)
        //{
        //    if (!next_q[i].empty()) {
        //        out << "NEXT:" << i << ':';
        //        for (auto& t : next_q[i]) { out << t << ' '; }
        //        out << endl;
        //    }
        //}

        std::string res = "";
        for (int i = 0; i < S.size(); i++)
        {
            if (S[i] != '?') {
                assert(S[i] != '(');
                assert(S[i] != ')');
                res += S[i];
            }
            else {
                res += func(i, 0).first;
                i = end_q[i];
            }
        }
        out << res << endl;


    }


    using std::string;
    using std::string_view;
    auto check = [](string token, const string (&words)[5]) -> bool {
        for (string_view tmp : words) {
            if (token == tmp) return true;
        }
        return false;
    };

    return 0;
}
#endif
accuracy: 1
time_ms: 10
memory_kb: 6604
final_rank: 3

code_snippet: #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using ll=long long;
using ld=long double;
ll ILL=2167167167167167167;
const int INF=2100000000;
const ll mod=998244353;
#define rep(i,a) for (ll i=0;i<a;i++)
#define all(p) p.begin(),p.end()
template<class T> using _pq = priority_queue<T, vector<T>, greater<T>>;
template<class T> ll LB(vector<T> &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> ll UB(vector<T> &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> bool chmin(T &a,const T &b){if(a>b){a=b;return 1;}else return 0;}
template<class T> bool chmax(T &a,const T &b){if(a<b){a=b;return 1;}else return 0;}
template<class T> void So(vector<T> &v) {sort(v.begin(),v.end());}
template<class T> void Sore(vector<T> &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});}
void yneos(bool a){if(a) cout<<"Yes\n"; else cout<<"No\n";}
template<class T> void vec_out(vector<T> &p){for(int i=0;i<(int)(p.size());i++){if(i) cout<<" ";cout<<p[i];}cout<<"\n";}

bool eng(char c){
	return ('a'<=c)&&(c<='z');
}

void solve();
// oddloop
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t=1;
	cin>>t;
	rep(i,t) solve();
}

void solve(){
	string S;
	cin>>S;
	S="!("+S+")";
	int ind=0;
	vector<vector<int>> G;
	vector<string> T;
	int l=0,N=0;
	vector<int> order;
	auto f=[&](auto self,int pare)->void{
		int now=ind;
		G.push_back({});
		//cout<<now<<" "<<l<<endl;
		if(!eng(S[l])){
			T.push_back("");
			T[ind]=S[l];
			l+=2;
			while(S[l]!=')'){
				ind++;
				self(self,now);
			}
			l++;
		}
		else{
			string tmp="";
			while(eng(S[l])){
				N++;
				tmp+=S[l];
				l++;
			}
			T.push_back(tmp);
		}
		if(pare!=-1){
			G[pare].push_back(now);
		}
		order.push_back(now);
	};
	f(f,-1);/*
	rep(i,(int)(G.size())){
		cout<<i<<" : ";
		vec_out(G[i]);
		cout<<T[i]<<"\n";
	}
	cout<<"##########\n";
	string I="{";*/
	vector<vector<string>> dp(ind+1,vector<string>(N+1));
	
	vector<int> D(ind+1);
	string ans="";
	for(auto x:order){
		//cout<<x<<" "<<T[x]<<endl;
		if(eng(T[x][0])){
			D[x]=T[x].size();
			for(int L=0;L<=D[x];L++){
				//cout<<T[x].substr(L,C[x]-L-R)<<endl;
				dp[x][L]=T[x].substr(L,D[x]-L);
				//cout<<x<<" "<<L<<" "<<R<<" "<<dp[x][L][R]<<endl;
			}
		}
		else if(T[x][0]=='!'){
			for(auto y:G[x]){
				//cout<<y<<" : "<<dp[y][0][0]<<"\n";
				ans+=(dp[y][0]).substr(0,D[y]);
			}
		}
		else{
			vector<int> A;
			for(auto y:G[x]) D[x]+=D[y],A.push_back(0);
			D[x]--;
			//cout<<x<<" "<<D[x]<<"\n";
			chmax(D[x],0);
			if(D[x]==0) continue;
			for(int L=0;L<=D[x];L++){
				rep(ty,2){
					int n_l=L;
					if(ty==0) n_l++;
					int a=0;
					for(auto y:G[x]){
						if(n_l>=D[y]) A[a]=D[y],n_l-=D[y];
						else A[a]=n_l,n_l=0;
						a++;
					}
					a=0;
					string tmp;
					for(auto y:G[x]){
						tmp+=dp[y][A[a]].substr(0,D[y]-A[a]);
						a++;
					}
					if(dp[x][L].empty()) dp[x][L]=tmp;
					else chmin(dp[x][L],tmp);
				}
			}
		}
	}
	cout<<ans<<"\n";
}
accuracy: 1
time_ms: 110
memory_kb: 25428
final_rank: 12