#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <unordered_map>
#include <fstream>
using namespace std;
struct Transition {
int write_val;
int move_dir; // -1: Left, +1: Right
string next_state;
};
struct StateTransitions {
Transition on_zero;
Transition on_one;
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// 1. transitions.tsv dosyasını oku ve durum haritasını oluştur
ifstream tsv("transitions.tsv");
unordered_map<string, StateTransitions> machine;
vector<string> state_order;
int w0, w1;
char m0, m1;
string n0, n1;
// Format: 0 L HI 1 R NT
while (tsv >> w0 >> m0 >> n0 >> w1 >> m1 >> n1) {
// Durum isimleri dosyadaki satır sırasıyla belirlenir
// veya başlangıç durumu ilk satırdır.
StateTransitions st;
st.on_zero = {w0, (m0 == 'L' ? -1 : 1), n0};
st.on_one = {w1, (m1 == 'L' ? -1 : 1), n1};
// Otomatın durum anahtarını oluştur
string current_name = "S_" + to_string(state_order.size());
state_order.push_back(current_name);
machine[current_name] = st;
}
// 2. Test senaryolarını işle
int num_testcases;
if (!(cin >> num_testcases)) return 0;
string line;
getline(cin, line); // İlk satır sonu karakterini tüket
while (num_testcases--) {
if (!getline(cin, line)) break;
if (line.empty()) {
num_testcases++;
continue;
}
stringstream ss(line);
vector<int> nums;
int val;
while (ss >> val) {
nums.push_back(val);
}
// Teybi oluştur: C_1 tane '1', '0', C_2 tane '1', ...
unordered_map<long long, int> tape;
long long tape_idx = 0;
for (size_t i = 0; i < nums.size(); ++i) {
for (int k = 0; k < nums[i]; ++k) {
tape[tape_idx++] = 1;
}
if (i + 1 < nums.size()) {
tape[tape_idx++] = 0; // Sayılar arası ayırıcı
}
}
// Turing makinesini çalıştır
long long head = 0;
string current_state = state_order[0]; // Başlangıç durumu
while (machine.count(current_state)) {
int current_symbol = tape[head];
const Transition& trans = (current_symbol == 0)
? machine[current_state].on_zero
: machine[current_state].on_one;
tape[head] = trans.write_val;
head += trans.move_dir;
current_state = trans.next_state;
}
// Çıktı: Teypte kalan toplam 1 sayısı
long long count_ones = 0;
for (const auto& cell : tape) {
if (cell.second == 1) {
count_ones++;
}
}
cout << count_ones << "\n";
}
return 0;
}