#include<bits/stdc++.h>
using namespace std;

#define fo(i,n) for(int i = 0; i < n; i++)
#define parr(a,n) fo(i,n){cout << a[i] << " ";}cout<<"\n"
#define sarr(a,n) fo(i,n)cin >> a[i]
#define pb push_back
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define ps(x,y) fixed<<setprecision(y)<<x //cout << ps(ans, decimal places);
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
typedef pair<int, int> pi;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef vector<string> vs;
typedef vector<pi> vpii;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef map<int, int> mi;
typedef map<long long, long long> ml;
typedef set<int> si;
typedef set<long long> sl;
typedef long long int ll;
typedef unsigned long long int  ull;
typedef priority_queue<ll> mxhpl;
typedef priority_queue<int> mxhpi;
typedef priority_queue<ll, vector<ll>, greater<ll>> mnhpl;
typedef priority_queue<int, vector<int>, greater<int>> mnhpi;

// DEBUGGING
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char* x) { cerr << '\"' << x << '\"'; }
void __print(const string& x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }

template<typename T, typename V>
void __print(const pair<T, V>& x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; }
template<typename T>
void __print(const T& x) { int f = 0; cerr << '{'; for (auto& i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; }
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); }
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

// Fast IO
void IO() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  // freopen("output.txt", "w", stdout);
#endif
}

#define MOD 1000000007

//CODE
/*******************************************************/

ll n;

void solve() {
  cin >> n;
  string s; cin >> s;
  // vi a(n, 0);
  bool foundR = false, foundL = false;
  int firstR = -1, firstL = -1;
  fo(i, n) {
    if (s[i] == 'L') {
      foundL = 1;
      if (firstL == -1)firstL = i;
    } else {
      foundR = 1;
      if (firstR == -1)firstR = i;
    }

    if (foundL && foundR) break;

  }

  if (foundL ^ foundR) {
    cout << n/3 + (n%3 != 0) << "\n";
    return;
  }

  firstL = (firstL)?firstL:firstR;

  // debug(a);
  int cnt = 0;
  int tmp = 0;
  char cur = 'N';
  for(int i = firstL; i < n + firstL; i++) {
    // if (s[i] == s[((i - 1) % n + n) % n] && s[i] == s[(i + 1) % n]) {
    if (s[i%n] == s[(i + 1) % n]) {
      if (cur == s[i%n]) tmp++;
      else {
        tmp = 2;
        cur = s[i%n];
      }
    }
    else {
      // debug(ceil((double)tmp / 3));
      if (tmp > 1) {
        tmp -= 2;
        cnt += (tmp/3 + (tmp%3 != 0));
      }
      tmp = 0;
      cur = 'N';
    }
  }

  if (tmp) cnt += (tmp / 3);

  cout << cnt << "\n";
}

int main() {
  IO();

  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }

  return 0;
}

/*******************************************************/


#include<bits/stdc++.h>
using namespace std;

#define fo(i,n) for(int i = 0; i < n; i++)
#define parr(a,n) fo(i,n){cout << a[i] << " ";}cout<<"\n"
#define sarr(a,n) fo(i,n)cin >> a[i]
#define pb push_back
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define ps(x,y) fixed<<setprecision(y)<<x //cout << ps(ans, decimal places);
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
typedef pair<int, int> pi;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef vector<string> vs;
typedef vector<pi> vpii;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef map<int, int> mi;
typedef map<long long, long long> ml;
typedef set<int> si;
typedef set<long long> sl;
typedef long long int ll;
typedef unsigned long long int  ull;
typedef priority_queue<ll> mxhpl;
typedef priority_queue<int> mxhpi;
typedef priority_queue<ll, vector<ll>, greater<ll>> mnhpl;
typedef priority_queue<int, vector<int>, greater<int>> mnhpi;

// DEBUGGING
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char* x) { cerr << '\"' << x << '\"'; }
void __print(const string& x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }

template<typename T, typename V>
void __print(const pair<T, V>& x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; }
template<typename T>
void __print(const T& x) { int f = 0; cerr << '{'; for (auto& i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; }
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); }
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

// Fast IO
void IO() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  // freopen("output.txt", "w", stdout);
#endif
}

#define MOD 1000000007

//CODE
/*******************************************************/

ll n;

void solve() {
  cin >> n;
  string s; cin >> s;
  vi a(n,0);

  fo (i,n) {
    if (s[i] == 'L') a[((i-1)%n + n)%n]++;
    else a[(i+1)%n]++;
  }

  int cnt = 0;

  fo (i,n) {
    if (a[i] == 0 || a[i] == 2) continue;
    if (s[(i+1)%n] == 'L' && s[i] == 'L') {
      cnt++;
      s[i] = 'R';
      a[((i - 1) % n + n) % n]--;
      a[(i+1)%n]++;
      continue;
    }

    if (s[(i-1)%n] == 'R' && s[i] == 'R') {
      cnt++;
      s[i] = 'L';
      a[(i+1)%n]--;
      a[((i - 1) % n + n) % n]++;
      continue;
    }
  }

  fo (i,n) {
    if (a[i] == 0 || a[i] == 2) continue;
    if (s[(i+1)%n] == 'L' && s[i] == 'L') {
      cnt++;
      s[i] = 'R';
      a[((i - 1) % n + n) % n]--;
      a[(i+1)%n]++;
      continue;
    }

    if (s[(i-1)%n] == 'R' && s[i] == 'R') {
      cnt++;
      s[i] = 'L';
      a[(i+1)%n]--;
      a[((i - 1) % n + n) % n]++;
      continue;
    }
  }

  cout << cnt << "\n";
}

int main() {
  IO();

  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }

  return 0;
}

/*******************************************************/


#include<bits/stdc++.h>
using namespace std;

#define FOR(i, j, k, in) for (int i=j ; i<k ; i+=in)
#define RFOR(i, j, k, in) for (int i=j ; i>=k ; i-=in)
#define FO(i, j) FOR(i, 0, j, 1)
#define RFO(i, j) RFOR(i, j, 0, 1)
#define all(cont) cont.begin(), cont.end()
#define rall(cont) cont.end(), cont.begin()
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define mp make_pair
#define pb push_back
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define ps(x,y) fixed<<setprecision(y)<<x //cout << ps(ans, decimal places);
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
typedef pair<int, int> pi;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef vector<string> vs;
typedef vector<pi> vpii;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef map<int,int> mi;
typedef map<long long,long long> ml;
typedef set<int> si;
typedef set<long long> sl;
typedef long long int ll;
typedef unsigned long long int  ull;
typedef priority_queue<ll> mxhpl;
typedef priority_queue<int> mxhpi;
typedef priority_queue<ll, vector<ll>, greater<ll>> mnhpl;
typedef priority_queue<int, vector<int>, greater<int>> mnhpi;

void IO() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  // freopen("output.txt", "w", stdout);
#endif
}

template<typename... T>
void read(T&... args) {
  ((cin >> args), ...);
}

template<typename... T>
void write(T&&... args) {
  ((cout << args << " "), ...);
}

#define MOD 1000000007
int mpow(int, int);
/*******************************************************/

ll n;

void solve() {
  read(n);
  string s; read(s);
  int cnt;
  int ans = 0;
string s1 = s;
  FO(i,n) {
    if (s[((i-1)%n+n)%n] == s[i] && s[i] == s[((i-2)%n+n)%n]) {
      ans++;
      if (s[(i+1)%n] != s[i]) {
        if (s[((i-1)%n+n)%n] == 'R') s[((i-1)%n+n)%n] = 'L';
        else s[((i-1)%n+n)%n] = 'R';

      } else {

        if (s[i] == 'R') s[i] = 'L';
        else s[i] = 'R';
      }
    }
  }

  int ans2 = 0;
  s = s1;
  FO(i,n) {
    if (s[((i-1)%n+n)%n] == s[i] && s[i] == s[(i+1)%n]) {
      ans2++;
      if (s[i] == 'R') s[i] = 'L';
      else s[i] = 'R';
    }
  }

  // FO(i, n) {
  //   cnt = 0;
  //   if (i == 0) {
  //     cnt = (s[n-1] == 'R') + (s[1] == 'L');
  //     if (cnt == 1) {
  //       if (s[n-1] == 'R' && s[0] == 'R') {
  //         ans++;
  //         s[0] = 'L';
  //       }
  //       else if (s[1] == 'L' && s[0] == 'L') {
  //         ans++;
  //         s[0] = 'R';
  //       }
  //     }
  //   } else if (i == n-1) {
  //     cnt = (s[n-2] == 'R') + (s[0] == 'L');
  //     if (cnt == 1) {
  //      if (s[n-2] == 'R' && s[i] == 'R') {
  //         ans++;
  //         s[i] = 'L';
  //       }
  //       else if (s[0] == 'L' && s[i] == 'L') {
  //         ans++;
  //         s[i] = 'R';
  //       }
  //     }
  //   } else {
  //     cnt = (s[i-1] == 'R') + (s[i+1] == 'L');
  //     if (cnt == 1) {
  //      if (s[i-1] == 'R' && s[i] == 'R') {
  //         ans++;
  //         s[i] = 'L';
  //       }
  //       else if (s[i+1] == 'L' && s[i] == 'L') {
  //         ans++;
  //         s[i] = 'R';
  //       }
  //     }
  //   }
  // }

  cout << min(ans2,ans) << "\n";
  // cout << ans << "\n";
}

int main() {
  IO();

  int t = 1;
  cin >> t;
  while(t--) {
    solve();
  }

  return 0;
}

/*******************************************************/
int mpow(int base, int exp) {
  base %= MOD;
  int result = 1;
  while (exp > 0) {
    if (exp & 1) result = ((ll)result * base) % MOD;
    base = ((ll)base * base) % MOD;
    exp >>= 1;
  }
  return result;
}


#include<bits/stdc++.h>
using namespace std;

#define fo(i,n) for(int i = 0; i < n; i++)
#define parr(a,n) fo(i,n){cout << a[i] << " ";}cout<<"\n"
#define sarr(a,n) fo(i,n)cin >> a[i]
#define pb push_back
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define ps(x,y) fixed<<setprecision(y)<<x //cout << ps(ans, decimal places);
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
typedef pair<int, int> pi;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vl;
typedef vector<string> vs;
typedef vector<pi> vpii;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef map<int, int> mi;
typedef map<long long, long long> ml;
typedef set<int> si;
typedef set<long long> sl;
typedef long long int ll;
typedef unsigned long long int  ull;
typedef priority_queue<ll> mxhpl;
typedef priority_queue<int> mxhpi;
typedef priority_queue<ll, vector<ll>, greater<ll>> mnhpl;
typedef priority_queue<int, vector<int>, greater<int>> mnhpi;

