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
// Marcin Knapik

// Potyczki algorytmiczne - runda 5. zadanie A2

#pragma GCC optimize "O3"
#include<bits/stdc++.h>
using namespace std;

#define f first
#define s second
#define sz(s) (int)s.size()
#define all(s) s.begin(), s.end()
#define pb push_back
#define mp make_pair

#define ii pair<int, int>
#define ll long long
#define vi vector<int>
#define vii vector<ii>
#define vvi vector<vi>

const int INF = 1e9 + 7;

ll symulate(vi & perm, vvi & op){
    vi cnt(sz(op));
    vector<ll> y(sz(op));
    ll x = 0;

    for(auto & u : perm){
        int teraz = op[u][cnt[u]++];
        if(teraz == INF)
            x = y[u];
        else if(teraz == -INF)
            y[u] = x;
        else
            y[u] += teraz;
    }
    return x;
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t;

    for(int test = 1; test <= t; test++){
        int n; cin >> n;
        vvi op(n);

        vi perm;
        for(int i = 0; i < n; i++){
            int m;
            cin >> m;
            for(int j = 0; j < m; j++){
                char c;
                cin >> c;

                if(c == 'Z')
                    op[i].pb(INF);
                else if(c == 'W')
                    op[i].pb(-INF);
                else{
                    int ile;cin >> ile;
                    op[i].pb(ile * (c == '+' ? 1 : -1));
                }
            }
            while(sz(op[i]) and op[i].back() != INF)
                op[i].pop_back(); 
            for(int j = 0; j < sz(op[i]); j++)
                perm.pb(i);
        }

        ll ans = 1ll * INF * INF;

        do{
            ans = min(ans, symulate(perm, op));
        }while(next_permutation(all(perm)));
        cout << ans << '\n';
    }
}