Problem:
Problem B:
Stylish
Stylish
is a programming language whose syntax comprises
names
, that are sequences of Latin alphabet letters, three types of
grouping symbols
, periods ('.'), and newlines. Grouping symbols, namely round brackets ('(' and ')'), curly brackets ('{' and '}'), and square brackets ('[' and ']'), must match and be nested properly. Unlike most other programming languages, Stylish uses periods instead of whitespaces for the purpose of term separation. The following is an example of a Stylish program.
1 ( Welcome .to
2 ......... Stylish )
3 { Stylish .is
4 .....[.( a. programming . language .fun .to. learn )
5 .......]
6 ..... Maybe .[
7 ....... It. will .be.an. official . ICPC . language
8 .......]
9 .....}
As you see in the example, a Stylish program is indented by periods. The
amount of indentation
of a line is the number of leading periods of it.
Your mission is to visit Stylish masters, learn their indentation styles, and become the youngest Stylish master. An indentation style for
well-indented
Stylish programs is defined by a triple of integers, (
R
,
C
,
S
), satisfying 1 ≤
R
,
C
,
S
≤ 20.
R
,
C
and
S
are amounts of indentation introduced by an open round bracket, an open curly bracket, and an open square bracket, respectively.
In a well-indented program, the amount of indentation of a line is given by
R
(
r
o
−
r
c
) +
C
(
c
o
−
c
c
) +
S
(
s
o
−
s
c
), where
r
o
,
c
o
, and
s
o
are the numbers of occurrences of open round, curly, and square brackets in all preceding lines, respectively, and
r
c
,
c
c
, and
s
c
are those of close brackets. The first line has no indentation in any well-indented program.
The above example is formatted in the indentation style (
R
,
C
,
S
) = (9, 5, 2). The only grouping symbol occurring in the first line of the above program is an open round bracket. Therefore the amount of indentation for the second line is 9 · (1 − 0) + 5 · (0 − 0) + 2 ·(0 − 0) = 9. The first four lines contain two open round brackets, one open curly bracket, one open square bracket, two close round brackets, but no close curly nor square bracket. Therefore the amount of indentation for the fifth line is 9 · (2 − 2) + 5 · (1 − 0) + 2 · (1 − 0) = 7.
Stylish masters write only well-indented Stylish programs. Every master has his/her own indentation style.
Write a program that imitates indentation styles of Stylish masters.
Input
The input consists of multiple datasets. The first line of a dataset contains two integers
p
(1 ≤
p
≤ 10) and
q
(1 ≤
q
≤ 10). The next
p
lines form a well-indented program
P
written by a
Stylish master and the following
q
lines form another program
Q
. You may assume that every line of both programs has at least one character and at most 80 characters. Also, you may assume that no line of
Q
starts with a period.
The last dataset is followed by a line containing two zeros.
Output
Apply the indentation style of
P
to
Q
and output the appropriate amount of indentation for each line of
Q
. The amounts must b
...(truncated)

Submitted solutions:

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
 */

struct Data {
    int A, B, C;
    Data(int a, int b, int c) : A(a), B(b), C(c) {};
};

bool Check(vector<string>& S, int A, int B, int C) {
    int CA = 0, CB = 0, CC = 0;
    int N = S.size();
    rep(i,0,N) {
        int COUNT = 0;
        while(COUNT < S[i].size()) {
            if (S[i][COUNT] == '.') COUNT++;
            else break;
        }
        if (COUNT != CA * A + CB * B + CC * C) return false;
        rep(j,0,S[i].size()) {
            if (S[i][j] == '(') CA++;
            if (S[i][j] == ')') CA--;
            if (S[i][j] == '{') CB++;
            if (S[i][j] == '}') CB--;
            if (S[i][j] == '[') CC++;
            if (S[i][j] == ']') CC--;
        }
    }
    return true;
}

int main() {
while(1) {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) return 0;
    vector<string> S(N), T(M);
    rep(i,0,N) cin >> S[i];
    rep(i,0,M) cin >> T[i];
    vector<Data> X;
    rep(i,1,21) {
        rep(j,1,21) {
            rep(k,1,21) {
                if (Check(S,i,j,k)) X.push_back(Data(i,j,k));
            }
        }
    }
    int CA = 0, CB = 0, CC = 0;
    rep(i,0,M) {
        vector<int> ANS;
        for (Data D : X) {
            ANS.push_back(CA * D.A + CB * D.B + CC * D.C);
        }
        UNIQUE(ANS);
        cout << (ANS.size() == 1 ? ANS[0] : -1) << (i == M - 1 ? '\n' : ' ');
        rep(j,0,T[i].size()) {
            if (T[i][j] == '(') CA++;
            if (T[i][j] == ')') CA--;
            if (T[i][j] == '{') CB++;
            if (T[i][j] == '}') CB--;
            if (T[i][j] == '[') CC++;
            if (T[i][j] == ']') CC--;
        }
    }
}
}
accuracy: 1
time_ms: 90
memory_kb: 3544
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); i++)
#define per(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep2(i, l, r) for (int i = (l); i < (r); i++)
#define per2(i, l, r) for (int i = (r)-1; i >= (l); i--)
#define each(e, v) for (auto &e : v)
#define MM << " " <<
#define pb push_back
#define eb emplace_back
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define sz(x) (int)x.size()
using ll = long long;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;

template <typename T>
using minheap = priority_queue<T, vector<T>, greater<T>>;

template <typename T>
using maxheap = priority_queue<T>;

template <typename T>
bool chmax(T &x, const T &y) {
    return (x < y) ? (x = y, true) : false;
}

template <typename T>
bool chmin(T &x, const T &y) {
    return (x > y) ? (x = y, true) : false;
}

template <typename T>
int flg(T x, int i) {
    return (x >> i) & 1;
}

template <typename T>
void print(const vector<T> &v, T x = 0) {
    int n = v.size();
    for (int i = 0; i < n; i++) cout << v[i] + x << (i == n - 1 ? '\n' : ' ');
    if (v.empty()) cout << '\n';
}

template <typename T>
void printn(const vector<T> &v, T x = 0) {
    int n = v.size();
    for (int i = 0; i < n; i++) cout << v[i] + x << '\n';
}

template <typename T>
int lb(const vector<T> &v, T x) {
    return lower_bound(begin(v), end(v), x) - begin(v);
}

template <typename T>
int ub(const vector<T> &v, T x) {
    return upper_bound(begin(v), end(v), x) - begin(v);
}

template <typename T>
void rearrange(vector<T> &v) {
    sort(begin(v), end(v));
    v.erase(unique(begin(v), end(v)), end(v));
}

template <typename T>
vector<int> id_sort(const vector<T> &v, bool greater = false) {
    int n = v.size();
    vector<int> ret(n);
    iota(begin(ret), end(ret), 0);
    sort(begin(ret), end(ret), [&](int i, int j) { return greater ? v[i] > v[j] : v[i] < v[j]; });
    return ret;
}

template <typename S, typename T>
pair<S, T> operator+(const pair<S, T> &p, const pair<S, T> &q) {
    return make_pair(p.first + q.first, p.second + q.second);
}

template <typename S, typename T>
pair<S, T> operator-(const pair<S, T> &p, const pair<S, T> &q) {
    return make_pair(p.first - q.first, p.second - q.second);
}

template <typename S, typename T>
istream &operator>>(istream &is, pair<S, T> &p) {
    S a;
    T b;
    is >> a >> b;
    p = make_pair(a, b);
    return is;
}

template <typename S, typename T>
ostream &operator<<(ostream &os, const pair<S, T> &p) {
    return os << p.first << ' ' << p.second;
}

struct io_setup {
    io_setup() {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout << fixed << setprecision(15);
    }
} io_setup;

const int inf = (1 << 30) - 1;
const ll INF = (1LL << 60) - 1;
// const int MOD = 1000000007;
const int MOD = 998244353;