// DEBUGGING
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char* x) { cerr << '\"' << x << '\"'; }
void __print(const string& x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }

template<typename T, typename V>
void __print(const pair<T, V>& x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; }
template<typename T>
void __print(const T& x) { int f = 0; cerr << '{'; for (auto& i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; }
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); }
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

// Fast IO
void IO() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  // freopen("output.txt", "w", stdout);
#endif
}

#define MOD 1000000007

//CODE
/*******************************************************/

ll n;

void solve() {
  cin >> n;
  string s; cin >> s;
  vi a(n, 0);

  fo(i, n) {
    if (s[i] == 'L') a[((i - 1) % n + n) % n]++;
    else a[(i + 1) % n]++;
  }

  // debug(a);

  int cnt = 0;
  int tmp = 0;
  char cur = 'N';
  fo(i, n) {
    if (s[i] == s[((i - 1) % n + n) % n] && s[i] == s[(i + 1) % n] && a[i] == 1) {
      if (cur == s[i]) tmp++;
      else {
        tmp = 1;
        cur = s[i];
      }
    }
    else {
      // debug(ceil((double)tmp / 3));
      cnt += (ceil((double)tmp / 3));
      tmp = 0;
      cur = 'N';
    }
    // debug(i, tmp);
  }
  if (tmp) cnt += ceil((double)tmp / 3);

  int cnt2 = 0;

  fo(i, n) {
    if (a[i] == 0 || a[i] == 2) continue;
    if (s[(i + 1) % n] == 'L' && s[i] == 'L') {
      cnt2++;
      s[i] = 'R';
      a[((i - 1) % n + n) % n]--;
      a[(i + 1) % n]++;
      continue;
    }

    if (s[(i - 1) % n] == 'R' && s[i] == 'R') {
      cnt2++;
      s[i] = 'L';
      a[(i + 1) % n]--;
      a[((i - 1) % n + n) % n]++;
      continue;
    }
  }

  cout << min(cnt,cnt2) << "\n";
}

int main() {
  IO();

  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }

  return 0;
}

/*******************************************************/


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=2e9;

using namespace std;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    int ans=0;

    int nr=1;

    while(s.size()>1 && s[0]==s[s.size()-1]) s.pop_back(),nr++;
    while(s.size()>1 && s[1]==s[0]) s.erase(s.begin()),nr++;

    s.erase(s.begin());

    ans+=nr/3+(nr>3 && nr%3);

    nr=1;
    for(int i=1;i<s.size();i++)
    {
        if(s[i]==s[i-1]) nr++; else
        {
            ans+=nr/3;
            nr=1;
        }
    }

    ans+=nr/3;

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=2e9;

using namespace std;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    int ans=0,nr=1;

    while(s.size()>1 && s[0]==s[s.size()-1]) s.pop_back(),nr++;

    if(s.size()==1)
    {
        cout<<(n+2)/3<<"\n";
        return;
    }

    for(int i=1;i<s.size();i++)
    {
        if(s[i]==s[i-1]) nr++; else
        {
            ans+=nr/3;
            nr=1;
        }
    }

    ans+=nr/3;

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=1e14;

using namespace std;

vector<int>v(nmax);
vector<bool>f(nmax);
int ans=0;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    for(int i=0;i<=n;i++) f[i]=0;

    for(int i=0;i<n;i++)
    {
        if(s[i]=='R')
        {
            if(i+1==n) v[i+1]=1; else v[i+1]=i+2;
        } else
        {
            if(i==0) v[i+1]=n; else v[i+1]=i;
        }
    }

    int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(!f[i])
        {
            if(v[v[i]]==i) f[v[i]]=1,f[i]=1; else
            if(v[v[v[i]]]==v[i]) f[i]=1,f[v[i]]=1,f[v[v[i]]]=1; else f[i]=1,f[v[i]]=1,ans++,v[i]=i;
        }
    }

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=1e14;

using namespace std;

vector<int>v(nmax);
vector<bool>f(nmax);
int ans=0;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    int ans=0,nr=1;
    for(int i=1;i<n-1;i++)
    {
        if(s[i]==s[i-1] && nr==2)
        {
            nr=1;
            if(s[i-1]=='R') s[i]='L'; else s[i]='R'
        } else nr++;
    }

    if((s[0]==s[1] && s[0]==s[2]) || (s[0]==s[n-1] && s[0]==s[n-2])) ans++;

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=1e14;

using namespace std;

vector<int>v(nmax);
vector<bool>f(nmax);
int ans=0;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    int ans=0;
    for(int i=1;i<n-1;i++)
    {
        if(s[i-1]=='L' && s[i]=='L' && s[i+1]=='L') ans++,s[i]='R'; else
        if(s[i-1]=='R' && s[i]=='R' && s[i+1]=='R') ans++,s[i]='L';
    }

    if(s[0]==s[1] && s[0]==s[n-1]) ans++; else
    if(s[n-1]==s[0] && s[n-1]==s[n-2]) ans++;

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=1e14;

using namespace std;

vector<int>v(nmax);
vector<bool>f(nmax);
int ans=0;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    int ans=0,nr=1;
    for(int i=1;i<n-1;i++)
    {
        if(s[i]==s[i-1] && nr==2)
        {
            nr=1;
            if(s[i-1]=='R') s[i]='L'; else s[i]='R';
            ans++;
        } else
        if(s[i]==s[i-1]) nr++; else nr=1;
    }

    if((s[0]==s[1] && s[0]==s[2]) || (s[0]==s[n-1] && s[0]==s[n-2])) ans++;

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=1e14;

using namespace std;

void kimusik()
{

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    //cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=1e14;

using namespace std;

vector<int>v(nmax);
vector<bool>f(nmax);
int ans=0;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    for(int i=0;i<=n;i++) f[i]=0;

    for(int i=0;i<n;i++)
    {
        if(s[i]=='R')
        {
            if(i+1==n) v[i+1]=1; else v[i+1]=i+2;
        } else
        {
            if(i==0) v[i+1]=n; else v[i+1]=i;
        }
    }

    int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(!f[i])
        {
            if(v[v[v[i]]]==v[i]) f[i]=1,f[v[i]]=1,f[v[v[i]]]=1; else
            {
                int x=v[v[i]];
                if(v[v[x]]!=x)
                {
                    f[i]=1,f[v[i]]=1,f[v[v[i]]]=1,v[v[v[i]]]=v[i],ans++;
                } else
                {
                    f[i]=1;
                    f[v[i]]=1;
                    ans++;
                    v[v[i]]=i;
                }
            }
        }
    }

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=2e9;

using namespace std;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    int ans=0,nr=1;

    while(s.size()>1 && s[0]==s[s.size()-1]) s.pop_back(),nr++;

    if(s.size()==1)
    {
        cout<<(n+3)/3<<"\n";
        return;
    }

    for(int i=1;i<s.size();i++)
    {
        if(s[i]==s[i-1]) nr++; else
        {
            ans+=nr/3;
            nr=1;
        }
    }

    ans+=nr/3;

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include<bits/stdc++.h>

#define int long long
#define all(a) (a).begin(), (a).end()

#define fr first
#define sc second

const int mod=1e9+7;
const int nmax=2e5+3;
const int inf=1e14;

using namespace std;

vector<int>v(nmax);
vector<bool>f(nmax);
int ans=0;

void kimusik()
{

    int n;
    cin>>n;

    string s;
    cin>>s;

    for(int i=0;i<=n;i++) f[i]=0;

    for(int i=0;i<n;i++)
    {
        if(s[i]=='R')
        {
            if(i+1==n) v[i+1]=1; else v[i+1]=i+2;
        } else
        {
            if(i==0) v[i+1]=n; else v[i+1]=i;
        }
    }

    int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(!f[i])
        {
            if(v[v[i]]==i) f[v[i]]=1,f[i]=1; else
            if(v[v[v[i]]]==v[i]) f[i]=1,f[v[i]]=1,f[v[v[i]]]=1; else
            {
                int x=v[v[i]];
                if(v[v[x]]!=x)
                {
                    f[i]=1,f[v[i]]=1,f[v[v[i]]]=1,v[v[v[i]]]=v[i],ans++;
                } else
                {
                    f[i]=1;
                    f[v[i]]=1;
                    ans++;
                    v[v[i]]=i;
                }
            }
        }
    }

    cout<<ans<<"\n";

}

int32_t main()
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);

    int t=1;
    cin>>t;

    while(t--) kimusik();

    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << n/2 << endl;
			continue;
		}
		int ans = 0;
		vector<int> count;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				if (num >= 3) {
					ans += (num-1)/2;
				}
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		if (num >= 3) {
			ans += 1 + (num-3)/2;
		}
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << ceil(n/3.0) << endl;
			continue;
		}
		int ans = 0;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				ans += n/3;
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

vector<int> dp(200001);
int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	dp[0] = 0;
	dp[1] = 0;
	dp[2] = 1;
	for (int i = 3; i <= 200000; i++) {
		dp[i] = 1 + dp[i-2];
	}
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << dp[n] << endl;
			continue;
		}
		int ans = 0;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		bool first = vals[index];
		last = vals[index];
		int count = 1;
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				num--;
				ans += dp[num];
				num = 1;
				count++;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		if (count % 2 == 1) {
			ans += dp[num];
		} else {
			ans += dp[num-1];
		}

		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

vector<int> dp(200001);
int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	dp[0] = 0;
	dp[1] = 0;
	dp[2] = 1;
	for (int i = 3; i <= 200000; i++) {
		dp[i] = 1 + dp[i-2];
	}
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << dp[n] << endl;
			continue;
		}
		int ans = 0;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		bool first = vals[index];
		last = vals[index];
		int num = 0;
		vector<int> count;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				num--;
				ans += dp[num];
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		num--;
		ans += dp[num];
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		//True if attacking right
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << 1 + (n-3)/2 << endl;
			continue;
		}
		int ans = 0;
		vector<int> count;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				if (num >= 3) {
					ans += 1 + (num-3)/2;
				}
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		if (num >= 3) {
			ans += 1 + (num-3)/2;
		}
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << ceil(n/3.0) << endl;
			continue;
		}
		int ans = 0;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				if (num >= 3) {
					ans += ceil((num-1)/3.0);
				}
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		if (num >= 3) {
			ans += 1 + (num-3)/2;
		}
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			if (n > 1) {
				cout << ceil(n/3.0) << endl;
				continue;
			}
		}
		int ans = 0;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				num--;
				if (num > 1) {
					ans += ceil((num)/3.0);
				}
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		if (num >= 3) {
			ans += 1 + (num-3)/2;
		}
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			if (n >= 3) {
				cout << 1 + (n-3)/2 << endl;
			} else if (n == 2) {
				cout << 1 << endl;
			} else {
				cout << 0 << endl;
			}
			continue;
		}
		int ans = 0;
		vector<int> count;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				if (num >= 3) {
					ans += 1 + (num-3)/2;
				}
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		if (num >= 3) {
			ans += 1 + (num-3)/2;
		}
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

