/*
  [BAPC'06] RUMMIKUB
  by: Jan Kuipers
*/

using namespace std;

#include <iostream>
#include <vector>
#include <string>

const int maxn = 100;
const int maxc = 4;
const string colors = "rgby";

const int numsets = 6;
const int sets[numsets] = { 0,7,11,13,14,15 };
const int minstrlen = 3;

int main () {

  int maxidx=1;
  for (int i=0; i<maxc; i++) maxidx*=minstrlen+1;
  
  int runs;
  cin>>runs;
  while (runs--) {

    vector<int> avai(maxn+1,0);
    int C;
    cin>>C;

    for (int i=0; i<C; i++) {
      int num; char col;
      cin>>num>>col;
      avai[num] |= 1<<colors.find(col);
    }

    int res=0;
    vector<int> best(maxidx,-INT_MAX/2);
    best[0]=0;
    
    for (int n=1; n<=maxn; n++) {
      vector<int> next(maxidx,-INT_MAX/2);

      for (int idx=0; idx<maxidx; idx++) {

	vector<int> len(maxc);
	int tmp=idx;
	for (int i=0; i<maxc; i++) { len[i]=tmp%(minstrlen+1); tmp/=(minstrlen+1); }

	for (int i=0; i<numsets; i++) {
	  if ((avai[n]&sets[i])!=sets[i]) continue;

	  vector<int> nlen(maxc);
	  int extra = 0;

	  for (int c=0; c<maxc; c++) {
	    if (!(avai[n]&(1<<c))) continue;
	    
	    if (sets[i]&(1<<c)) {
	      nlen[c]=0;
	      extra+=n;
	    }
	    else {
	      nlen[c] = (len[c]+1) <? minstrlen;
	      if (len[c]>=minstrlen-1) extra+=n;
	      if (len[c]==minstrlen-1) extra+=(minstrlen-1)*n - minstrlen*(minstrlen-1)/2;
	    }
	  }

	  int nidx=0;
	  for (int i=0; i<maxc; i++) nidx=(minstrlen+1)*nidx+nlen[maxc-1-i];
	  res >?= next[nidx] >?= best[idx]+extra;
	}	  
      }

      best=next;
    }

    cout << res << endl;
  }

  return 0;
}