void solve() {
    int N, M;
    cin >> N >> M;

    if (N == 0) exit(0);

    vector<string> S(N), T(M);
    rep(i, N) cin >> S[i];
    rep(i, M) cin >> T[i];

    vector<int> indent(N, 0);
    rep(i, N) {
        while (indent[i] < sz(S[i]) && S[i][indent[i]] == '.') indent[i]++;
    }

    vector<tuple<int, int, int>> candi;

    auto check = [&](int r, int c, int s) {
        int sum = 0;
        rep(i, N) {
            if (sum != indent[i]) return false;
            each(e, S[i]) {
                if (e == '(') sum += r;
                if (e == ')') sum -= r;
                if (e == '{') sum += c;
                if (e == '}') sum -= c;
                if (e == '[') sum += s;
                if (e == ']') sum -= s;
            }
        }
        return true;
    };

    rep2(r, 1, 21) rep2(c, 1, 21) rep2(s, 1, 21) {
        if (check(r, c, s)) candi.eb(r, c, s);
    }

    vector<vector<int>> indents(M);
    for (auto [r, c, s] : candi) {
        int sum = 0;
        rep(i, M) {
            indents[i].eb(sum);
            each(e, T[i]) {
                if (e == '(') sum += r;
                if (e == ')') sum -= r;
                if (e == '{') sum += c;
                if (e == '}') sum -= c;
                if (e == '[') sum += s;
                if (e == ']') sum -= s;
            }
        }
    }

    vector<int> ans(M);
    rep(i, M) {
        rearrange(indents[i]);
        if (sz(indents[i]) != 1) {
            ans[i] = -1;
        } else {
            ans[i] = indents[i][0];
        }
    }

    print(ans);
}

int main() {
    while (true) solve();
}
accuracy: 1
time_ms: 90
memory_kb: 3552
final_rank: 13

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

using namespace std;

#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = (n) - 1; i >= 0; --i)

#define all(c) std::begin(c), std::end(c)

#ifdef LOCAL
#define debug(...) debug_impl(#__VA_ARGS__, __VA_ARGS__)
template <class T, class ...Args> void debug_impl(string s, T&& f, Args &&...args) {
    cerr << "(" << s << "): " << "(" << forward<T>(f);
    ((cerr << ", " << forward<Args>(args)), ..., (cerr << ")\n"));
}
#else
#define debug(...) void(0)
#endif

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


template <class T> istream& operator>>(istream& in, vector<T>& v) {
    for (auto& e : v) in >> e;
    return in;
}
template <class ...Args> void read(Args&... args) {
    (cin >> ... >> args);
}

template <class T> ostream& operator>>(ostream& out, const vector<T>& v) {
    int n = v.size();
    rep(i, n) {
        out << v[i];
        if (i + 1 != n) out << ' ';
    }
    return out;
}

template <class T, class ...Tails> void print(T&& h, Tails &&... tails) {
    cout << h, ((cout << ' ' << forward<Tails>(tails)), ..., (cout << '\n'));
}

template <class T> using vc = vector<T>;
template <class T> using vvc = vector<vc<T>>;
#define si(c) (int)(c).size()
#define eb emplace_back

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int p, q;
    while(cin >> p >> q) {
        if(p == 0 and q == 0) break;
        vvc<int> ans(q);
        vc<string> s(p + q); read(s);
        for(int x = 1; x <= 20; ++ x) {
            for(int y = 1; y <= 20; ++ y) {
                for(int z = 1; z <= 20; ++ z) {
                    int cx = 0, cy = 0, cz = 0;
                    bool ok = 1;
                    rep(i, p) {
                        int cnt = 0;
                        while(cnt < (int)s[i].size() and s[i][cnt] == '.') {
                            ++ cnt;
                        }
                        // debug(cnt);
                        if(x * cx + y * cy + z * cz != cnt) {
                            ok = 0;
                        }
                        for(char c: s[i]) {
                            if(c == '(') ++ cx;
                            else if(c == ')') -- cx;

                            if(c == '{') ++ cy;
                            else if(c == '}') -- cy;

                            if(c == '[') ++ cz;
                            else if(c == ']') -- cz;
                        }
                    }
                    cx = 0, cy = 0, cz = 0;
                    rep(j, q) {
                        int i = j + p;
                        // int cnt = 0;
                        // while(cnt < (int)s[i].size() and s[i][cnt] == '.') {
                        //     ++ cnt;
                        // }
                        if(ok) {
                            ans[j].eb(x * cx + y * cy + z * cz);
                        }
                        for(char c: s[i]) {
                            if(c == '(') ++ cx;
                            else if(c == ')') -- cx;

                            if(c == '{') ++ cy;
                            else if(c == '}') -- cy;

                            if(c == '[') ++ cz;
                            else if(c == ']') -- cz;
                        }
                    }
                }
            }
        }
        vc<int> vs;
        rep(i, q) {
            sort(all(ans[i]));
            ans[i].erase(unique(all(ans[i])), ans[i].end());
            // debug(ans[i]);
            int val = (si(ans[i]) == 1 ? ans[i][0] : -1);
            cout << val << " \n"[i == q - 1];
        }
    }
}
accuracy: 1
time_ms: 570
memory_kb: 3540
final_rank: 20

code_snippet: #include<bits/stdc++.h>
#define rep(i,a,...) for(int i = (a)*(strlen(#__VA_ARGS__)!=0);i<(int)(strlen(#__VA_ARGS__)?__VA_ARGS__:(a));++i)
#define per(i,a,...) for(int i = (strlen(#__VA_ARGS__)?__VA_ARGS__:(a))-1;i>=(int)(strlen(#__VA_ARGS__)?(a):0);--i)
#define foreach(i, n) for(auto &i:(n))
#define all(x) (x).begin(), (x).end()
#define bit(x) (1ll << (x))
#define lambda(RES_TYPE, ...) (function<RES_TYPE(__VA_ARGS__)>)[&](__VA_ARGS__) -> RES_TYPE
#define method(FUNC_NAME, RES_TYPE, ...) function<RES_TYPE(__VA_ARGS__)> FUNC_NAME = lambda(RES_TYPE, __VA_ARGS__)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
//const ll MOD = (ll)1e9+7;
const ll MOD = 998244353;
const int INF = (ll)1e9+7;
const ll INFLL = (ll)1e18;
template<class t>
using vvector = vector<vector<t>>;
template<class t>
using vvvector = vector<vector<vector<t>>>;
template<class t>
using priority_queuer = priority_queue<t, vector<t>, greater<t>>;
template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;}
template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;}
#ifdef DEBUG
#define debug(x) cout<<"LINE "<<__LINE__<<": "<<#x<<" = "<<x<<endl;
#else
#define debug(x) (void)0
#endif

namespace templates{
    ll modpow(ll x, ll b,ll mod=MOD){
        ll res = 1;
        while(b){
            if(b&1)res = res * x % mod;
            x = x * x % mod;
            b>>=1;
        }
        return res;
    }

    ll modinv(ll x){
        return modpow(x, MOD-2);
    }

    bool was_output = false;

    void print();
    template <class t> void print(const vector<t> &);
    template <class t, class u> void print(const pair<t, u> &);
    template <class t> void print(const t&);
    template <class Head, class... Tail> void print(const Head&, const Tail&...);

    template <class t> void println(const vector<vector<t>>&);
    template <class t> void println(const vector<t>&);
    template <class t> void println(const t&);
    template <class Head, class... Tail> void println(const Head&, const Tail&...);
    void println();
    void newline();

    void print(){
        return;
    }

    template <class t>
    void print(const vector<t>&x){
        for(const t&i:x)print(i);
    }
    template <class t, class u>
    void print(const pair<t,u>&p){
        print(p.first);
        print(p.second);
    }
    template <class t>
    void print(const t&x){
        if(was_output)cout<<" ";
        cout<<x;
        was_output = true;
    }
    template <class Head, class... Tail>
    void print(const Head&head,const Tail&...tail){
        print(head);
        print(tail...);
    }

    template<class t>
    void println(const vector<vector<t>>&x){
        for(vector<t> i:x)println(i);
    }
    template<class t>
    void println(const vector<t>&x){
        for(const t&i:x)print(i);
        println();
    }
    template <class t>
    void println(const t&x){
        print(x);
        println();
    }
    void println(){
        if(was_output){
            cout << endl;
            was_output = false;
        }
    }
    template <class Head, class... Tail>
    void println(const Head&head,const Tail&...tail){
        print(head);
        println(tail...);
    }