vector<int> dp(200001);
int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	dp[0] = 0;
	dp[1] = 0;
	dp[2] = 1;
	for (int i = 3; i <= 200000; i++) {
		dp[i] = 1 + dp[i-2];
	}
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << dp[n] << endl;
			continue;
		}
		int ans = 0;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				num--;
				if (num > 1) {
					ans += dp[num];
				}
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		if (num >= 3) {
			ans += 1 + (num-3)/2;
		}
		cout << ans << endl;
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <iomanip>
#define INF 2147483647
#define LINF 9223372036854775807ll
#define PI pair<int, int>
#define PL pair<long long, long long>
#define ll long long
#define pb push_back
#define loop(h) while(h--)
using namespace std;
char _;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int t; cin >> t;
	loop(t) {
		int n; cin >> n;
		vector<bool> vals(n);
		string s; cin >> s;
		bool right = false;
		bool left = false;
		for (int i = 0; i < n; i++) {
			vals[i] = s[i] == 'R';
			if (vals[i] == true) right = true;
			else left = true;
		}
		if (!right || !left) {
			cout << ceil(n/3.0) << endl;
			continue;
		}
		int ans = 0;
		bool last = vals[0];
		int index = 0;
		while (vals[index] == last) {
			index++;
		}
		last = vals[index];
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (vals[index] == last) {
				num++;
			} else {
				ans += num/3;
				num = 1;
			}
			last = vals[index];
			index = (index + 1)%n;
		}
		ans += num/3;
		cout << ans << endl;
	}
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

vector<set<int>> graph;
vector<char> s;
vector<bool> vis;
set<int> good;
int n;

pair<int, int> dfs(int vertex) {
  vis[vertex] = true;
  int gc = 0, bc = 0;
  stack<int> s;
  s.push(vertex);
  set<int> b;
  while (!s.empty()) {
    int v = s.top();
    gc++;
    b.insert(v);
    s.pop();
    for (int i : graph[v]) {
      if (vis[i]) {
        if (b.find(i) != b.end()) bc++;
      } else {
        s.push(i);
        vis[i] = true;
      }
    }
  }
  for (int i : b) good.insert(i);
  return make_pair(gc, bc);
}

void solve() {
  cin >> n;
  graph.resize(n + 1);
  graph.clear();
  s.resize(n + 1);
  s.clear();
  vis.assign(n + 1, false);
  bool diff = false;
  for (int i = 1; i <= n; i++) {
    cin >> s[i];
    if (i > 1 && s[i] != s[i - 1]) diff = true;
  }
  // for (int i = 1; i <= n; i++) cout << s[i];
  // cout << "\n";
  s[0] = s[n];
  vector<int> in(n + 1);
  for (int i = 1; i <= n; i++) {
    if (s[i] == 'L') {
      if (i == 1) {
        graph[i].insert(n);
        in[n]++;
        // graph[n].insert(i);
      } else {
        graph[i].insert(i - 1);
        in[i - 1]++;
        // graph[i - 1].insert(i);
      }
    } else {
      if (i == n) {
        graph[n].insert(1);
        in[1]++;
        // graph[1].insert(n);
      } else {
        graph[i].insert(i + 1);
        in[i + 1]++;
        // graph[i + 1].insert(i);
      }
    }
  }
  // for (int i = 1; i <= n; i++) {
  //   cout << i << " -> ";
  //   for (int x : graph[i]) cout << x << " ";
  //   cout << "\n";
  // }
  int res = 0;
  vector<int> b;
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0) b.push_back(i);
  }
  if (!diff) {
    cout << n / 2;
    cout << "\n";
    return;
  }
  b.push_back(1);
  for (int i : b) {
    if (vis[i]) continue;
    // cout << i << "\n";
    auto [gc, bc] = dfs(i);
    int x = gc - 2 * bc;
    if (x < 0) x = 0;
    x /= 2;
    // cout << i << " -> " << gc << ", " << bc << "\n";
    // cout << i << " -> " << x << "\n";
    res += x;
  }
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

