1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <bits/stdc++.h>


using namespace std;


const long long INF = 1LL << 60;


map <pair<vector<long long>,vector <int>>, long long> cache;


long long backtrack(const vector <long long> &local, const vector <vector<pair<int,int>>> &prog) {
    vector <int> lens(prog.size());
    for (int i = 0; i < (int) prog.size(); i++) {
        lens[i] = prog[i].size();
    }

    auto sig = make_pair(local, lens);

    auto it = cache.find(sig);
    if (it != cache.end()) {
        return it->second;
    }

    long long ans = INF;

    for (int i = 0; i < (int) prog.size(); i++) if (!prog[i].empty()) {
        auto progNew = prog;

        auto op = progNew[i].back();
        progNew[i].pop_back();

        auto localNew = local;

        long long chg = 0;

        if (op.first == -1) {
            localNew[i] = 0;
        } else if (op.first == 1) {
            chg = localNew[i];

            for (long long &x : localNew) {
                x -= chg;
            }
        } else {
            localNew[i] += op.second;
        }

        ans = min(ans, chg + backtrack(localNew, progNew));
    }

    if (ans == INF) {
        ans = 0;
    }

    cache[sig] = ans;
    return ans;
}


long long solve(int n, vector <vector<pair<int,int>>> prog) {
    cache.clear();

    for (auto &p : prog) {
        reverse(p.begin(), p.end());
    }

    return backtrack(vector <long long> (n, 0), prog);
}


int main() {
    ios_base::sync_with_stdio(false);

    int t;
    cin >> t;

    while (t--) {
        int n;
        cin >> n;

        vector <vector<pair<int,int>>> prog(n);
        for (auto &p : prog) {
            int len;
            cin >> len;

            while (p.size() < len) {
                string s;
                cin >> s;

                if (s == "+" || s == "-") {
                    int val;
                    cin >> val;

                    if (s == "-") {
                        val *= -1;
                    }

                    p.push_back({0, val});
                } else if (s == "W") {
                    p.push_back({-1, 0});
                } else {
                    p.push_back({1, 0});
                }
            }
        }

        cout << solve(n, prog) << '\n';
    }

    return 0;
}