    void newline(){
        was_output = true;
        println();
    }

    template<class t>
    istream& operator>>(istream&is, vector<t>&x){
        for(auto &i:x)is >> i;
        return is;
    }

    template<class t, class u>
    istream& operator>>(istream&is, pair<t, u>&x){
        is >> x.first >> x.second;
        return is;
    }

    template<class t>
    ostream& operator<<(ostream&os, vector<t> &v){
        os << "{";
        for(t &i:v){
            os << i << ", ";
        }
        os << "}";
        return os;
    }

    template<class t = long long>
    t in(){
        t res; cin >> res; return res;
    }

    template<class t>
    vector<t> sorted(vector<t> line,function<bool(t,t)> comp=[](t a,t b){return a<b;}){
        sort(line.begin(),line.end(),comp);
        return line;
    }

    template<class t>
    vector<t> reversed(vector<t> line){
        reverse(line.begin(),line.end());
        return line;
    }
    string reversed(string str){
        reverse(str.begin(),str.end());
        return str;
    }

    long long gcd(long long a,long long b){
        while(b){
            a %= b;
            swap(a,b);
        }
        return a;
    }

    long long lcm(long long a,long long b){
        return a / gcd(a,b) * b;
    }

    class output_initializer{
    public:
        output_initializer(){
            ios::sync_with_stdio(false);
            cin.tie(nullptr);
            cout << setprecision(20);
        }
    };output_initializer OUTPUT_INITIALIZER_INSTANCE = output_initializer();
}

using namespace templates;

vector<int> func(int p,int q){
    {
        string tmp;
        getline(cin,tmp);
    }
    method(readIndent,int,string str){
        rep(i,str.size()){
            if(str[i]!='.')return i;
        }
        return -1;
    };
    method(readLine,string){
        string str;
        getline(cin,str);
        return str;
    };
    using Brackets = array<int,3>;
    method(readBrackets,Brackets,string str){
        Brackets res;
        foreach(i,res)i=0;
        foreach(c,str){
            if(c=='(')++res[0];
            if(c=='{')++res[1];
            if(c=='[')++res[2];
            if(c==')')--res[0];
            if(c=='}')--res[1];
            if(c==']')--res[2];
        }
        return res;
    };
    vector<int> indents(p);
    vector<string> line(p);
    vector<Brackets> shifts(p);
    foreach(i,shifts)foreach(j,i)j=0;
    foreach(i,line)i=readLine();
    set<Brackets> cans;
    rep(i,p){
        indents[i] = readIndent(line[i]);
        if(i){
            rep(j,3)shifts[i][j] += shifts[i-1][j];
            auto add =readBrackets(line[i-1]);
            rep(j,3)shifts[i][j] += add[j];
        }
    }
    method(getCan,set<Brackets>,int indent,Brackets shift){
        set<Brackets> res;
        rep(a,1,21){
            rep(b,1,21){
                rep(c,1,21){
                    if(shift[0] * a + shift[1] * b + shift[2] * c == indent){
                        res.emplace(Brackets({a,b,c}));
                    }
                }
            }
        }
        return res;
    };
    set<Brackets> can = getCan(indents[0],shifts[0]);
    rep(i,1,p){
        auto adds = getCan(indents[i],shifts[i]);
        set<Brackets> next;
        foreach(c,can){
            if(adds.count(c))next.emplace(c);
        }
        swap(can,next);
    }
    vector<int> res;
    Brackets shift;
    foreach(i,shift)i=0;
    rep(_,q){
        string str = readLine();
        set<int> ans;
        foreach(c,can){
            ans.emplace(shift[0] * c[0] + shift[1] * c[1] + shift[2] * c[2]);
        }
        if(ans.size()==1){
            res.emplace_back(*ans.begin());
        }else{
            res.emplace_back(-1);
        }
        auto add = readBrackets(str);
        rep(i,3){
            shift[i] += add[i];
        }
    }
    return res;
}

int main(){
    while(true){
        int p = in();
        int q = in();
        if(p==0)break;
        println(func(p,q));
    }
    return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 4860
final_rank: 19

code_snippet: #include <iostream>
#include <vector>
#include <map>
using namespace std;

int solve(vector<int> &v, map<vector<int>, int> &mp){
    int ans = -1;
    for(int x = 1; x <= 20; x++){
        for(int y = 1; y <= 20; y++){
            for(int z = 1; z <= 20; z++){
                bool g = true;
                for(auto itr = mp.begin(); itr != mp.end(); itr++){
                    if((itr->first)[0] * x + (itr->first)[1] * y + (itr->first)[2] * z != itr->second){
                        g = false;
                    }
                }
                if(g){
                    int s = v[0] * x + v[1] * y + v[2] * z;
                    if(ans == -1) ans = s;
                    else if(ans != s) ans = -2;
                }
            }
        }
    }
    if(ans < 0) ans = -1;
    return ans;
}

int main()
{
    while(true){
        int n, m;
        cin >> n >> m;
        if(n == 0 && m == 0) break;
        string p[12], q[12];
        for(int i = 0; i < n; i++) cin >> p[i];
        for(int i = 0; i < m; i++) cin >> q[i];
        map<vector<int>, int> mp;
        vector<int> r(3);
        for(int i = 0; i < n; i++){
            int l = 0;
            while(p[i][l] == '.') l++;
            mp[r] = l;
            for(int j = l; j < (int)p[i].size(); j++){
                if(p[i][j] == '(') r[0]++;
                if(p[i][j] == ')') r[0]--;
                if(p[i][j] == '[') r[1]++;
                if(p[i][j] == ']') r[1]--;
                if(p[i][j] == '{') r[2]++;
                if(p[i][j] == '}') r[2]--;
            }
        }
        vector<int> v(3);
        for(int i = 0; i < m; i++){
            if(i > 0) cout << " ";
            cout << solve(v, mp);
            for(int j = 0; j < (int)q[i].size(); j++){
                if(q[i][j] == '(') v[0]++;
                if(q[i][j] == ')') v[0]--;
                if(q[i][j] == '[') v[1]++;
                if(q[i][j] == ']') v[1]--;
                if(q[i][j] == '{') v[2]++;
                if(q[i][j] == '}') v[2]--;
            }
        }
        cout << endl;
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3068
final_rank: 1

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
//#include <atcoder/all>
using namespace std;
//using namespace atcoder;
#define DEBUG
#ifdef DEBUG
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for(int i = 0; i < (int)v.size(); i++) {
        if(i) { os << ','; }
        os << v[i];
    }
    os << '}';
    return os;
}
void debugg() { cerr << endl; }
template <class T, class... Args>
void debugg(const T &x, const Args &... args) {
    cerr << " " << x;
    debugg(args...);
}
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = 1<<30;
const ll linf = 1LL<<62;
const int MAX = 4020000;
int dy[8] = {0,1,0,-1,1,-1,-1,1};
int dx[8] = {-1,0,1,0,1,-1,1,-1};
const double pi = acos(-1);
const double eps = 1e-7;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    int sz = a.size();
    for(auto itr = a.begin(); itr != a.end(); itr++){
		cout << *itr;
        sz--;
        if(sz) cout << " ";
	}
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){
	cout << a << " " << b << "\n";
}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << a << " " << b << " " << c << "\n";
}
void mark() {cout << "#" << "\n";}
ll pcount(ll x) {return __builtin_popcountll(x);}
const int mod = 1e9 + 7;
//const int mod = 998244353;