void solve() {
  int n;
  cin >> n;
  string s;
  cin >> s;
  s += s[0];
  s += s[1];
  int res = 0, cnt = 0;
  for (int i = 0; i < n + 2; i++) {
    cnt++;
    if (s[i] != s[i - 1]) {
      res += cnt / 3;
      cnt = 0;
    }
  }
  res += cnt / 3;
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

void solve() {
  int n;
  cin >> n;
  vector<char> s(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> s[i];
    if (i == n) s[0] = s[i];
  }
  // for (int i = 1; i <= n; i++) cout << s[i];
  // cout << "\n";
  vector<int> in(n + 2);
  set<int> good;
  for (int i = 1; i <= n; i++) {
    if (s[i] == 'L') in[i - 1]++;
    else in[i + 1]++;
  }
  in[n] = in[0] = max(in[0], in[n]);
  for (int i = 1; i <= n; i++) {
    // if (in[i] == 1) continue;
    // good.insert(i);
    // if (in[i] == 0) continue;
    if (in[i] == 0) {
      good.insert(i); continue;
    }
    if (s[i] == 'L' && s[i - 1] == 'R')
      good.insert(i - 1), good.insert(i);
    if (s[i] == 'R' && s[i + 1] == 'L')
      good.insert(i + 1), good.insert(i);
  }
  // for (int i = 1; i <= n; i++) {
  //   cout << in[i] << " ";
  // }
  // cout << "\n";
  // for (auto it = good.begin(); it != good.end(); it++) {
  //   cout << *it << " ";
  // }
  // cout << "\n";
  int res = 0;
  for (int i = 1; i <= n; i++) {
    if (good.find(i) != good.end() || in[i] == 0 || in[i] == 2) continue;
    if (s[i - 1] == 'R' && s[i] != 'L') {
      if (i != n) in[i + 1]--;
      else in[1]--;
      in[i - 1]++;
      // cout << i << "\n";
      res++;
    }
    if (s[i + 1] == 'L' && s[i] != 'R') {
      in[i - 1]--;
      if (i != n) in[i + 1]++;
      else in[1]++;
      // cout << i << "\n";
      res++;
    }
    if (i == 1 || i == n) {
      in[0] = in[n] = min(in[0], in[n]);
    }
  }
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

vector<set<int>> graph;
vector<char> s;
vector<bool> vis;
set<int> good;
int n;

pair<int, int> dfs(int vertex) {
  vis[vertex] = true;
  int gc = 0, bc = 0;
  stack<int> s;
  s.push(vertex);
  set<int> b;
  while (!s.empty()) {
    int v = s.top();
    gc++;
    b.insert(v);
    s.pop();
    for (int i : graph[v]) {
      if (vis[i]) {
        if (b.find(i) != b.end()) bc++;
      } else {
        s.push(i);
        vis[i] = true;
      }
    }
  }
  for (int i : b) good.insert(i);
  return make_pair(gc, bc);
}

void solve() {
  cin >> n;
  graph.resize(n + 1);
  graph.clear();
  s.resize(n + 1);
  s.clear();
  good.clear();
  vis.assign(n + 1, false);
  bool diff = false;
  for (int i = 1; i <= n; i++) {
    cin >> s[i];
    if (i > 1 && s[i] != s[i - 1]) diff = true;
  }
  // for (int i = 1; i <= n; i++) cout << s[i];
  // cout << "\n";
  s[0] = s[n];
  vector<int> in(n + 1);
  for (int i = 1; i <= n; i++) {
    if (s[i] == 'L') {
      if (i == 1) {
        graph[i].insert(n);
        in[n]++;
        // graph[n].insert(i);
      } else {
        graph[i].insert(i - 1);
        in[i - 1]++;
        // graph[i - 1].insert(i);
      }
    } else {
      if (i == n) {
        graph[n].insert(1);
        in[1]++;
        // graph[1].insert(n);
      } else {
        graph[i].insert(i + 1);
        in[i + 1]++;
        // graph[i + 1].insert(i);
      }
    }
  }
  // for (int i = 1; i <= n; i++) {
  //   cout << i << " -> ";
  //   for (int x : graph[i]) cout << x << " ";
  //   cout << "\n";
  // }
  int res = 0;
  vector<int> b;
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0) b.push_back(i);
  }
  if (!diff) {
    cout << n / 2;
    cout << "\n";
    return;
  }
  b.push_back(1);
  for (int i : b) {
    if (vis[i]) continue;
    // cout << i << "\n";
    auto [gc, bc] = dfs(i);
    int x = gc - 2 * bc;
    if (x < 0) x = 0;
    x /= 2;
    // cout << i << " -> " << gc << ", " << bc << "\n";
    // cout << i << " -> " << x << "\n";
    res += x;
  }
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

void solve() {
  int n;
  cin >> n;
  vector<char> s(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> s[i];
    if (i == n) s[0] = s[i];
  }
  // for (int i = 1; i <= n; i++) cout << s[i];
  // cout << "\n";
  vector<int> in(n + 1);
  set<int> good;
  for (int i = 1; i <= n; i++) {
    if (s[i] == 'L') in[i - 1]++;
    else in[i + 1]++;
  }
  in[n] = in[0] = max(in[0], in[n]);
  for (int i = 1; i <= n; i++) {
    if (in[i] == 1) continue;
    good.insert(i);
    if (in[i] == 0) continue;
    if (s[i] == 'L' && s[i - 1] == 'R') good.insert(i - 1);
    if (s[i] == 'R' && s[i + 1] == 'L') good.insert(i + 1);
  }
  // for (int i = 1; i <= n; i++) {
  //   cout << in[i] << " ";
  // }
  // cout << "\n";
  // for (auto it = good.begin(); it != good.end(); it++) {
  //   cout << *it << " ";
  // }
  // cout << "\n";
  int res = 0;
  for (int i = 1; i <= n; i++) {
    if (good.find(i) != good.end() || in[i] == 0 || in[i] == 2) continue;
    if (s[i - 1] == 'R' && s[i] != 'L') {
      in[i + 1]--;
      in[i - 1]++;
      // cout << i << "\n";
      res++;
    }
    if (s[i + 1] == 'L' && s[i] != 'R') {
      in[i - 1]--;
      in[i + 1]++;
      // cout << i << "\n";
      res++;
    }
    if (i == 1 || i == n) {
      in[0] = in[n] = min(in[0], in[n]);
    }
  }
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

void solve() {
  int n;
  cin >> n;
  string s;
  cin >> s;
  s += s[0];
  s += s[1];
  int res = 0, cnt = 0;
  bool fine = true;
  for (int i = 0; i < n + 2; i++) {
    cnt++;
    if (s[i] != s[i - 1]) {
      fine = false;
      res += cnt / 3;
      cnt = 0;
    }
  }
  if (fine) cnt += 2;
  res += cnt / 3;
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

void solve() {
  int n;
  cin >> n;
  vector<char> s(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> s[i];
    if (i == n) s[0] = s[i];
  }
  // for (int i = 1; i <= n; i++) cout << s[i];
  // cout << "\n";
  vector<int> in(n + 1);
  set<int> good;
  for (int i = 1; i <= n; i++) {
    if (s[i] == 'L') in[i - 1]++;
    else in[i + 1]++;
  }
  in[n] = in[0] = max(in[0], in[n]);
  for (int i = 1; i <= n; i++) {
    if (in[i] == 1) continue;
    good.insert(i);
    if (in[i] == 0) continue;
    if (s[i] == 'L' && s[i - 1] == 'R') good.insert(i - 1);
    if (s[i] == 'R' && s[i + 1] == 'L') good.insert(i + 1);
  }
  // for (int i = 1; i <= n; i++) {
  //   cout << in[i] << " ";
  // }
  // cout << "\n";
  // for (auto it = good.begin(); it != good.end(); it++) {
  //   cout << *it << " ";
  // }
  // cout << "\n";
  int res = 0;
  for (int i = 1; i <= n; i++) {
    if (good.find(i) != good.end() || in[i] == 0 || in[i] == 2) continue;
    if (s[i - 1] == 'R' && s[i] != 'L') {
      in[i + 1]--;
      in[i - 1]++;
      // cout << i << "\n";
      res++;
    }
    if (s[i + 1] == 'L' && s[i] != 'R') {
      in[i - 1]--;
      in[i + 1]++;
      // cout << i << "\n";
      res++;
    }
    if (i == 1 || i == n) {
      in[0] = in[n] == min(in[0], in[n]);
    }
  }
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

void solve() {
  int n;
  cin >> n;
  vector<char> s(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> s[i];
    if (i == n) s[0] = s[i];
  }
  // for (int i = 1; i <= n; i++) cout << s[i];
  // cout << "\n";
  vector<int> in(n + 2);
  set<int> good;
  for (int i = 1; i <= n; i++) {
    if (s[i] == 'L') in[i - 1]++;
    else in[i + 1]++;
  }
  in[n] = in[0] = max(in[0], in[n]);
  for (int i = 1; i <= n; i++) {
    if (in[i] == 1) continue;
    good.insert(i);
    if (in[i] == 0) continue;
    if (s[i] == 'L' && s[i - 1] == 'R') good.insert(i - 1);
    if (s[i] == 'R' && s[i + 1] == 'L') good.insert(i + 1);
  }
  // for (int i = 1; i <= n; i++) {
  //   cout << in[i] << " ";
  // }
  // cout << "\n";
  // for (auto it = good.begin(); it != good.end(); it++) {
  //   cout << *it << " ";
  // }
  // cout << "\n";
  int res = 0;
  for (int i = 1; i <= n; i++) {
    if (good.find(i) != good.end() || in[i] == 0 || in[i] == 2) continue;
    if (s[i - 1] == 'R' && s[i] != 'L') {
      if (i != n) in[i + 1]--;
      else in[1]--;
      in[i - 1]++;
      // cout << i << "\n";
      res++;
    }
    if (s[i + 1] == 'L' && s[i] != 'R') {
      in[i - 1]--;
      if (i != n) in[i + 1]++;
      else in[1]++;
      // cout << i << "\n";
      res++;
    }
    if (i == 1 || i == n) {
      in[0] = in[n] = min(in[0], in[n]);
    }
  }
  cout << res << "\n";
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while(t--) solve();
  return 0;
}


import math
import sys
for _ in range (int(sys.stdin.readline())) :
    n,m,x,y = map(int,sys.stdin.readline().split())
    l = []
    count = 0
    for i in range (n) :
        xx = []
        yy = sys.stdin.readline()
        for i in range (m) :
            xx.append(yy[i])
        count += xx.count(".")
        l.append(xx)
    if 2*x <= y :
        print(count*x)
    else :
        ans = 0
        last = 1
        for i in range (n) :
            last = 1
            for j in range (m) :
                if l[i][j] == "." :
                    if last == 0 :
                        ans += 1
                        last = 1
                    else :
                        last = 0
        print((count-2*ans)*x + ans*y)


import math
import sys
for _ in range (int(sys.stdin.readline())) :
    n,m,x,y = map(int,sys.stdin.readline().split())
    l = []
    count = 0
    for i in range (n) :
        xx = []
        yy = sys.stdin.readline()
        for i in range (m) :
            xx.append(yy[i])
        count += xx.count(".")
        l.append(xx)
    if 2*x <= y :
        print(count*x)
    else :
        ans = 0
        last = 1
        for i in range (n) :
            for j in range (m-1) :
                if l[i][j] == "." and l[i][j+1] == "."  :
                    ans += 1
                    l[i][j] = "*"
                    l[i][j+1] = "*"
        print((count-2*ans)*x + ans*y)


t = int(input())
for _ in range(t):
    n, m, x, y = map(int, input().split())
    mat = ['o']*n
    for i in range(n):
        mat[i] = input()
    ans = 0
    if (m == 1):
        ans = n * x
    else:
        i = 0
        while (i < n):
            j = 0
            while (j < m):
                if (mat[i][j] == '*'):
                    j = j + 1
                else:
                    if (j == m - 1):
                        ans = ans + x;
                        j = j + 1;
                    else:
                        if (2*x < y and mat[i][j] == mat[i][j + 1]):
                            ans = ans + (2 * x);
                            j = j + 2;
                        elif(y <= 2*x and mat[i][j] == mat[i][j + 1]):
                            ans = ans + y;
                            j = j + 2;
                        else:
                            ans = ans + x;
                            j += 1;
            i += 1
    print(ans)


t = int(input())
for _ in range(t):
    n, m, x, y = map(int, input().split())
    mat = ['o']*n
    for i in range(n):
        mat[i] = input()
    ans = 0
    if (m == 1):
        i = 0
        while (i < n):
            if (mat[i][0] == '.'):
                ans = ans + x
            i += 1
    else:
        i = 0
        while (i < n):
            j = 0
            while (j < m):
                if (mat[i][j] == '*'):
                    j = j + 1
                else:
                    if (j == m - 1):
                        ans = ans + x;
                        j = j + 1;
                    else:
                        if (2*x < y and mat[i][j] == mat[i][j + 1]):
                            ans = ans + (2 * x);
                            j = j + 2;
                        elif(y <= 2*x and mat[i][j] == mat[i][j + 1]):
                            ans = ans + y;
                            j = j + 2;
                        else:
                            ans = ans + x;
                            j += 1;
            i += 1
    print(ans)


t = int(input())
for _ in range(t):
    n, m, x, y = map(int, input().split())
    mat = ['o']*n
    for i in range(n):
        mat[i] = input()
    ans = 0
    if (m == 1):
        ans = n * x
    else:
        i = 0
        while (i < n):
            j = 0
            while (j < m):
                if (mat[i][j] == '*'):
                    j = j + 1
                    continue
                if (j == m - 1):
                    ans = ans + x;
                    j = j + 1;
                else:
                    if (2*x < y and mat[i][j] == mat[i][j + 1]):
                        ans = ans + (2 * x);
                        j = j + 2;
                    elif(y <= 2*x and mat[i][j] == mat[i][j + 1]):
                        ans = ans + y;
                        j = j + 2;
                    else:
                        ans = ans + x;
                        j += 1;
            i += 1
    print(ans)


for i in range(int(input())):
    n,m,x,y=map(int,input().split())
    z=0
    for i in range(n):
          s=input()
          k=s.count('.')
          a=s.count('..')
          if a*2==k:
              z=min(k*x,a*y)+z
          if a*2!=k :
              z=a*y+abs(k-2*a)*x+z
    print(z)


for i in range(int(input())):
    n,m,x,y=map(int,input().split())
    z=0
    for i in range(n):
          s=input()
          k=s.count('.')*x
          a=s.count('..')*y
          if k!=0 and a!=0:
              z=min(k,a)+z
          else:
              z=max(k,a)+z
    print(z)


for i in range(int(input())):
    n,m,x,y=map(int,input().split())
    z=0
    for i in range(n):
          s=input()
          k=s.count('.')
          a=s.count('..')
          if a*2==k:
              z=min(k*x,a*y)+z
          if a*2!=k :
              z=min((a*y+abs(k-2*a)*x+z),(k*x+z))
    print(z)


import math
t=int(input())
for i in range(t):
    l=list(map(int,input().split()))
    n,m,x,y=l[0],l[1],l[2],l[3]
    if(y>=2*x):
        val=0
        for j in range(n):
            p=str(input())
            val+=p.count('.')
        print(x*val)
    else:
        vala,valb=0,0
        for j in range(n):
            p=str(input())
            vala+=p.count('..')
            valb+=(p.count('.'))%2
        print(x*(valb)+y*vala)


import math
t=int(input())
for i in range(t):
    l=list(map(int,input().split()))
    n,m,x,y=l[0],l[1],l[2],l[3]
    if(y>2*x):
        val=0
        for j in range(n):
            p=str(input())
            val+=p.count('.')
        print(x*val)
    else:
        vala,valb=0,0
        for j in range(n):
            p=str(input())
            vala+=p.count('..')
            valb+=(p.count('.'))%2
        print(x*(valb)+y*vala)


import math
t=int(input())
for i in range(t):
    l=list(map(int,input().split()))
    n,m,x,y=l[0],l[1],l[2],l[3]
    if(y>2*x):
        val=0
        for j in range(n):
            p=str(input())
            val+=p.count('.')
        print(x*val)
    else:
        vala,valb=0,0
        for j in range(n):
            p=str(input())
            vala+=p.count('..')
            valb+=(p.count('.'))
        print(x*(valb-2*vala)+y*vala)


import math
t = int(input())
for _ in range(t):
    l = list(map(int, input().split()))
    n = l[0]
    m = l[1]
    x = l[2]
    y = l[3]
    mat = []
    c = 0
    for _ in range(n):
        a = input().split()
        c+= a.count('.')
        mat.append(a)
    if c*x <= math.floor(c/2)*y + (c%2)*x:
        print("D",c)
        print(c*x)
    else :
        c1 = 0
        c2 = 0
        for i in range(0,n,1):
            j = 0
            while j<m:
                if mat[i][j] == '.':
                    if  j+1 < m and mat[i][j+1] == '.' :
                        c2 +=1
                        j += 1
                    else:
                        c1+=1
                j+=1
        print(c1*x + c2*y)


import math
t = int(input())
for _ in range(t):
    l = list(map(int, input().split()))
    n = l[0]
    m = l[1]
    x = l[2]
    y = l[3]
    mat = []
    c = 0
    for _ in range(n):
        a = input()
        a = list(a)
        # print("a",a)
        c+= a.count('.')
        mat.append(a)
    if c*x <= math.floor(c/2)*y + (c%2)*x:
        # print("D",c)
        print(c*x)
    else :
        c1 = 0
        c2 = 0
        for i in range(0,n,1):
            j = 0
            while j<m:
                if mat[i][j] == '.':
                    if  j+1 < m and mat[i][j+1] == '.' :
                        c2 +=1
                        j += 1
                    else:
                        c1+=1
                j+=1
        print(c1*x + c2*y)


import math
t = int(input())
for _ in range(t):
    l = list(map(int, input().split()))
    n = l[0]
    m = l[1]
    x = l[2]
    y = l[3]
    mat = []
    c = 0
    for _ in range(n):
        a = input().split()
        # print(a)
        c+= a.count('.')
        mat.append(a)
    if c*x <= math.floor(c/2)*y + (c%2)*x:
        # print("D",c)
        print(c*x)
    else :
        c1 = 0
        c2 = 0
        for i in range(0,n,1):
            j = 0
            while j<m:
                if mat[i][j] == '.':
                    if  j+1 < m and mat[i][j+1] == '.' :
                        c2 +=1
                        j += 1
                    else:
                        c1+=1
                j+=1
        print(c1*x + c2*y)


import math
import sys
from sys import stdin
input=sys.stdin.readline
for _ in range(int(input())):
    n,m,x,y=[int(j) for j in input().split()]
    arr=[]
    for i in range(n):
        arr.append(input())
    if x*2<=y:
        counti=0
        for i in range(n):
            counti+=arr[i].count('.')
        print(counti*x)
    else:
        counti=0
        countii=0
        for i in range(n):
            counti+=arr[i].count('.')
        for i in range(n):
            temp=m-1
            j=0
            while temp>0:
                if arr[i][j]=='.' and arr[i][j+1]=='.':
                    countii+=1
                    j+=2
                else:
                    j+=1
                temp-=1
        # print(counti,countii)
        result=countii*y
        counti=counti-2*countii
        result+=counti*x
        print(result)


import math
import sys
from sys import stdin
input=sys.stdin.readline
for _ in range(int(input())):
    n,m,x,y=[int(j) for j in input().split()]
    arr=[]
    for i in range(n):
        arr.append(input())
    if x*2<=y:
        counti=0
        for i in range(n):
            counti+=arr[i].count('.')
        print(counti*x)
    else:
        counti=0
        countii=0
        for i in range(n):
            counti+=arr[i].count('.')
        for i in range(n):
            temp=m
            j=0
            while temp>0:
                if arr[i][j]=='.' and arr[i][j+1]=='.':
                    countii+=1
                    j+=2
                else:
                    j+=1
                temp-=1
        # print(counti,countii)
        result=countii*y
        counti=counti-2*countii
        result+=counti*x
        print(result)


import math
import sys
from sys import stdin
input=sys.stdin.readline
for _ in range(int(input())):
    n,m,x,y=[int(j) for j in input().split()]
    arr=[]
    for i in range(n):
        arr.append(input())
    if x*2<=y:
        counti=0
        for i in range(n):
            counti+=arr[i].count('.')
        print(counti*x)
    else:
        counti=0
        countii=0
        for i in range(n):
            counti+=arr[i].count('.')
        for i in range(n):
            temp=m-1
            j=0
            try:
                while temp>0:
                    if arr[i][j]=='.' and arr[i][j+1]=='.':
                        countii+=1
                        j+=2
                    else:
                        j+=1
                    temp-=1
            except:
                temp-=1
        # print(counti,countii)
        result=countii*y
        counti=counti-2*countii
        result+=counti*x
        print(result)


for _ in range(int(input())): n,m,x,y=map(int,input().split()) c=0 for q in range(n): s=input() a=s.count("..") b=s.count(".") if y<2*x: c+=a*y+(b-2*a)*x else: c+=b*x print(c)


for _ in range(int(input())):
    n,m,x,y = map(int, input().split())
    ans=0
    for i in range(n):
        a = input()
        qq = a.count('..')
        q = a.count('.')
        if(2*x>y and qq>0):
            ans=ans+qq*y+(q%2)*x
        else:
            ans=ans+q*x
    print(ans)


for _ in range(int(input())):
    n,m,x,y = map(int, input().split())
    ans=0
    for i in range(n):
        a = input()
        qq = a.count('..')
        q = a.count('.')
        if(2*x>y):
            ans+=qq*y+(q%2)*x
        else:
            ans+=q*x
    print(ans)


for _ in range(int(input())):
    n,m,x,y = map(int, input().split())
    ans=0
    for i in range(n):
        a = input()
        qq = a.count('..')
        q = a.count('.')
        if(2*x>y):
            ans+=qq*y+(q-2*qq)*x
        else:
            ans+=q*x
    print(ans)


for _ in range(int(input())):
    n,m,x,y = map(int, input().split())
    ans=0
    for i in range(n):
        a = input()
        qq = a.count('..')
        q = a.count('.')
        if(2*x<=y):
            ans=ans+qq*y+(q%2)*x
        else:
            ans=ans+q*x
    print(ans)


for _ in range(int(input())):
	n,m,x,y=map(int,input().split())
	c=0
	for q in range(n):
		s=input()
		a=s.count("..")
		b=s.count(".")
		if y<2*x:
			c+=a*y+(b-2*a)*x
		else:
			c+=b*x
	print(c)


for j in range(int(input)):
    a,b,c,d=map(int(input().spilt()))
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)

print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)

print(val)


for _ in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if (2*c)>d:
            val=val+((y*d)+(x-2*y)*c)

        else:
            val=val+x*c

    print(val)


for j in range(int(input)):
    a,b,c,d=map(int(input().spilt()))
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for q in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)
    print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        z=input()
        x=z.count('.')
        y=z.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)

    print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        z=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)

    print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+(x*c)
        else:
            val=val+((y*d)+(x-2*y)*c)

    print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if (2*c)>d:
            val=val+((y*d)+(x-2*y)*c)

        else:
            val=val+x*c

    print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)

    print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if 2*c<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)
    print(val)


