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
#include <bits/stdc++.h>

using namespace std;

struct ins{
	char type;
	long long c;
};

int n;

const long long  M = 1000000000000000;

vector < int > v;

vector < vector < ins > > programs;
vector < int > used;
vector < long long > y;
long long x;

long long ans;

void check(){
	x = 0;
	y.clear();
	y.resize(n);
	used.clear();
	used.resize(n);


	for(int i : v){
		ins cur = programs[i][used[i]];
		if(cur.type == 'W'){
			y[i] = x;
		}
		if(cur.type == 'Z'){
			x = y[i];
		}
		if(cur.type == '+'){
			y[i] += cur.c;
		}
		if(cur.type == '-'){
			y[i] -= cur.c;
		}
		used[i]++;
	}



	ans = min(ans, x);
}

int main(){
	int t;
	cin >> t;
	while(t--){
		ans = M;
		v.clear();
		used.clear();
		x = 0;
		y.clear();

		cin >> n;
		used.resize(n);	
		programs.resize(n);
		y.resize(n);

		for (int i = 0; i < n; ++i)
		{
			//cout << "i = " << i << endl;
			int l;
			cin >> l;
			programs[i].resize(l);
			for (int k = 0; k < l; ++k)
			{
				v.push_back(i);
				// tutaj wczytanie programu
				char a;
				cin >> a;
				ins ins1;
				if(a == 'W'){
					ins1.type = 'W';
				}
				if(a == 'Z'){
					ins1.type = 'Z';
				}
				if(a == '+'){
					ins1.type = '+';
					cin >> ins1.c;
				}
				if(a == '-'){
					ins1.type = '-';
					cin >> ins1.c;
				}
				programs[i][k] = ins1;
			}
		}

		
		check();
		//return 0;
		while(next_permutation(v.begin(), v.end())){
			check();
		}
		check();

		cout << ans << endl;
	}
}