int main(){
    while(1){
        int n,m; cin >> n >> m;
        if(!n) break;
        vector<string> a(n), b(m);
        rep(i,n) cin >> a[i];
        rep(i,m) cin >> b[i];
        vector<int> ans(m,inf);
        bool no = false;
        for(int R=1; R<=20; R++){
            for(int C=1; C<=20; C++){
                for(int S=1; S<=20; S++){
                    int r=0,c=0,s=0;
                    bool f = true;
                    rep(i,n){
                        int cnt = 0;
                        while(cnt < a[i].size() && a[i][cnt] == '.') cnt++;
                        if(cnt != R*r+C*c+S*s) f = false;
                        for(auto j : a[i]){
                            if(j == '(') r++;
                            if(j == ')') r--;
                            if(j == '{') c++;
                            if(j == '}') c--;
                            if(j == '[') s++;
                            if(j == ']') s--;
                        }
                    }
                    if(!f) continue;
                    rep(i,m){
                        int res = R*r + C*c + S*s;
                        if(ans[i] != inf && ans[i] != res){
                            ans[i] = -1;
                        }else if(ans[i] != -1){
                            ans[i] = res;
                        }
                        for(auto j : b[i]){
                            if(j == '(') r++;
                            if(j == ')') r--;
                            if(j == '{') c++;
                            if(j == '}') c--;
                            if(j == '[') s++;
                            if(j == ']') s--;
                        }
                    }
                }
            }
        }
        rep(i,m) cout << ans[i] << " \n"[i==m-1];
    }
}
accuracy: 1
time_ms: 410
memory_kb: 3172
final_rank: 18

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

using ll = long long;

string P[10], Q[10];
int p, q;

bool match(int R, int C, int S) {
    int r = 0, c = 0, s = 0;
    for (int i = 0; i < p; i++) {
        int pos = 0;
        while (pos < P[i].size() && P[i][pos] == '.')
            pos++;
        if (pos != R * r + C * c + S * s) {
            return false;
        }
        while (pos < P[i].size()) {
            if (P[i][pos] == '(')
                r++;
            else if (P[i][pos] == ')')
                r--;
            else if (P[i][pos] == '{')
                c++;
            else if (P[i][pos] == '}')
                c--;
            else if (P[i][pos] == '[')
                s++;
            else if (P[i][pos] == ']')
                s--;
            pos++;
        }
    }
    return true;
}

int main() {
    while (1) {
        cin >> p >> q;
        if (p == 0)
            break;
        getchar();
        for (int i = 0; i < p; i++) {
            getline(cin, P[i]);
        }
        for (int i = 0; i < q; i++) {
            getline(cin, Q[i]);
        }
        int cnt = 0;
        vector<int> R, C, S;
        for (int i = 1; i <= 20; i++) {
            for (int j = 1; j <= 20; j++) {
                for (int k = 1; k <= 20; k++) {
                    if (match(i, j, k)) {
                        R.push_back(i);
                        C.push_back(j);
                        S.push_back(k);
                    }
                }
            }
        }
        vector<int> ans;
        int r = 0, c = 0, s = 0;
        for (int i = 0; i < q; i++) {
            bool ok = 0;
            int indent = -1;
            for (int j = 0; j < R.size(); j++) {
                int x = R[j] * r + C[j] * c + S[j] * s;
                if (indent == -1) {
                    indent = x;
                    ok = 1;
                } else if (indent != x) {
                    ok = 0;
                }
            }
            if (ok)
                ans.push_back(indent);
            else
                ans.push_back(-1);
            int pos = 0;
            while (pos < Q[i].size()) {
                if (Q[i][pos] == '(')
                    r++;
                else if (Q[i][pos] == ')')
                    r--;
                else if (Q[i][pos] == '{')
                    c++;
                else if (Q[i][pos] == '}')
                    c--;
                else if (Q[i][pos] == '[')
                    s++;
                else if (Q[i][pos] == ']')
                    s--;
                pos++;
            }
        }
        cout << ans[0];
        for (int i = 1; i < q; i++)
            cout << " " << ans[i];
        cout << '\n';
    }
}
accuracy: 1
time_ms: 70
memory_kb: 3476
final_rank: 9

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream> // cout, endl, cin
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
#include <iomanip> // setprecision
#include <complex> // complex
#include <math.h> 
#include <functional>
#include <cassert>
using namespace std;
using ll = long long;
using P = pair<int,int>;
constexpr ll INF = 1e18;
constexpr int inf = 1e9;
constexpr ll mod = 1000000007;
constexpr ll mod2 = 998244353;
const int dx[8] = {1, 0, -1, 0,1,1,-1,-1};
const int dy[8] = {0, 1, 0, -1,1,-1,1,-1};
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
// ---------------------------------------------------------------------------

bool solve(){
  int N,M;
  cin >> N >> M;
  if(N==0 && M==0) return false;
  vector<string> GN(N);
  for(int i=0; i<N; i++) cin >> GN[i];
  vector<string> GM(M);
  for(int i=0; i<M; i++) cin >> GM[i]; 
  // (){}[]cnt
  vector<pair<vector<int>,int>> p;
  vector<int> cnt(3,0);
  string in = "({[";
  string out = ")}]";
  for(int i=0; i<N; i++){
    int num = 0;
    for(int j=0; j<GN[i].size(); j++){
      if(GN[i][j] != '.') break;
      num++;
    }
    p.emplace_back(cnt,num);
    for(int j=0; j<GN[i].size(); j++){
      for(int k=0; k<3; k++){
        if(GN[i][j] == in[k]) cnt[k]++;
        if(GN[i][j] == out[k]) cnt[k]--;
      }
    }
  }
  vector<vector<int>> num;
  for(int i=1; i<=20; i++){
    for(int j=1; j<=20; j++){
      for(int k=1; k<=20; k++){
        bool ok = true;
        for(int l=0; l<p.size(); l++){
          vector<int> now;
          int cnt;
          tie(now,cnt) = p[l];
          if(i*now[0]+j*now[1]+k*now[2] != cnt) ok = false;
        }
        if(ok){
          vector<int> pu(3);
          pu[0] = i;
          pu[1] = j;
          pu[2] = k;
          num.emplace_back(pu);
        }
      }
    }
  }
  vector<int> ans(M,-1);
  for(int i=0; i<M; i++){
    set<int> can;
    for(int j=0; j<num.size(); j++){
      int now = 0;
      for(int k=0; k<3; k++){
        now += cnt[k]*num[j][k];
      }
      can.emplace(now);
    }
    if(can.size() == 1) ans[i] = *can.begin();
    for(int j=0; j<GM[i].size(); j++){
      for(int k=0; k<3; k++){
        if(GM[i][j] == in[k]) cnt[k]++;
        if(GM[i][j] == out[k]) cnt[k]--;
      }
    }
  }
  for(int i=0; i<M; i++){
    cout << ans[i] << " \n"[i+1==M];
  }
  return true;
}


int main(){
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  while(solve());
  return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 4116
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define SZ(x) (int)(x.size())
#define REP(i, n) for(int i=0;i<(n);++i)
#define FOR(i, a, b) for(int i=(a);i<(b);++i)
#define RREP(i, n) for(int i=(int)(n)-1;i>=0;--i)
#define RFOR(i, a, b) for(int i=(int)(b)-1;i>=(a);--i)
#define ALL(a) a.begin(),a.end()
#define DUMP(x) cerr<<#x<<" = "<<(x)<<endl
#define DEBUG(x) cerr<<#x<<" = "<<(x)<<" (L"<<__LINE__<<")"<< endl;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using P = pair<int, int>;
const double eps = 1e-8;
const ll MOD = 1000000007;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;
template <typename T1, typename T2>
bool chmax(T1 &a, const T2 &b) {
    if (a < b) { a = b; return true; }
    return false;
}
template <typename T1, typename T2>
bool chmin(T1 &a, const T2 &b) {
    if (a > b) { a = b; return true; }
    return false;
}
template<typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
    os << p.first << ":" << p.second;
    return os;
}
template<typename T1, typename T2>
ostream &operator<<(ostream &os, const map<T1, T2> &mp) {
    os << "{";
    int a = 0;
    for (auto &tp : mp) {
        if (a) os << ", "; a = 1;
        os << tp;
    }
    return os << "}";
}
template<typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
    os << "[";
    REP(i, SZ(v)) {
        if (i) os << ", ";
        os << v[i];
    }
    return os << "]";
}