for j in range(int(input())):
    a,b,c,d=map(int,input().split())
    val=0
    for i in range(a):
        s=input()
        x=s.count('.')
        y=s.count('. .')

        if (2*c)<d:
            val=val+x*c
        else:
            val=val+((y*d)+(x-2*y)*c)

    print(val)


t=int(input())
count=0
while count<t:
    count+=1
    l=list(map(int, input().split(' ')))
    n=l[0]
    m=l[1]
    one=l[2]
    two=l[3]
    board = []
    for i in range(n):
        board.append(input())
    prof = min(2*one,two)
    ans=0
    for i in board:
        if m==1 and i[0]=='.':
            ans+=one
        else:
            j=0
            while j<m:
                if j==m-1:
                    if i[j]=='.':
                        ans+=one
                elif i[j]=='.':
                    if i[j+1]=='.':
                        ans+=prof
                        j+=1
                    else:
                        ans+=one
                j+=1
    print(ans)


t=int(input())
count=0
while count<t:
    count+=1
    l=list(map(int, input().split(' ')))
    n=l[0]
    m=l[1]
    one=l[2]
    two=l[3]
    board = []
    for i in range(n):
        board.append(input())
    prof = min(2*one,two)
    ans=0
    for i in board:
        if m==1:
            ans+=one
        else:
            j=0
            while j<m:
                if j==m-1:
                    if i[j]=='.':
                        ans+=one
                elif i[j]=='.':
                    if i[j+1]=='.':
                        ans+=prof
                        j+=1
                    else:
                        ans+=one
                j+=1
    print(ans)


t=int(input())
count=0
while count<t:
    count+=1
    l=list(map(int, input().split(' ')))
    n=l[0]
    m=l[1]
    one=l[2]
    two=l[3]
    board = []
    for i in range(n):
        board.append(input())
    prof = min(2*one,two)
    ans=0
    for i in board:
        if m==1:
            ans+=one
        else:
            j=0
            while j<m:
                if j==m-1:
                    if i[j]=='.':
                        ans+=one
                elif i[j]=='.' and i[j+1]=='.':
                    ans+=prof
                    j+=1
                elif i[j]=='.':
                    ans+=one
                j+=1
    print(ans)


import string
from sys import stdin
t = int(input())
for _ in range(t):
    n,m,x,y = [int(w) for w in input().split()]
    l=[]
    for i in range(n):
        q = input()
        q1=[]
        for g in q:
            q1.append(g)
        l.append(q1)
    countx = 0
    county = 0

    if m==1:
        for h in range(n):
            if l[h][0]=='.':
                countx+=1

    for row in l:
        flag=0
        for h in range(m-1):

            if row[h] =='.' and row[h+1]=='.'and flag==0:
                county+=1
                flag=1
            elif row[h]=='.' :
                countx+=1
                flag=0
            elif (row[h]=='.' and row[h+1]=='*' ):
                countx+=1
                flag=0
            else:
                flag=0

    ans1=0
    ans2=0
    ans1 = countx*x + 2*county*y
    ans2 = (countx+county)*x
    print(min(ans1,ans2))

#        flag=0
#        row = l[f]
#        previous = row[0]
#        for column in range(1,m):
#            if previous=='.' and row[column]=='.' and flag==0:
#                county+=1
#                flag=1
#            else:
#                flag=0
#                if row[column]=='.':
#                    countx+=1
#            previous = row[column]
#    print(countx,county)
#
#
#


from sys import stdin
t = int(stdin.readline())
#t = int(input())
for _ in range(t):
    n,m,x,y = map(int,stdin.readline().split())
