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

using namespace std;

int n, m, len;
long long odp, s;
int z[100001];
int zl[100001];
long long w[100001];
vector <int> t;
vector <pair <int, long long> > v[100001];

void xd(int p)
{
	if(p==len+1)
	{
		for(int i=1; i<=n; ++i)
		{
			z[i]=-1;
			w[i]=0;
		}
		s=0;
		for(int i=1; i<=len; ++i)
		{
			int x=t[i];
			++z[x];
			int y=z[x];
			if(v[x][y].first)
			{
				w[x]+=v[x][y].second;
				s=w[x];
			}
			else
			{
				w[x]=s;
			}
		}
		odp=min(odp, s);
		return;
	}
	for(int i=1; i<=n; ++i)
	{
		if(zl[i]<(int)v[i].size())
		{
			++zl[i];
			t[p]=i;
			xd(p+1);
			--zl[i];
		}
	}
}

void solve()
{
	len=0;
	cin>>n;
	for(int i=1; i<=n; ++i)
	{
		v[i].clear();
		cin>>m;
		s=0;
		for(int j=1; j<=m; ++j)
		{
			char c;
			cin>>c;
			if(c=='W')
			{
				s=0;
				if(!v[i].empty())
				{
					if(!v[i].back().first) continue;
				}
				v[i].push_back({0, 0});
			}
			else if(c=='Z')
			{
				v[i].push_back({1, s});
				s=0;
			}
			else if(c=='-')
			{
				int a;
				cin>>a;
				s-=a;
			}
			else
			{
				int a;
				cin>>a;
				s+=a;
			}
		}
		len+=v[i].size();
		zl[i]=0;
	}
	t.resize(len+10);
	odp=1e18;
	xd(1);
	printf("%lld\n", odp);
}

int main()
{
	int q;
	cin>>q;
	while(q--)
	{
		solve();
	}
	return 0;
}