int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);

    for (;;) {
        int p, q; cin >> p >> q;
        if (p == 0) break;
        vector<map<char,int>> cnt(p);
        vector<int> indent(p);
        map<char,int> count;
        REP(i, p) {
            string s; cin >> s;
            int j = 0;
            while (j < SZ(s) and s[j] == '.') ++j;
            indent[i] = j;
            for (; j < SZ(s); ++j) {
                if (s[j] == '(') ++count['('];
                if (s[j] == ')') --count['('];
                if (s[j] == '{') ++count['{'];
                if (s[j] == '}') --count['{'];
                if (s[j] == '[') ++count['['];
                if (s[j] == ']') --count['['];
            }
            cnt[i] = count;
        }

        vector<tuple<int,int,int>> cands;
        FOR(r, 1, 21) {
            FOR(c, 1, 21) {
                FOR(s, 1, 21) {
                    int valid = 1;
                    REP(i, p-1) {
                        if (r * cnt[i]['('] + c * cnt[i]['{'] + s * cnt[i]['['] != indent[i+1]) valid = 0;
                    }
                    if (valid) {
                        cands.emplace_back(r, c, s);
                    }
                }
            }
        }

        count.clear();
        vi ans(q);
        REP(i, q) {
            string s; cin >> s;
            if (i == q-1) continue;
            for (char c : s) {
                if (c == '(') ++count['('];
                if (c == ')') --count['('];
                if (c == '{') ++count['{'];
                if (c == '}') --count['{'];
                if (c == '[') ++count['['];
                if (c == ']') --count['['];
            }

            map<int,int> value;
            for (auto &tp : cands) {
                int r, c, s; tie(r, c, s) = tp;
                value[r * count['('] + c * count['{'] + s * count['[']] = 1;
            }
            if (value.size() > 1) ans[i+1] = -1;
            else ans[i+1] = value.begin()->first;
        }

        REP(i, q) {
            if (i) cout << " ";
            cout << ans[i];
        }
        cout << endl;

    }

    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3352
final_rank: 5

code_snippet: #include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <tuple>
using namespace std;

int main() {
    int p, q;
    while (cin >> p >> q, p) {
        vector<vector<int>> a(p, vector<int>(3));
        vector<int> b(p);
        {
            map<char, int> cnt;
            for (int i = 0; i < p; i++) {
                a[i][0] = cnt['('] - cnt[')'];
                a[i][1] = cnt['{'] - cnt['}'];
                a[i][2] = cnt['['] - cnt[']'];
                string s; cin >> s;
                int& ind = b[i];
                while (ind < s.size() && s[ind] == '.') ind++;
                for (auto c: s) cnt[c]++;
            }
        }
        set<tuple<int, int, int>> se;
        for (int r = 1; r <= 20; r++) {
            for (int c = 1; c <= 20; c++) {
                for (int s = 1; s <= 20; s++) {
                    bool ok = true;
                    for (int i = 0; i < p; i++) {
                        ok &= a[i][0] * r + a[i][1] * c + a[i][2] * s == b[i];
                    }
                    if (ok) se.emplace(r, c, s);
                }
            }
        }
        vector<int> res(q); {
            map<char, int> cnt;
            for (int i = 0; i < q; i++) {
                set<int> ans;
                for (auto &t: se) {
                    int tmp = 0;
                    tmp += (cnt['('] - cnt[')']) * get<0>(t);
                    tmp += (cnt['{'] - cnt['}']) * get<1>(t);
                    tmp += (cnt['['] - cnt[']']) * get<2>(t);
                    ans.emplace(tmp);
                }
                res[i] = ans.size() == 1 ? *ans.begin() : -1;
                string s; cin >> s;
                for (auto c: s) cnt[c]++;
            }
        }
        for (int i = 0; i < q; i++) cout << res[i] << " \n"[i == q - 1];
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3644
final_rank: 7

code_snippet: #include <bits/stdc++.h>
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define pr(...) cerr<< GET_MACRO(__VA_ARGS__,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__) <<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
#define prArr(a) {cerr<<(#a)<<"={";int i=0;for(auto t:(a))cerr<<(i++?", ":"")<<t;cerr<<"}"<<endl;}
using namespace std;
using Int = long long;
using _int = int;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";}
template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){
  return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;}
template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;}
template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;}
//INSERT ABOVE HERE



void count(Int &a, Int &b, Int &c, char ch){
  if(ch == '(') a++;
  if(ch == ')') a--;
  if(ch == '{') b++;
  if(ch == '}') b--;
  if(ch == '[') c++;
  if(ch == ']') c--;
  assert(a >= 0 && b >= 0 && c >= 0);
}

Int check(vector<string> &code, Int R, Int C, Int S){
  Int a = 0, b = 0, c = 0;
  for(string &s: code){
    Int idx = 0;
    Int cnt = 0;
    while(idx < (Int)s.size() && s[idx] == '.') idx++, cnt++;

    if(R * a + C * b + S * c != cnt) return 0;
    while(idx < (Int)s.size()) count(a, b, c, s[idx++]);
  }
  assert(a == 0 && b == 0 && c == 0);
  return 1;
}

using T = tuple<Int,Int,Int>;
map<T, Int> calcMem(vector<string> &code){
  Int a = 0, b = 0, c = 0;
  map<T, Int> res;
  for(string &s: code){
    Int idx = 0;
    Int cnt = 0;
    while(idx < (Int)s.size() && s[idx] == '.') idx++, cnt++;
    res[T(a, b, c)] = cnt;
    while(idx < (Int)s.size()) count(a, b, c, s[idx++]);
  }
  return res;
}




signed main(){
  srand((unsigned)time(NULL));
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  while(1){
    Int n, m;
    cin>>n>>m;
    if(n == 0 && m == 0) break;
    vector<string> code1(n);
    cin>>code1;
    vector<string> code2(m);
    cin>>code2;

    set<Int> R, C, S;
    for(Int i=1;i<=20;i++)
      for(Int j=1;j<=20;j++)
        for(Int k=1;k<=20;k++){
          if(!check(code1, i, j, k)) continue;
          R.insert(i);
          C.insert(j);
          S.insert(k);
        }

    {
      map<T, Int> mem = calcMem(code1);
      vector<Int> ans;
      Int a = 0, b = 0, c = 0;
      for(string s:code2){
        Int num = 0;
        Int valid = 1;
        if(a != 0){
          valid &= R.size() == 1;
          if(valid) num += *R.begin() * a;
        }
        if(b != 0){
          valid &= C.size() == 1;
          if(valid) num += *C.begin() * b;
        }
        if(c != 0){
          valid &= S.size() == 1;
          if(valid) num += *S.begin() * c;
        }

        if(mem.count(T(a, b, c))) {valid = 1, num = mem[T(a, b, c)];}

        Int idx = 0;
        while(idx < (Int)s.size()) count(a, b, c, s[idx++]);
        if(!valid) ans.push_back(-1);
        else ans.push_back(num);
        }
        cout<<ans<<endl;
      }
    }
    return 0;
}
accuracy: 1
time_ms: 150
memory_kb: 3228
final_rank: 10

code_snippet: #if __has_include("../library/Basic/Debug.hpp")

#include "../library/Basic/Debug.hpp"

#else

/* ----- Header Files ----- */
// IO
#include <cstdio>
#include <iomanip>
#include <ios>
#include <iostream>

// algorithm
#include <algorithm>
#include <cmath>
#include <numeric>

// container
#include <vector>
#include <string>
#include <tuple>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>

// others
#include <random>
#include <limits>
#include <functional>
#include <ctime>
#include <cassert>
#include <cstdint>


/* ----- Type Alias ----- */
using Int = long long int;
using Real = long double;
using String = std::string;
template <class... Ts>
using Tuple = std::tuple<Ts...>;

template <class T>
using Vector = std::vector<T>;
template <class T>
using Queue = std::queue<T>;
template <class T>
using Stack = std::stack<T>;
template <class T>
using Deque = std::deque<T>;

template <class T>
using MaxHeap = std::priority_queue<T>;
template <class T>
using MinHeap = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <class T>
using Set = std::set<T>;
template <class T, class U>
using Map = std::map<T, U>;

template <class T, class... Us>
using Func = std::function<T(Us...)>;

template <class T>
T genv(T v) { return v; }

template <class T, class... Ts>
auto genv(size_t l, Ts... ts) {
    return Vector<decltype(genv<T>(ts...))>(l, Vector<T>(ts...));
}

template <class Cost = Int>
struct Edge {
    Int src, dst;
    Cost cost;
    Edge(Int src = -1, Int dst = -1, Cost cost = 1)
        : src(src), dst(dst), cost(cost){};