#    n,m,x,y = [int(x) for x in input().split()]
    if y>2*x:
        y=2*x
    ans=0
    for i in range(n):
        l = input()
        flag=0
        for j in range(m):
            if l[j]=='.' and flag==0: #this shows that this . is not included in y
                if j!=m-1 and l[j+1]=='.':
                    ans+=y
                    flag=1
                else:
                    ans+=x
            elif flag==1:
                flag=0
    print(ans)


from sys import stdin
t = int(stdin.readline())
for _ in range(t):
    n,m,x,y = map(int,stdin.readline().split())
    if y>2*x:
        y=2*x
    ans=0
    for i in range(n):
        l = input()
        flag=0
        for j in range(m):
            if l[i]=='.' and flag==0: #this shows that this . is not included in y
                if j!=m-1 and l[j+1]=='.':
                    ans+=y
                    flag=1
                else:
                    ans+=x
            elif flag==1:
                flag=0
    print(ans)


import string
from sys import stdin
t = int(input())
for _ in range(t):
    n,m,x,y = [int(w) for w in input().split()]
    l=[]
    for i in range(n):
        q = input()
        q1=[]
        for g in q:
            q1.append(g)
        l.append(q1)
    countx = 0
    county = 0

    if m==1:
        for h in range(n):
            if l[h][0]=='.':
                countx+=1

    for row in l:
        flag=0
        for h in range(m-1):
            if h==m-2:
                if flag==0 and row[h+1]=='.':
                    countx+=1
            if row[h] =='.' and row[h+1]=='.'and flag==0:
                county+=1
                flag=1
            elif row[h]=='.' :
                countx+=1
                flag=0
            elif (row[h]=='.' and row[h+1]=='*' ):
                countx+=1
                flag=0
            else:
                flag=0

    ans1=0
    ans2=0
    ans1 = countx*x + county*y
    ans2 = ((countx)+2*county)*x
    print(min(ans1,ans2))

#        flag=0
#        row = l[f]
#        previous = row[0]
#        for column in range(1,m):
#            if previous=='.' and row[column]=='.' and flag==0:
#                county+=1
#                flag=1
#            else:
#                flag=0
#                if row[column]=='.':
#                    countx+=1
#            previous = row[column]
#    print(countx,county)
#
#
#


import string
from sys import stdin
t = int(input())
for _ in range(t):
    n,m,x,y = [int(w) for w in input().split()]
    l=[]
    for i in range(n):
        q = input()
        q1=[]
        for g in q:
            q1.append(g)
        l.append(q1)
    countx = 0
    county = 0

    if m==1:
        for h in range(n):
            if l[h][0]=='.':
                countx+=1

    for row in l:
        flag=0
        for h in range(m-1):

            if row[h] =='.' and row[h+1]=='.'and flag==0:
                county+=1
                flag=1
            elif row[h]=='.' and flag==0:
                countx+=1
                flag=0
            elif (row[h]=='.' and row[h+1]=='*' and flag==0):
                countx+=1
                flag=0
            else:
                flag=0

    ans1=0
    ans2=0
    ans1 = countx*x + county*y
    ans2 = (countx+county)*x
    print(min(ans1,ans2))

#        flag=0
#        row = l[f]
#        previous = row[0]
#        for column in range(1,m):
#            if previous=='.' and row[column]=='.' and flag==0:
#                county+=1
#                flag=1
#            else:
#                flag=0
#                if row[column]=='.':
#                    countx+=1
#            previous = row[column]
#    print(countx,county)
#
#
#


import string
from sys import stdin
t = int(input())
for _ in range(t):
    n,m,x,y = [int(w) for w in input().split()]
    l=[]
    for i in range(n):
        q = input()
        q1=[]
        for g in q:
            q1.append(g)
        l.append(q1)
    countx = 0
    county = 0

    if m==1:
        for h in range(n):
            if l[h][0]=='.':
                countx+=1

    for row in l:
        flag=0
        for h in range(m-1):

            if row[h] =='.' and row[h+1]=='.'and flag==0:
                county+=1
                flag=1
            elif row[h]=='.' :
                countx+=1
                flag=0
            elif (row[h]=='.' and row[h+1]=='*' ):
                countx+=1
                flag=0
            else:
                flag=0

    ans1=0
    ans2=0
    ans1 = countx*x + county*y
    ans2 = ((countx)+2*county)*x
    print(min(ans1,ans2))

#        flag=0
#        row = l[f]
#        previous = row[0]
#        for column in range(1,m):
#            if previous=='.' and row[column]=='.' and flag==0:
#                county+=1
#                flag=1
#            else:
#                flag=0
#                if row[column]=='.':
#                    countx+=1
#            previous = row[column]
#    print(countx,county)
#
#
#


def sol():
    t=int(input())
    for tt in range(t):
        n,m,x,y=map(int,input().split())
        A=[]
        for i in range(n):
            A.append(input())
        #print(A)
        cnt=0
        #continue
        for i in range(n):
            if(m==1):
                if(A[i][0]=='.'):
                    cnt+=x
                else:
                    cnt+=0
                continue
            if(x*2<=y):
                for j in range(m):
                    if(A[i][j]=='.'):
                        cnt+=x
            else:
                A[i]=A[i].replace("..","p")
                for j in range(len(A[i])):
                    if(A[i][j]=='p'):
                        cnt+=y
                    elif(A[i][j]=='.'):
                        cnt+=x
        print(cnt)
if(__name__=='__main__'):
    sol()


def sol():
    t=int(input())
    for tt in range(t):
        n,m,x,y=map(int,input().split())
        A=[]
        for i in range(n):
            A.append(input())
        #print(A)
        cnt=0
        #continue
        for i in range(n):
            if(m==1):
                if(A[i][0]=='.'):
                    cnt+=x
                else:
                    cnt+=0
                continue
            if(x*2<=y):
                for j in range(m):
                    if(A[i][j]=='.'):
                        cnt+=x
            else:
                j=0
                while(j<m-1):
                    print(j)
                    if(A[i][j]==A[i][j+1]=='.'):
                        cnt+=y
                        j+=1
                        break
                    elif(A[i][j]=='.'):
                        cnt+=x
                    j+=1
                    if(j>m-1):
                        break
                if(A[i][m-1]=='.'):
                    if(A[i][m-2]=='*'):
                        cnt+=x
        print(cnt)
if(__name__=='__main__'):
    sol()


def sol():
    t=int(input())
    for tt in range(t):
        n,m,x,y=map(int,input().split())
        A=[]
        for i in range(n):
            A.append(input())
        #print(A)
        cnt=0
        #continue
        for i in range(n):
            if(m==1):
                if(A[i][0]=='.'):
                    cnt+=x
                else:
                    cnt+=0
                continue
            if(x*2<=y):
                for j in range(m):
                    if(A[i][j]=='.'):
                        cnt+=x
            else:
                j=0
                while(j<m-1):
                    #print(j)
                    if(A[i][j]==A[i][j+1]=='.'):
                        cnt+=y
                        j+=1
                        break
                    elif(A[i][j]=='.'):
                        cnt+=x
                    j+=1
                    if(j>m-1):
                        break
                if(A[i][m-1]=='.'):
                    if(A[i][m-2]=='*'):
                        cnt+=x
        print(cnt)
if(__name__=='__main__'):
    sol()


import math
for _ in range(int(input())):
    n,m,x,y=map(int,input().split())
    single,double=0,0
    for _ in range(n):
        a=input()
        a=list(a)
        print(a)
        if len(a)==1 and a[0]==".":
            single+=1
        i=0
        while(i<m-1):
            if a[i]=='.':
              if a[i+1]=='.':
                  double+=1
                  i+=2
              else:
                  single+=1
                  i+=1
            else:
                i+=1
        if (a[m-1]=='.' and a[m-2]!='.'):
            single+=1
    print(single,double)
    singlecost=single*x
    if x<y/2:
        doublecost=double*2*x
    else:
        doublecost=double*y
    print(singlecost+doublecost)


import math
for _ in range(int(input())):
    n,m,x,y=map(int,input().split())
    single,double=0,0
    for _ in range(n):
        a=input()
        a=list(a)
        if len(a)==1 and a[0]==".":
            single+=1
            continue
        elif len(a)==1 and a[0]=="*":
            continue
        i=0
        while(i<m-1):
            if a[i]=='.':
              if a[i+1]=='.':
                  double+=1
                  i+=2
              else:
                  single+=1
                  i+=1
            else:
                i+=1
        if (a[m-1]=='.' and a[m-2]!='.'):
            single+=1
    singlecost=single*x
    if x<y/2:
        doublecost=double*2*x
    else:
        doublecost=double*y
    print(singlecost+doublecost)


import math
for _ in range(int(input())):
    n,m,x,y=map(int,input().split())
    single,double=0,0
    for _ in range(n):
        a=input()
        a=list(a)
        if len(a)==1 and a[0]==".":
            single+=1
        i=0
        while(i<m-1):
            if a[i]=='.':
              if a[i+1]=='.':
                  double+=1
                  i+=2
              else:
                  single+=1
                  i+=1
            else:
                i+=1
        if (a[m-1]=='.' and a[m-2]!='.'):
            single+=1
    singlecost=single*x
    if x<y/2:
        doublecost=double*2*x
    else:
        doublecost=double*y
    print(singlecost+doublecost)


for _ in range(int(input())):
    n,m,x,y=map(int,input().split())
    single,double=0,0
    for _ in range(n):
        a=input()
        a=list(a)
        if len(a)==1 and a[0]==".":
            single+=1
        i=0
        while(i<m-1):
            if a[i]=='.':
              if a[i+1]=='.':
                  double+=1
                  i+=2
              else:
                  single+=1
                  i+=1
            else:
                i+=1
        if (a[m-1]=='.' and a[m-2]!='.'):
            single+=1
    singlecost=single*x
    if x<y//2:
        doublecost=double*2*x
    else:
        doublecost=double*y
    print(singlecost+doublecost)


import math
for _ in range(int(input())):
    n,m,x,y=map(int,input().split())
    single,double=0,0
    for _ in range(n):
        a=input()
        a=list(a)
        for i in range(m):
            if a[i]=='.':
                single+=1
        i=0
        while(i<m-1):
            if a[i]=='.' and a[i+1]=='.':
                double+=1
                i+=2
                single-=2
            else:
                i+=1
    singlecost=single*x
    if x<y/2:
        doublecost=double*2*x
    else:
        doublecost=double*y
    print(singlecost+doublecost)


