#include <iostream>
#include <vector>
#include <set>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <utility>
#include <ctime>
#include <algorithm>
#include <iomanip>
using namespace std;
#define pb push_back
const int SIZE = 100005;
bool GirlFriends[SIZE], check_type_1[SIZE], check_type_2[SIZE];
int final_type_1[SIZE], final_type_2[SIZE];
vector<int> type_1[SIZE][2];
vector<int> type_2[SIZE][2];
priority_queue <int> q;
int main()
{
ios::sync_with_stdio(false);// to boost I/O
cin.tie(0);
int t, len, k, type, l, r, ans;
string s;
cin >> t;
while(t--)
{
cin >> s;
len = s.size();
for(int i = 1; i<=len; i++)
{
GirlFriends[i] = false;
if(s[i-1]=='X')
GirlFriends[i] = true;
}
cin >> k;
/* Store Queries and their Indices */
for(int i = 1; i<=k; i++)
{
cin >> type >> l >> r;
if(type==1)
{
type_1[l][0].pb(i);
type_1[r+1][1].pb(i);
}
else if(type==2)
{
type_2[l][0].pb(i);
type_2[r+1][1].pb(i);
}
}
/* End */
/* Initializations */
for(int i = 1; i<=(len+2); i++)
{
final_type_1[i] = 0;
final_type_2[i] = 0;
}
for(int i = 1; i<=k; i++)
{
check_type_1[i] = true;
check_type_2[i] = true;
}
/* End */
/* Update for Type-1 */
for(int i = 1; i<=len; i++)
{
for(int j = 0; j<type_1[i][1].size(); j++)
{
check_type_1[type_1[i][1][j]] = false;
}
for(int j = 0; j<type_1[i][0].size(); j++)
{
q.push(type_1[i][0][j]);
}
if(!q.empty())
{
while(!q.empty() && !check_type_1[q.top()])
{
q.pop();
}
if(!q.empty())
{
final_type_1[i] = q.top();
}
}
}
/* End */
while(!q.empty())
{
q.pop();
}
/* Update for Type-2 */
for(int i = 1; i<=len; i++)
{
for(int j = 0; j<type_2[i][1].size(); j++)
{
check_type_2[type_2[i][1][j]] = false;
}
for(int j = 0; j<type_2[i][0].size(); j++)
{
q.push(type_2[i][0][j]);
}
if(!q.empty())
{
while(!q.empty() && !check_type_2[q.top()])
{
q.pop();
}
if(!q.empty())
{
final_type_2[i] = q.top();
}
}
}
/* End */
while(!q.empty())
{
q.pop();
}
/* Final String After Updating */
for(int i = 1; i<=len; i++)
{
if(final_type_1[i]>final_type_2[i])
{
GirlFriends[i] = true;
}
else if(final_type_1[i]<final_type_2[i])
{
GirlFriends[i] = false;
}
}
/* End */
/* Minimum number of Toggles */
int sum_X = 0, sum_O = 0;
for(int i = 1; i<=len; i++)
{
if(GirlFriends[i])
sum_X++;
}
int ans = sum_X;
for(int i = 1; i<=len; i++)
{
if(!GirlFriends[i]) sum_O++;
if(GirlFriends[i]) sum_X--;
ans = min(ans, sum_X + sum_O);
}
cout << ans << "\n";
/* End */
/* Clearing all the vector arrays for next test case */
for(int i = 0; i<=len; i++)
{
type_1[i][0].clear();
type_1[i][1].clear();
type_2[i][0].clear();
type_2[i][1].clear();
}
type_1[len+1][0].clear();
type_1[len+1][1].clear();
type_2[len+1][0].clear();
type_2[len+1][1].clear();
/* End */
}
}