    bool operator<(const Edge<Cost>& e) const { return this->cost < e.cost; }
    bool operator>(const Edge<Cost>& e) const { return this->cost > e.cost; }
};

template <class Cost = Int>
using Edges = Vector<Edge<Cost>>;
template <class Cost = Int>
using Graph = Vector<Vector<Edge<Cost>>>;

#endif

/* ----- Misc ----- */
void fastio() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
}

struct Fout {
    Int precision;
    Fout(Int precision) : precision(precision) {}
};
std::ostream& operator<<(std::ostream& os, const Fout& fio) {
    os << std::fixed << std::setprecision(fio.precision);
    return os;
}


/* ----- Constants ----- */
// constexpr Int INF = std::numeric_limits<Int>::max() / 1000;
// constexpr Int MOD = 1000000007;
// constexpr Real PI = acos(-1);
// constexpr Real EPS = 1e-10;
// std::mt19937 mt(int(std::time(nullptr)));

Int parse(const String& s, Vector<Int>& cnt) {
    Int i;
    for (i = 0; s[i] == '.'; ++i) {}

    for (char c : s) {
        switch (c) {
            case '(':
                ++cnt[0];
                break;
            case ')':
                --cnt[0];
                break;
            case '{':
                ++cnt[1];
                break;
            case '}':
                --cnt[1];
                break;
            case '[':
                ++cnt[2];
                break;
            case ']':
                --cnt[2];
                break;
            default:
                break;
        }
    }
    return i;
}

bool solve() {
    Int n, m;
    std::cin >> n >> m;
    if (n == 0) return false;

    Vector<Tuple<Vector<Int>, Int>> lines(n);
    Vector<Int> cnt(3, 0);
    for (auto& l : lines) {
        String s;
        std::cin >> s;

        Vector<Int> prev = cnt;
        Int dots = parse(s, cnt);
        l = std::make_tuple(prev, dots);
    }

    Vector<Vector<Int>> pos;
    Vector<Int> x(3);
    for (x[0] = 1; x[0] <= 20; ++x[0]) {
        for (x[1] = 1; x[1] <= 20; ++x[1]) {
            for (x[2] = 1; x[2] <= 20; ++x[2]) {
                bool judge = true;

                for (auto l : lines) {
                    Vector<Int> v;
                    Int s;
                    std::tie(v, s) = l;

                    for (Int i = 0; i < 3; ++i) s -= v[i] * x[i];
                    if (s != 0) judge = false;
                }

                if (judge) pos.push_back(x);
            }
        }
    }

    fill(cnt.begin(), cnt.end(), 0);
    for (Int i = 0; i < m; ++i) {
        String s;
        std::cin >> s;

        Vector<Int> prev = cnt;
        parse(s, cnt);

        Set<Int> ans;
        for (const auto& x : pos) {
            Int sum = 0;
            for (Int i = 0; i < 3; ++i) sum += x[i] * prev[i];
            ans.insert(sum);
        }

        std::cout << (ans.size() == 1 ? *ans.begin() : -1) << " \n"[i == m - 1];
    }
    return true;
}

int main() {
    while (solve()) {}
    return 0;
}
accuracy: 1
time_ms: 120
memory_kb: 3392
final_rank: 11

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

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;

#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e16;
const ll MOD = 1e9 + 7;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,N) for(int i=0;i<(N);i++)
#define ALL(s) (s).begin(),(s).end()
#define EQ(a,b) (abs((a)-(b))<EPS)
#define EQV(a,b) ( EQ((a).real(), (b).real()) && EQ((a).imag(), (b).imag()) )
#define fi first
#define se second
#define N_SIZE (1LL << 20)
#define NIL -1

ll mod_add(ll a, ll b) { return (a + b) % MOD; }
ll mod_sub(ll a, ll b) { return (a - b + MOD) % MOD; }
ll mod_mul(ll a, ll b) { return a*b % MOD; }

ll p,q;

vector<string> PP,Q;
vector<ll> ans;

char ot[] = {'(','{','['};
char ct[] = {')','}',']'};

bool check(ll r,ll c,ll s){
    ll cost[] = {r,c,s};
    ll sum = 0;
    rep(i,PP.size() - 1){
        ll cnt = 0;
        rep(j,PP[i].size()){
            rep(k,3){
                if(ot[k] == PP[i][j])sum += cost[k];
                if(ct[k] == PP[i][j])sum -= cost[k];
            }
        }

        rep(j,PP[i+1].size()){
            if(PP[i+1][j] != '.')break;
            cnt++;
        }
        if(cnt != sum)return false;
    }
    return true;
}

void solve(ll r,ll c,ll s){
    ll cnt[3] = {}; 
    rep(i,Q.size() - 1){
        rep(j,Q[i].size()){
            rep(k,3){
                if(ot[k] == Q[i][j])cnt[k]++;
                if(ct[k] == Q[i][j])cnt[k]--;
            }
        }
        ll nn = cnt[0]*r + cnt[1]*c + cnt[2]*s;
        if(ans[i] == 0)ans[i] = nn;
        else if(ans[i] != nn)ans[i] = -1;
    }
}

int main(){
    while(cin >> p >> q && p){
        PP.clear();
        Q.clear();
        ans.clear();
        ans.resize(q-1,0);
        rep(i,p){
            string s;
            cin >> s;
            PP.push_back(s);
        }
        rep(i,q){
            string s;
            cin >> s;
            Q.push_back(s);
        }
        FOR(r,1,21){
            FOR(c,1,21){
                FOR(s,1,21){
                    if(check(r,c,s)){
                        // cout << r << " " << c << " " << s << endl;
                        solve(r,c,s);
                    }
                }
            }
        }
        cout << 0 << " ";
        rep(i,ans.size()){
            if(i != ans.size() - 1)cout << ans[i] << " ";
            else cout << ans[i] << endl;
        }
    }
}
accuracy: 1
time_ms: 300
memory_kb: 3140
final_rank: 15

code_snippet: #include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
using ll = long long;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;

int a[100][100][100];