for _ in range(int(input())):
    n,m,x,y=map(int,input().split())
    single,double=0,0
    for _ in range(n):
        a=input()
        a=list(a)
        i=0
        while(i<m-1):
            if a[i]=='.':
              if a[i+1]=='.':
                  double+=1
                  i+=2
              else:
                  single+=1
                  i+=1
            else:
                i+=1
        if (a[m-1]=='.' and a[m-2]!='.'):
            single+=1
    singlecost=single*x
    if x<y//2:
        doublecost=double*2*x
    else:
        doublecost=double*y
    print(singlecost+doublecost)


import math
for _ in range(int(input())):
    n,m,x,y=map(int,input().split())
    single,double=0,0
    for _ in range(n):
        a=input()
        a=list(a)
        if len(a)==1 and a[0]==".":
            single+=1
        elif len(a)==1 and a[0]=="*":
            continue
        i=0
        while(i<m-1):
            if a[i]=='.':
              if a[i+1]=='.':
                  double+=1
                  i+=2
              else:
                  single+=1
                  i+=1
            else:
                i+=1
        if (a[m-1]=='.' and a[m-2]!='.'):
            single+=1
    singlecost=single*x
    if x<y/2:
        doublecost=double*2*x
    else:
        doublecost=double*y
    print(singlecost+doublecost)


def min_cost(n,m,x,y, arr):
    cost = 0
    for i in range(n):
        j = 0
        while j < m:
            if arr[i][j] == '.':
                next = j+1
                if next<m and arr[i][next] == '.':
                    j = j+2
                    cost1 = 2*x
                    cost2 = y
                    cost += min(cost1, cost2)
                else:
                    cost += x
                    j = j+1
            j += 1
    return cost

if __name__ == "__main__":
    # import ipdb
    # ipdb.set_trace()
    T = int(input())
    for t in range(T):
        numbers = list(map(int, input().split()))
        n, m, x, y = numbers[0], numbers[1], numbers[2], numbers[3]
        mat = []
        for i in range(n):
            mat.append(input())
        print(mat)
        ans = min_cost(n,m,x,y, mat)
        print(ans)


def min_cost(n,m,x,y, arr):
    cost = 0
    if x>=y:
        for i in range(n):
            j = 0
            while j<m:
                if arr[i][j] == '.':
                    next = j+1
                    if next<m and arr[i][next] == '.':
                        j = j+2
                        cost += y
                    else:
                        cost += x
                        j = j+1
                j += 1
    else:
        for i in range(n):
            for j in range(m):
                if arr[i][j] == '.':
                    cost += x
    return cost

if __name__ == "__main__":
    # import ipdb
    # ipdb.set_trace()
    T = int(input())
    for t in range(T):
        numbers = list(map(int, input().split()))
        n, m, x, y = numbers[0], numbers[1], numbers[2], numbers[3]
        mat = []
        for i in range(n):
            mat.append(input())
        #print(mat)
        ans = min_cost(n,m,x,y, mat)
        print(ans)


def min_cost(n,m,x,y, arr):
    cost = 0
    for i in range(n):
        j = 0
        while j < m:
            if arr[i][j] == '.':
                next = j+1
                if next<m and arr[i][next] == '.':
                    j = j+2
                    cost1 = 2*x
                    cost2 = y
                    cost += min(cost1, cost2)
                else:
                    cost += x
                    j = j+1
            j += 1
    return cost

if __name__ == "__main__":
    # import ipdb
    # ipdb.set_trace()
    T = int(input())
    for t in range(T):
        numbers = list(map(int, input().split()))
        n, m, x, y = numbers[0], numbers[1], numbers[2], numbers[3]
        mat = []
        for i in range(n):
            mat.append(input())
        #print(mat)
        ans = min_cost(n,m,x,y, mat)
        print(ans)


def min_cost(n,m,x,y, arr):
    cost = 0
    for i in range(n):
        j = 0
        while j < m:
            if arr[i][j] == '.':
                next = j+1
                if next < m and arr[i][next] == '.':
                    j = j+2
                    cost1 = 2*x
                    cost2 = y
                    cost += min(cost1, cost2)
                    continue
                cost += x
                j = j+1
            else:
                j += 1
    return cost

if __name__ == "__main__":
    # import ipdb
    # ipdb.set_trace()
    T = int(input())
    for t in range(T):
        numbers = list(map(int, input().split()))
        n, m, x, y = numbers[0], numbers[1], numbers[2], numbers[3]
        mat = []
        for i in range(n):
            mat.append(input())
        #print(mat)
        ans = min_cost(n,m,x,y, mat)
        print(ans)


def min_cost(n,m,x,y, arr):
    cost = 0
    if x>=y:
        for i in range(n):
            j = 0
            while j<m:
                if arr[i][j] == '.':
                    next = j+1
                    if next<m and arr[i][next] == '.':
                        j = j+2
                        cost += y
                    else:
                        cost += x
                        j = j+1
                j += 1
    else:
        for i in range(n):
            for j in range(m):
                if arr[i][j] == '.':
                    cost += x
    return cost

if __name__ == "__main__":
    # import ipdb
    # ipdb.set_trace()
    T = int(input())
    for t in range(T):
        numbers = list(map(int, input().split()))
        n, m, x, y = numbers[0], numbers[1], numbers[2], numbers[3]
        mat = []
        for i in range(n):
            mat.append(input())
        print(mat)
        ans = min_cost(n,m,x,y, mat)
        print(ans)


t=int(input())
for i in range(t):
    a,b,c,d=map(int,input().split())
    l=[]
    for i in range(a):
        l.append(list(input()))
    x=0

    for i in range(a):
        for j in range(b):
            if(j!=b-1)and(l[i][j]=='.')and(l[i][j+1]=='.')and(c>=d):
                l[i][j+1]='*'
                x=x+d
                l[i][j]='*'
            elif(l[i][j]=='.'):
                    x=x+c
    print(x)


t=int(input())
for i in range(t):
    a,b,c,d=map(int,input().split())
    l=[]
    for i in range(a):
        l.append(list(input()))
    x=0
    for i in range(a):
        for j in range(b):
            if(j!=b-1)and(l[i][j]=='.')and(l[i][j+1]=='.')and(c>d):
                l[i][j+1]='*'
                x=x+d
            elif(l[i][j]=='.'):
                    x=x+c
    print(x)


t=int(input())
for i in range(t):
    a,b,c,d=map(int,input().split())
    l=[]
    for i in range(a):
        l.append(list(input()))
    x=0

    for i in range(a):
        for j in range(b):
            if(j!=b-1)and(l[i][j]=='.')and(l[i][j+1]=='.')and(2*c>d):
                l[i][j+1]='*'
                x=x+d
                l[i][j]='*'
            elif(j!=b-1)and(l[i][j]=='.')and(l[i][j+1]=='.')and(2*c<d):
                l[i][j]='*'
                l[i][j+1]='*'
                x=x+2*c
            elif(l[i][j]=='.'):
                    x=x+c
    print(x)


t=int(input())
for i in range(t):
    a,b,c,d=map(int,input().split())
    if(2*c<d):
        d=2*c
    l=[]
    for i in range(a):
        l.append(list(input()))
    x=0

    for i in range(a):
        for j in range(b):
            if(l[i][j]=='.'):
                if(j+1<b and l[i][j+1]=='.'):
                    x+=d
                    l[i][j+1]='*';
                else:
                    x+=c
                    l[i][j]='*'
    print(x)


import math
for i in range(int(input())):

    n, m, x, y = list(map(int, input().split()))

    rows = []
    for _ in range(n):
        rows.append(list(input()))
    # print(rows)
    price = 0
    if x <= y/2:
        for row in rows:
            for c in row:
                if c==".":
                    price += x

    else:
        for i  in range(n):
            for j in range(m):

                if rows[i][j] == "." and rows[i][j+1]==".":
                    price += y
                    rows[i][j] = "*"
                    rows[i][j+1]="*"
        # print(rows)
        for row in rows:
            for c in row:
                if c==".":
                    price += x
    print(price)


import math
for i in range(int(input())):

    n, m, x, y = list(map(int, input().split()))

    rows = []
    for _ in range(n):
        rows.append(list(input()))
    # print(rows)
    price = 0
    if x <= y/2:
        for row in rows:
            for c in row:
                if c==".":
                    price += x

    else:
        for i  in range(n):
            for j in range(m-1):

                if rows[i][j] == "." and rows[i][j+1]==".":
                    price += y
                    rows[i][j] = "*"
                    rows[i][j+1]="*"
        # print(rows)
        for row in rows:
            for c in row:
                if c==".":
                    price += x
    print(price)


import math
for i in range(int(input())):

    n, m, x, y = list(map(int, input().split()))

    rows = []
    for _ in range(n):
        rows.append(list(input()))
    print(rows)
    price = 0
    if x <= y/2:
        for row in rows:
            for c in row:
                if c==".":
                    price += x

    else:
        for i  in range(n):
            for j in range(m-1):

                if rows[i][j] == "." and rows[i][j+1]==".":
                    price += y
                    rows[i][j] = "*"
                    rows[i][j+1]="*"
        print(rows)
        for row in rows:
            for c in row:
                if c==".":
                    price += x
    print(price)


import math
for i in range(int(input())):

    n, m, x, y = list(map(int, input().split()))

    rows = []
    for _ in range(n):
        rows.append(list(input()))
    print(rows)
    price = 0
    if x <= y/2:
        for row in rows:
            for c in row:
                if c==".":
                    price += x

    else:
        for i  in range(n):
            for j in range(m):

                if rows[i][j] == "." and rows[i][j+1]==".":
                    price += y
                    rows[i][j] = "*"
                    rows[i][j+1]="*"
        print(rows)
        for row in rows:
            for c in row:
                if c==".":
                    price += x
    print(price)


n=int(input())

for i in range(n):
	a,b,x,y=map(int,input().split())
	c=[]
	for j in range(a):
		c.append(str(input()))
	cost=0
	for j in range(a):
		h=0
		f=0
		for k in range(b):
			if(c[j][k]=='*'):
				h=h+f
				cost1=int(h/2)*y+(h%2)*x
				cost2=h*x
				cost=cost+min(cost1,cost2)
				f=0
				h=0
			else:
				f=f+1
		if(f!=0):
			cost1=int(f/2)*y+(f%2)*x
			cost2=f*x
			cost=cost+min(cost1,cost2)

	print(cost)


n=int(input())

for i in range(n):
	a,b,x,y=map(int,input().split())
	c=[]
	for j in range(a):
		c.append(str(input()))
	if(x>=y):
		s=0
	else:
		s=1
	cost=0
	for j in range(a):
		h=0
		f=0
		for k in range(b):
			if(c[j][k]=='*'):
				h=h+f
				if(s==0):
					cost=cost+int(h/2)*y+(h%2)*x
				else:
					cost=cost+h*x
				f=0
				h=0
			else:
				f=f+1
		if(f!=0):
			if(s==0):
				cost=cost+int(f/2)*y+(f%2)*x
			else:
				cost=cost+f*x

	print(cost)


