#pragma GCC optimize ("O3") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; const int INF = 0x3f3f3f3f; #define FOR(i,b,e) for(int i = (b); i < (e); i++) #define TRAV(x,a) for(auto &x: (a)) #define SZ(x) ((int)x.size()) #define PB push_back #define X first #define Y second int n; ll ans; void reku(vector<vi> op, vector<ll> vals){ bool cos = 0; FOR(i, 0, SZ(op)){ if(!SZ(op[i])) continue; cos = 1; vector<vi> nop = op; vector<ll> nvals = vals; if(nop[i].back() == INF) nvals[i] = nvals[n]; else if(nop[i].back() == -INF) nvals[n] = nvals[i]; else nvals[i] += nop[i].back(); nop[i].pop_back(); reku(nop, nvals); } if(!cos) ans = min(ans, vals[n]); } void solve(){ cin >> n; ans = 1ll*INF*INF; vector<vi> op(n); vector<ll> vals(n+1); FOR(i, 0, n){ int dl; cin >> dl; FOR(j, 0, dl){ int a = INF; char c; cin >> c; if(c == '+' || c == '-') cin >> a; if(c == 'Z' || c == '-') a *= -1; op[i].PB(a); } reverse(op[i].begin(), op[i].end()); } reku(op, vals); cout << ans << '\n'; } int main(){ ios::sync_with_stdio(0); cin.tie(0); int tt; cin >> tt; FOR(te, 0, tt) solve(); return 0; }
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 | #pragma GCC optimize ("O3") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; const int INF = 0x3f3f3f3f; #define FOR(i,b,e) for(int i = (b); i < (e); i++) #define TRAV(x,a) for(auto &x: (a)) #define SZ(x) ((int)x.size()) #define PB push_back #define X first #define Y second int n; ll ans; void reku(vector<vi> op, vector<ll> vals){ bool cos = 0; FOR(i, 0, SZ(op)){ if(!SZ(op[i])) continue; cos = 1; vector<vi> nop = op; vector<ll> nvals = vals; if(nop[i].back() == INF) nvals[i] = nvals[n]; else if(nop[i].back() == -INF) nvals[n] = nvals[i]; else nvals[i] += nop[i].back(); nop[i].pop_back(); reku(nop, nvals); } if(!cos) ans = min(ans, vals[n]); } void solve(){ cin >> n; ans = 1ll*INF*INF; vector<vi> op(n); vector<ll> vals(n+1); FOR(i, 0, n){ int dl; cin >> dl; FOR(j, 0, dl){ int a = INF; char c; cin >> c; if(c == '+' || c == '-') cin >> a; if(c == 'Z' || c == '-') a *= -1; op[i].PB(a); } reverse(op[i].begin(), op[i].end()); } reku(op, vals); cout << ans << '\n'; } int main(){ ios::sync_with_stdio(0); cin.tie(0); int tt; cin >> tt; FOR(te, 0, tt) solve(); return 0; } |