void solve(int n,int m){
    map<int,int> mp;
    int x=0,y=0,z=0;
    rep(i,n){
        string s;cin>>s;
        int c=0;
        while(c<s.size()&&s[c]=='.')++c;
        mp[10000*x+100*y+z]=c;
        rep(j,s.size()){
            if(s[j]=='(')++x;
            if(s[j]==')')--x;
            if(s[j]=='{')++y;
            if(s[j]=='}')--y;
            if(s[j]=='[')++z;
            if(s[j]==']')--z;
        }
    }
    vector<int> P,Q,R;
    REP(i,1,21)REP(j,1,21)REP(k,1,21){
        bool ok=true;
        for(auto p : mp){
            if(i*(p.first/10000)+j*(p.first/100%100)+k*(p.first%100)!=p.second)ok=false;
        }
        if(ok){
            P.push_back(i);
            Q.push_back(j);
            R.push_back(k);
        }
    }
    x=0,y=0,z=0;
    rep(i,m){
        string s;
        cin>>s;
        if(mp.count(10000*x+100*y+z))cout<<mp[10000*x+100*y+z];
        else {
            set<int> st;
            rep(j,P.size()){
                st.insert(x*P[j]+y*Q[j]+z*R[j]);
            }
            if(st.size()==1)cout<<*st.begin();
            else cout<<-1;
        }
        rep(j,s.size()){
            if(s[j]=='(')++x;
            if(s[j]==')')--x;
            if(s[j]=='{')++y;
            if(s[j]=='}')--y;
            if(s[j]=='[')++z;
            if(s[j]==']')--z;
        }
        if(i!=m-1)cout<<" ";
        else cout<<endl;
    }
}
int main(){
    int n,m;
    while(cin>>n>>m,n)solve(n,m);
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3344
final_rank: 4

code_snippet: #include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>

static const int MOD = 1000000007;
using ll = long long;
using u32 = uint32_t;
using namespace std;

template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;
void solve(int p, int q){
    vector<string> v(p), u(q);
    for (auto &&i : v) cin >> i;
    for (auto &&i : u) cin >> i;
    vector<int> ans(q, -2);
    for (int R = 1; R <= 20; ++R) {
        for (int C = 1; C <= 20; ++C) {
            for (int S = 1; S <= 20; ++S) {
                int cnt1 = 0, cnt2 = 0, cnt3 = 0;
                int ok = 1;
                for (int i = 0; i < p; ++i) {
                    int x = 0;
                    for (auto &&j : v[i]) {
                        if(j == '.') x++;
                        else break;
                    }
                    if(x != R*cnt1+C*cnt2+S*cnt3){
                        ok = 0;
                        break;
                    }
                    for (auto &&j : v[i]) {
                        if(j == '(') cnt1++;
                        if(j == ')') cnt1--;
                        if(j == '{') cnt2++;
                        if(j == '}') cnt2--;
                        if(j == '[') cnt3++;
                        if(j == ']') cnt3--;
                    }
                }
                if(!ok) continue;
                for (int i = 0; i < q; ++i) {
                    if(ans[i] == -2){
                        ans[i] = R*cnt1+C*cnt2+S*cnt3;
                    } else if(ans[i] != R*cnt1+C*cnt2+S*cnt3){
                        ans[i] = -1;
                    }
                    for (auto &&j : u[i]) {
                        if(j == '(') cnt1++;
                        if(j == ')') cnt1--;
                        if(j == '{') cnt2++;
                        if(j == '}') cnt2--;
                        if(j == '[') cnt3++;
                        if(j == ']') cnt3--;
                    }
                }
            }
        }
    }
    for (int i = 0; i < q; ++i) {
        if(i) printf(" ");
        printf("%d", ans[i]);
    }
    puts("");
}
int main() {
    int p, q;
    while(cin >> p >> q, p){
        solve(p, q);
    }
    return 0;
}
accuracy: 1
time_ms: 150
memory_kb: 3180
final_rank: 8

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n,m;
string ss[10];
main()
{
	while(cin>>n>>m,n)
	{
		for(int i=0;i<n;i++)cin>>ss[i];
		vector<int>R,C,S;
		for(int r=1;r<21;r++)for(int c=1;c<21;c++)for(int s=1;s<21;s++)
		{
			bool flag=1;
			int cr=0,cc=0,cs=0;
			for(int i=0;i<n;i++)
			{
				int cnt=0;
				for(int j=0;j<ss[i].size()&&ss[i][j]=='.';j++)cnt++;
				if(cr*r+cc*c+cs*s!=cnt)
				{
					flag=0;
					break;
				}
				for(int j=0;j<ss[i].size();j++)
				{
					if(ss[i][j]=='(')cr++;
					else if(ss[i][j]==')')cr--;
					else if(ss[i][j]=='{')cc++;
					else if(ss[i][j]=='}')cc--;
					else if(ss[i][j]=='[')cs++;
					else if(ss[i][j]==']')cs--;
				}
			}
			if(flag)
			{
				R.push_back(r);
				C.push_back(c);
				S.push_back(s);
			}
		}
		vector<int>ans;
		int cr=0,cc=0,cs=0;
		for(;m--;)
		{
			string t;cin>>t;
			int cnt=-1;
			for(int j=0;j<R.size();j++)
			{
				int now=cr*R[j]+cc*C[j]+cs*S[j];
				if(cnt<0)cnt=now;
				else
				{
					if(cnt!=now)cnt=114514;
				}
			}
			if(cnt==114514)ans.push_back(-1);
			else ans.push_back(cnt);
			for(int j=0;j<t.size();j++)
			{
				if(t[j]=='(')cr++;
				else if(t[j]==')')cr--;
				else if(t[j]=='{')cc++;
				else if(t[j]=='}')cc--;
				else if(t[j]=='[')cs++;
				else if(t[j]==']')cs--;
			}
		}
		for(int i=0;i<ans.size();i++)cout<<ans[i]<<(i+1==ans.size()?"\n":" ");
	}
}
accuracy: 1
time_ms: 90
memory_kb: 3284
final_rank: 6

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

void solve(int p,int q){
    cin.ignore();
    string buf;
    int ro=0,rc=0,co=0,cc=0,so=0,sc=0;
    auto incl=[&](string str){
        ro+=count(str.begin(),str.end(),'(');
        rc+=count(str.begin(),str.end(),')');
        co+=count(str.begin(),str.end(),'{');
        cc+=count(str.begin(),str.end(),'}');
        so+=count(str.begin(),str.end(),'[');
        sc+=count(str.begin(),str.end(),']');
    };
    auto cntIndent=[](string str){
        int res=0;
        for(int i=0;i<str.size();i++){
            if(str[i]!='.') break;
            res++;
        }
        return res;
    };
    vector<tuple<int,int,int>> rcs;
    for(int i=0;i<20;i++){
        for(int j=0;j<20;j++){
            for(int k=0;k<20;k++){
                rcs.push_back(make_tuple(i+1,j+1,k+1));
            }
        }
    }
    for(int i=0;i<p;i++){
        string str;
        getline(cin,str);
        vector<tuple<int,int,int>> tmp;
        int x=cntIndent(str);
        for(int i=0;i<rcs.size();i++){
            if(get<0>(rcs[i])*(ro-rc)+get<1>(rcs[i])*(co-cc)+get<2>(rcs[i])*(so-sc)==x){
                tmp.push_back(rcs[i]);
            }
        }
        rcs=tmp;
        incl(str);
    }
    ro=rc=0,co=cc=0,so=sc=0;
    vector<int> res;
    for(int i=0;i<q;i++){
        string str;
        getline(cin,str);
        int y=get<0>(rcs[0])*(ro-rc)+get<1>(rcs[0])*(co-cc)+get<2>(rcs[0])*(so-sc);
        for(int i=0;i<rcs.size();i++){
            if(get<0>(rcs[i])*(ro-rc)+get<1>(rcs[i])*(co-cc)+get<2>(rcs[i])*(so-sc)!=y){
                y=-1;
            }
        }
        res.push_back(y);
        incl(str);
    }
    for(int i=0;i<q;i++){
        cout<<res[i]<<(i+1==q ? "\n" : " ");
    }
    return;
}
int main(){
    int p,q;
    while(cin>>p>>q,p){
        solve(p,q);
    }
    return 0;    
}
accuracy: 1
time_ms: 10
memory_kb: 3228
final_rank: 2

code_snippet: #include<bits/stdc++.h>
using namespace std;
int main(){
  int n,m;
  while(cin>>n>>m,n){
  string s1[11],s2[11];
  for(int i=0;i<n;i++)cin>>s1[i];
  for(int i=0;i<m;i++)cin>>s2[i];

  int pi[11];
  for(int i=0;i<n;i++){
    int j=0;
    while(s1[i][j]=='.'){
      j++;
    }
    pi[i]=j;
  }

  // for(int i=0;i<n;i++)cout<<"p "<<pi[i]<<endl;
  
  int ans[11];
  fill_n(ans,11,-2);
  ans[0]=0;
  
  for(int r=1;r<=20;r++){
    for(int c=1;c<=20;c++){
      for(int s=1;s<=20;s++){
	//cout<<r<<" "<<c<<" "<<s<<endl;
	int f=1;
	
	int cnt[3]={};
	for(int i=0;i<n;i++){
	    
	  int t=r*cnt[0]+c*cnt[1]+s*cnt[2];
	  //if(r==9&&c==5&&s==2)cout<<pi[i]<<" "<<t<<endl;
	  if(t!=pi[i])f=0;
	    
	  for(int j=0;j<s1[i].size();j++){
	    if(s1[i][j]=='(')cnt[0]++;
	    if(s1[i][j]==')')cnt[0]--;
	    if(s1[i][j]=='{')cnt[1]++;
	    if(s1[i][j]=='}')cnt[1]--;
	    if(s1[i][j]=='[')cnt[2]++;
	    if(s1[i][j]==']')cnt[2]--;
	  }
	}
	
	if(f==0)continue;
	//cout<<r<<" "<<c<<" "<<s<<endl;
	
	cnt[0]=cnt[1]=cnt[2]=0;
	for(int i=0;i<m;i++){
	    
	  int t=r*cnt[0]+c*cnt[1]+s*cnt[2];
	    
	  if(ans[i]==-2)ans[i]=t;
	  else if(ans[i]!=t)ans[i]=-1;
	    
	  for(int j=0;j<s2[i].size();j++){
	    if(s2[i][j]=='(')cnt[0]++;
	    if(s2[i][j]==')')cnt[0]--;
	    if(s2[i][j]=='{')cnt[1]++;
	    if(s2[i][j]=='}')cnt[1]--;
	    if(s2[i][j]=='[')cnt[2]++;
	    if(s2[i][j]==']')cnt[2]--;
	  }
	}
	
      }
    }
  }
  for(int i=0;i<m;i++){
    if(i)cout<<" ";
    cout<<ans[i];
  }

  cout<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 290
memory_kb: 2996
final_rank: 14

code_snippet: #include <iostream>
#include <string>
#include <tuple>
#include <unordered_set>
#include <utility>
#include <vector>

using namespace std;

int main()
{
    while (true) {
        int p, q;
        cin >> p >> q;
        if (p == 0 && q == 0) {
            return 0;
        }

        vector<string> P;
        for (int i = 0; i < p; ++i) {
            string a;
            cin >> a;
            P.push_back(a);
        }

        auto processLine = [](const string& line) {
            auto aoi = 0;
            auto groupingNotFound = true;
            auto cr = make_pair(0, 0);
            auto cc = make_pair(0, 0);
            auto cs = make_pair(0, 0);
            for (char i : line) {
                if (groupingNotFound && i == '.') {
                    aoi += 1;
                }
                else {
                    groupingNotFound = false;
                    if (i == '(')
                        cr.first += 1;
                    else if (i == ')') {
                        cr.second += 1;
                    }
                    else if (i == '{') {
                        cc.first += 1;
                    }
                    else if (i == '}') {
                        cc.second += 1;
                    }
                    else if (i == '[') {
                        cs.first += 1;
                    }
                    else if (i == ']') {
                        cs.second += 1;
                    }
                }
            }
            return make_tuple(aoi, cr, cc, cs);
        };
        auto computeAoi = [](const tuple<int, int, int>& param,
                             const pair<int, int>& r, const pair<int, int>& c,
                             const pair<int, int>& s) {
            int R, C, S;
            tie(R, C, S) = param;
            return R * (r.first - r.second) + C * (c.first - c.second) +
                   S * (s.first - s.second);
        };
        auto addPair = [](auto& a, const auto& b) {
            a.first += b.first;
            a.second += b.second;
        };

        auto candidates = [processLine, computeAoi,
                           addPair](const vector<string>& v) {
            auto r = make_pair(0, 0);
            auto c = make_pair(0, 0);
            auto s = make_pair(0, 0);
            vector<tuple<int, int, int>> remainCandidates;
            for (int R = 1; R <= 20; ++R) {
                for (int C = 1; C <= 20; ++C) {
                    for (int S = 1; S <= 20; ++S) {
                        remainCandidates.emplace_back(R, C, S);
                    }
                }
            }
            for (auto&& line : v) {
                int aoi;
                pair<int, int> cr, cc, cs;
                tie(aoi, cr, cc, cs) = processLine(line);

                vector<tuple<int, int, int>> temp;
                for (auto&& j : remainCandidates) {
                    if (computeAoi(j, r, c, s) == aoi) {
                        temp.push_back(move(j));
                    }
                }
                swap(remainCandidates, temp);
                addPair(r, cr);
                addPair(c, cc);
                addPair(s, cs);
            }
            return remainCandidates;
        };
        const auto candidates_ = candidates(P);
        auto normalize = [](const vector<tuple<int, int, int>>& v) {
            tuple<unordered_set<int>, unordered_set<int>, unordered_set<int>> n;
            unordered_set<int> r, c, s;
            tie(r, c, s) = n;
            for (auto&& i : v) {
                int rr, cc, ss;
                tie(rr, cc, ss) = i;
                r.insert(rr);
                c.insert(cc);
                s.insert(ss);
            }
            return n;
        };
        const auto nn = normalize(candidates_);

        vector<string> Q;
        for (int i = 0; i < q; ++i) {
            string a;
            cin >> a;
            Q.push_back(a);
        }

        auto computeAoiByCandidates = [&candidates_,
                                       computeAoi](const pair<int, int>& r,
                                                   const pair<int, int>& c,
                                                   const pair<int, int>& s) {
            bool first = true;
            int current = -1;
            for (auto&& candidate : candidates_) {
                if (first) {
                    current = computeAoi(candidate, r, c, s);
                    first = false;
                }
                else {
                    auto r_ = computeAoi(candidate, r, c, s);
                    if (r_ != current) {
                        return -1;
                    }
                    else {
                        current = r_;
                    }
                }
            }
            return current;
        };

        auto r = make_pair(0, 0);
        auto c = make_pair(0, 0);
        auto s = make_pair(0, 0);
        vector<int> results;
        for (auto&& line : Q) {
            int aoi;
            pair<int, int> cr, cc, cs;
            tie(aoi, cr, cc, cs) = processLine(line);
            results.push_back(computeAoiByCandidates(r, c, s));
            addPair(r, cr);
            addPair(c, cc);
            addPair(s, cs);
        }
        for (size_t i = 0; i < results.size(); ++i) {
            cout << results[i];
            if (i == results.size() - 1) {
                cout << endl;
            }
            else {
                cout << " ";
            }
        }
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3284
final_rank: 3

code_snippet: #include "bits/stdc++.h"

#define REP(i,n) for(ll i=0;i<ll(n);++i)
#define RREP(i,n) for(ll i=ll(n)-1;i>=0;--i)
#define FOR(i,m,n) for(ll i=m;i<ll(n);++i)
#define RFOR(i,m,n) for(ll i=ll(n)-1;i>=ll(m);--i)
#define ALL(v) (v).begin(),(v).end()
#define UNIQUE(v) v.erase(unique(ALL(v)),v.end());
#define DUMP(v) REP(aa, (v).size()) { cout << v[aa]; if (aa != v.size() - 1)cout << " "; else cout << endl; }
#define INF 1000000001ll
#define MOD 1000000007ll
#define EPS 1e-9

const int dx[8] = { 1,1,0,-1,-1,-1,0,1 };
const int dy[8] = { 0,1,1,1,0,-1,-1,-1 };


using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
ll max(ll a, int b) { return max(a, ll(b)); }
ll max(int a, ll b) { return max(ll(a), b); }
ll min(ll a, int b) { return min(a, ll(b)); }
ll min(int a, ll b) { return min(ll(a), b); }


int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	int n, m;
	while (cin >> n >> m, n) {
		vector<string> p(n), q(m);
		REP(i, n)cin >> p[i];
		REP(i, m)cin >> q[i];
		vi ind(n);
		REP(i, n) {
			int cnt = 0;
			REP(j, p[i].size()) {
				if (p[i][j] != '.')break;
				cnt++;
			}
			ind[i] = cnt;
		}
		vi res(m, -1);
		REP(i, 20)REP(j, 20)REP(k, 20) {
			int r = 0, c = 0, s = 0;
			bool ok = true;
			REP(a, n) {
				if (ind[a] != (i + 1)*r + (j + 1)*c + (k + 1)*s)ok = false;
				REP(b, p[a].size()) {
					if (p[a][b] == '(')r++;
					else if (p[a][b] == ')')r--;
					else if (p[a][b] == '{')c++;
					else if (p[a][b] == '}')c--;
					else if (p[a][b] == '[')s++;
					else if (p[a][b] == ']')s--;
				}

			}
			if (!ok)continue;
			r = 0, c = 0, s = 0;
		
			REP(a, m) {
				if(res[a]==-1)res[a] = (i + 1)*r + (j + 1)*c + (k + 1)*s;
				else if(res[a]!=(i + 1)*r + (j + 1)*c + (k + 1)*s)res[a] = INF;
				REP(b, q[a].size()) {
					if (q[a][b] == '(')r++;
					else if (q[a][b] == ')')r--;
					else if (q[a][b] == '{')c++;
					else if (q[a][b] == '}')c--;
					else if (q[a][b] == '[')s++;
					else if (q[a][b] == ']')s--;
				}
			}

		}
		REP(i, m) {
			if (i)cout << " ";
			if (res[i] == INF)cout << -1;
			else cout << res[i];
		}
		cout << endl;
	}
}
accuracy: 1
time_ms: 360
memory_kb: 3140
final_rank: 17