n=int(input())

for i in range(n):
	a,b,x,y=map(int,input().split())
	c=[]
	for j in range(a):
		c.append(str(input()))
	if(x>=y):
		s=0
	else:
		s=1
	cost=0
	for j in range(a):
		h=0
		f=0
		for k in range(b):
			if(c[j][k]=='*'):
				h=h+f
				cost1=int(h/2)*y+(h%2)*x
				cost2=cost+h*x
				cost=cost+min(cost1,cost2)
				f=0
				h=0
			else:
				f=f+1
		if(f!=0):
			cost1=int(f/2)*y+(f%2)*x
			cost2=f*x
			cost=cost+min(cost1,cost2)

	print(cost)


for z in range(int(input())):
    n,m,x,y = list(map(int, input().split()))
    ans=0
    for i in range(n):
        s=input()
        if(2*x<=y):
            for j in range(m):
                if(s[j]=="."):
                    ans+=x
        else:
            if(m!=1):
                if(s[0]=="." and s[1]=="."):
                    ans+=y
                elif(s[0]=="."):
                    ans+=x
                if(s[m-1]=="." and s[n-1]!="."):
                    ans+=x
            else:
                if(s[0]=="."):
                    ans+=x
            for j in range(1,m-1):
                if(s[j]=="." and s[j+1]=="."):
                    ans+=y
                elif(s[j]=="." and s[j-1]!="."):
                    ans+=x
    print(ans)


for z in range(int(input())):
    n,m,x,y = list(map(int, input().split()))
    ans=0
    for i in range(n):
        s=input()
        if(2*x<=y):
            for j in range(m):
                if(s[j]=="."):
                    ans+=x
        else:
            if(m!=1):
                if(s[0]=="." and s[1]=="."):
                    ans+=y
                elif(s[0]=="."):
                    ans+=x
                if(s[m-1]=="." and s[m-2]!="."):
                    ans+=x
            else:
                if(s[0]=="."):
                    ans+=x
            for j in range(1,m-1):
                if(s[j]=="." and s[j+1]=="."):
                    ans+=y
                elif(s[j]=="." and s[j-1]!="."):
                    ans+=x
    print(ans)


for z in range(int(input())):
    n,m,x,y = list(map(int, input().split()))
    ans=0
    for i in range(n):
        s=input()
        array=[]
        for k in range(len(s)):
            array.append(s[k])
        if(2*x<=y):
            for j in range(m):
                if(array[j]=="."):
                    ans+=x
        else:
            for j in range(m-1):
                if(array[j]=="." and array[j+1]=="."):
                    ans+=y
                    array[j]="*"
                    array[j+1]="*"
                elif(array[j]=="."):
                    ans+=x
            if(array[m-1]=="."):
                ans+=x
    print(ans)


for z in range(int(input())):
    n,m,x,y = list(map(int, input().split()))
    ans=0
    for i in range(n):
        s=input()
        if(2*x<=y):
            for j in range(m):
                if(s[j]=="."):
                    ans+=x
        else:
            if(m!=1):
                if(s[0]=="." and s[1]=="."):
                    ans+=y
                elif(s[0]=="."):
                    ans+=x
                if(s[m-1]=="." and s[m-1]!="."):
                    ans+=x
            else:
                if(s[0]=="."):
                    ans+=x
            for j in range(1,m-1):
                if(s[j]=="." and s[j+1]=="."):
                    ans+=y
                elif(s[j]=="." and s[j-1]!="."):
                    ans+=x
    print(ans)


t=int(input())
for _ in range(0,t):
    n,m,x,y=map(int,input().strip().split(" "))
    arr=[]
    for i in range(0,n):
        arr.append(str(input()))

    ans=0

    for i in range(0,n):
        j=0
        while j<m:
            if j+1<m and arr[i][j]==arr[i][j+1]=='.':
                ans+=min(2*x,y)
                j+=1

            elif arr[i][j]=='.':
                ans+=x
            j+=1
    print(ans)


t=int(input())
for _ in range(0,t):
    n,m,x,y=map(int,input().strip().split(" "))
    arr=[]
    for i in range(0,n):
        arr.append(str(input()))

    ans=0

    if 2*x<=y:
        c=1    #Use 1
    else:
        c=0    #Use 2

    for i in range(0,n):
        j=0
        while j<m:
            if j+1<m and arr[i][j]==arr[i][j+1]=='.':
                ans+=min(2*x,y)

            elif arr[i][j]=='.':
                ans+=x
            j+=1
    print(ans)


t=int(input())
for _ in range(0,t):
    n,m,x,y=map(int,input().strip().split(" "))
    arr=[]
    for i in range(0,n):
        arr.append(str(input()))

    ans=0

    if 2*x<=y:
        c=1    #Use 1
    else:
        c=0    #Use 2

    if c==1:
        for i in range(0,n):
            for j in range(0,m):
                if arr[i][j]=='.':
                    ans+=x

        print(ans)

    else:
        i=0

        if m==1:
            for i in range(0,n):
                if arr[i]=='.':
                    ans+=x
        else:
            while i<n:
                j=0
                while j+1<m:

                    if arr[i][j]==arr[i][j+1] and arr[i][j]=='.':
                        ans+=y
                        j+=2

                    elif arr[i]=='.':
                        ans+=x
                        j+=1

                    else:
                        j+=1

                if j+1==m:
                    if arr[i][j]=='.':
                        ans+=x
                i+=1

        print(ans)


t=int(input())
for _ in range(0,t):
    n,m,x,y=map(int,input().strip().split(" "))
    arr=[]
    for i in range(0,n):
        arr.append(str(input()))

    ans=0

    if 2*x<y:
        c=1    #Use 1
    else:
        c=0    #Use 2

    if c==1:
        for i in range(0,n):
            for j in range(0,m):
                if arr[i][j]=='.':
                    ans+=x

        print(ans)

    else:
        i=0
        j=0

        if m==1:
            for i in range(0,n):
                if arr[i]=='.':
                    ans+=x
        else:
            while i<=n:
                while j<n:
                    if arr[i][j]==arr[i][j+1]=='.':
                        ans+=y
                        j+=2

                    elif arr[i]=='.':
                        ans+=x
                        j+=1
                i+=1

        print(ans)


def solve
  n, m, x, y = gets.strip.split(' ').map(&:to_i)
  an = 0
  n.times {
    str = gets.strip.split('')
    count = 0
    str.each_with_index { |e, i|
      if e == '.' && i < str.size - 1
        count += 1
      else
        count += 1 if e == '.'
        two = (count / 2).floor
        if two * y < two * 2 * x && !two.zero?
          an += (two * y)
        else
          an += (two * 2 * x)
        end
        an += x if count.odd?
        count = 0
      end
    }
  }
  puts an
end

gets.strip.to_i.times { solve }


def solve
  n, m, x, y = gets.strip.split(' ').map(&:to_i)
  an = 0
  n.times {
    str = gets.strip.split('')
    count = 0
    str.each_with_index { |e, i|
      if e == '.' && i < str.size - 1
        count += 1
      else
        count += 1 if e == '.'
        two = (count / 2).floor
        if two * y < two * 2 * x && !two.zero?
          an += (two * y)
        else
          an += (two * 2 * x
        end
        an += x if count.odd?
        count = 0
      end
    }
  }
  puts an
end

gets.strip.to_i.times { solve }


def solve
  n, m, x, y = gets.strip.split(' ').map(&:to_i)
  an = 0
  n.times {
    str = gets.strip.split('')
    count = 0
    str.each_with_index { |e, i|
      if e == '.' && i < str.size - 1
        count += 1
      else
        count += 1 if e == '.'
        two = (count / 2).floor
        if two * y < two * 2 * x && !two.zero?
          an += (two * y)
        else
          an += (two * 2 * x)
          an += x if count.odd?
        end
        count = 0
      end
    }
  }
    puts an
end

gets.strip.to_i.times { solve }


def solve
  n, m, x, y = gets.strip.split(' ').map(&:to_i)
  an = 0
  n.times {
    str = gets.strip.split('')
    count = 0
    str.each_with_index { |e, i|
      if e == '.' && i < str.size - 1
        count += 1
      else
        count += 1 if e == '.'
        two = (count / 2).to_i
        if two * y < count * x && !two.zero?
          an += (two * y)
        else
          an += (count * x)
        end
        count = 0
      end
    }
  }
    puts an
end

gets.strip.to_i.times { solve }


def solve
  n, m, x, y = gets.strip.split(' ').map(&:to_i)
  an = 0
  n.times {
    str = gets.strip.split('')
    count = 0
    str.each_with_index { |e, i|
      if e == '.' && i < str.size - 1
        count += 1
      else
        count += 1 if e == '.'
        two = (count / 2).to_i
        if two * y < two * 2 * x && !two.zero?
          an += (two * y)
        else
          an += (two * 2 * x)
          an += x if count.odd?
        end
        count = 0
      end
    }
  }
    puts an
end

gets.strip.to_i.times { solve }


def solve
  n, m, x, y = gets.strip.split(' ').map(&:to_i)
  an = 0
  n.times {
    str = gets.strip.split('')
    count = 0
    p str
    str.each_with_index { |e, i|
      if e == '.' && i < str.size - 1
        count += 1
      else
        count += 1 if e == '.'
        two = (count / 2).to_i
        if two * y < count * x && !two.zero?
          an += (two * y)
        else
          an += (count * x)
        end
        count = 0
      end
    }
  }
    puts an
end

gets.strip.to_i.times { solve }


  q = gets.chomp.to_i

  q.times {

    n, m, x, y = gets.split.map(&:to_i)

    table = []
    n.times {
      row = gets.chomp
      table << row
    }

    d = []
    n.times { |i|
      d << []
      m.times {
        d[i] << 0
      }
    }

    n.times { |i|
      m.times { |j|

        if j == 0

          if table[i][j] == '.'
            d[i][j] = x
          end

          next
        end

        d[i][j] = d[i][j - 1]

        if table[i][j] == '*'
          next
        end

        d[i][j] = d[i][j - 1] + x

        if table[i][j - 1] == '.'
          curVal = 0
          if j == 1
            curVal = y
          else
            curVal = d[i][j - 2] + yield
          end

          d[i][j] = [d[i][j], curVal].min
        end
      }
    }

    sum = 0
    d.each { |row|
      sum += row.last
    }

    puts sum
  }