import java.io.*;
import java.util.*;

public class Main {
    static MyReader in = new MyReader();

    public static void main(String[] args) {
        int N = in.i();
        char[] s = new char[10];

        int ans = 0;
        int A = 0;
        int B = 0;
        int AB = 0;
        for (int i = 0; i < N; i++) {
            int n = in.read(s);

            boolean readA = false;
            for (int j = 0; j < n; j++) {
                if (readA && s[j] == 'B') ans++;
                readA = s[j] == 'A';
            }

            boolean tailA = s[n - 1] == 'A';
            boolean headB = s[0] == 'B';
            if (tailA && headB) AB++;
            else if (tailA) A++;
            else if (headB) B++;
        }

        ans += AB + Math.min(A, B) + Math.min(A + B - 1, 0);
        System.out.println(ans);
    }
}

class MyReader extends BufferedReader {
    char[] cbuf = new char[1024];
    int head = 0;
    int tail = 0;

    MyReader() {
        super(new InputStreamReader(System.in));
    }

    char next() {
        if (head == tail) {
            try {
                tail = super.read(cbuf, 0, cbuf.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            head = 0;
        }
        return cbuf[head++];
    }

    int i() {
        int k = next() - '0';
        boolean minus = k == -3;
        int n = minus ? 0 : k;
        while (0 <= (k = next() - '0') && k <= 9) n = 10 * n + k;
        return minus ? -n : n;
    }

    int[] ii(final int N) {
        int[] a = new int[N];
        for (int j = 0; j < a.length; j++) a[j] = i();
        return a;
    }

    long l() {
        int k = next() - '0';
        boolean minus = k == -3;
        long n = minus ? 0 : k;
        while (0 <= (k = next() - '0') && k <= 9) n = 10 * n + k;
        return minus ? -n : n;
    }

    char[] s(final int N) {
        char[] s = new char[N];
        for (int i = 0; i < N; i++) {
            s[i] = next();
        }
        next();
        return s;
    }

    public int read(char[] cbuf) {
        int i;
        char c;
        for (i = 0; (c = next()) != ' ' && c != '\n'; i++) cbuf[i] = c;
        return i;
    }

    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {
    static MyReader in = new MyReader();

    public static void main(String[] args) {
        int N = in.i();
        char[][] s = new char[N][10];
        int[] n = new int[N];
        for (int i = 0; i < N; i++) {
            n[i] = in.read(s[i]);
        }
        int ans = 0;
        int A = 0;
        int B = 0;
        int AB = 0;
        for (int i = 0; i < N; i++) {
            boolean a = s[i][n[i] - 1] == 'A';
            boolean b = s[i][0] == 'B';
            if (a && b) {
                AB++;
            } else if (a) {
                A++;
            } else if (b) {
                B++;
            }
            char[] si = s[i];
            boolean f = false;
            for (int j = 0; j < n[i]; j++) {
                if (si[j] == 'A') {
                    f = true;
                } else if (f && si[j] == 'B') {
                    ans++;
                    f = false;
                } else {
                    f = false;
                }
            }
        }
        if (AB > 0) {
            ans += AB - 1;
            A++;
            B++;
        }
        ans += Math.min(A, B);
        System.out.println(ans);
    }
}

class MyReader extends BufferedReader {
    char[] cbuf = new char[1024];
    int head = 0;
    int tail = 0;

    MyReader() {
        super(new InputStreamReader(System.in));
    }

    char next() {
        if (head == tail) {
            try {
                tail = super.read(cbuf, 0, cbuf.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            head = 0;
        }
        return cbuf[head++];
    }

    int i() {
        int k = next() - '0';
        boolean minus = k == -3;
        int n = minus ? 0 : k;
        while (0 <= (k = next() - '0') && k <= 9) n = 10 * n + k;
        return minus ? -n : n;
    }

    int[] ii(final int N) {
        int[] a = new int[N];
        for (int j = 0; j < a.length; j++) a[j] = i();
        return a;
    }

    long l() {
        int k = next() - '0';
        boolean minus = k == -3;
        long n = minus ? 0 : k;
        while (0 <= (k = next() - '0') && k <= 9) n = 10 * n + k;
        return minus ? -n : n;
    }

    char[] s(final int N) {
        char[] s = new char[N];
        for (int i = 0; i < N; i++) {
            s[i] = next();
        }
        next();
        return s;
    }

    public int read(char[] cbuf) {
        int i;
        char c;
        for (i = 0; (c = next()) != ' ' && c != '\n'; i++) cbuf[i] = c;
        return i;
    }

    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }
}


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <functional>
#define SIZE 10005

using namespace std;
typedef long long int ll;
typedef pair <int,int> P;

char str[SIZE];

int main()
{
	int n;
	scanf("%d",&n);
	int cnt=0;
	int a=0,b=0,ba=0;
	for(int i=0;i<n;i++)
	{
		scanf("%s",&str);
		int L=strlen(str);
		for(int j=0;j+1<L;j++)
		{
			if(str[j]=='A'&&str[j+1]=='B')
			{
				cnt++;
			}
		}
		if(str[0]=='B') b++;
		if(str[L-1]=='A') a++;
		if(str[0]=='B'&&str[L-1]=='A') ba++;
	}
	cnt+=min(a,b);
	if(a==ba&&b==ba&&b>0) cnt--;
	printf("%d\n",cnt);
	return 0;
}


#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>

using namespace std;

using ll=long long;
using vi=vector<int>;
using vvi=vector<vi>;
using pii=pair<int,int>;
using vll=vector<ll>;
using vvll=vector<vll>;

int main(void)
{
	int n;

	while(scanf("%d\n", &n)==1)
	{
		int ab=0, b_front=0, a_back=0, bf_ab=0;
		for(int i=0;i<n;i++)
		{
			char s[10+2];
			scanf("%10s", s);

			int l=strlen(s);
			if(s[0]=='B') b_front++;
			if(s[l-1]=='A') a_back++;
			if(s[0]=='B' && s[l-1]=='A') bf_ab++;
			for(int j=1;j<l;j++)
			{
				if(s[j]=='B')
				{
					if(s[j-1]=='A') ab++;
				}
			}
		}
//		printf("ab=%d a_back=%d b_front=%d\n", ab, a_back, b_front);
		int ans=ab+min(a_back, b_front);
		if(bf_ab>0 && bf_ab==a_back && bf_ab==b_front) ans--;
		printf("%d\n", ans);
	}
	return 0;
}


#include <bits/stdc++.h>

//#include <atcoder/all>

using namespace std;
// using namespace atcoder;
using ll = long long;

int main() {
  int n;
  int ba = 0, _a = 0, b_ = 0;
  int in = 0;
  cin >> n;

  for (int i = 0; i < n; i++) {
    string s;
    cin >> s;
    if (s.find("AB") != string::npos) {
      in++;
    }

    if (s.front() == 'B' && s.back() == 'A') {
      ba++;
    } else {
      if (s.front() == 'B') {
        b_++;
      }
      if (s.back() == 'A') {
        _a++;
      }
    }
  }

  if (_a == 0 && b_ == 0) {
    cout << in + max(ba - 1, 0) << endl;
  } else {
    cout << in + ba + min(_a, b_) << endl;
  }
}


#include <bits/stdc++.h>

//#include <atcoder/all>

using namespace std;
// using namespace atcoder;
using ll = long long;

int main() {
  int n;
  int ba = 0, _a = 0, b_ = 0;
  int in = 0;
  cin >> n;

  for (int i = 0; i < n; i++) {
    string s;
    cin >> s;
    if (s.find("AB") != string::npos) {
      in++;
    }

    if (s.front() == 'B' && s.back() == 'A') {
      ba++;
    } else {
      if (s.front() == 'B') {
        b_++;
      } else if (s.back() == 'A') {
        _a++;
      }
    }
  }

  if (_a == 0 && b_ == 0) {
    cout << in + max(ba - 1, 0) << endl;
  } else {
    cout << in + ba + min(_a, b_) << endl;
  }
}


#include <bits/stdc++.h>

//#include <atcoder/all>

using namespace std;
// using namespace atcoder;
using ll = long long;

int main() {
  int n;
  int ba = 0, _a = 0, b_ = 0;
  int in = 0;
  cin >> n;

  for (int i = 0; i < n; i++) {
    string s;
    cin >> s;
    if (s.find("AB") != string::npos) {
      in++;
    }

    if (s.front() == 'B' && s.back() == 'A') {
      ba++;
    } else if (s.front() == 'B') {
      b_++;
    } else if (s.back() == 'A') {
      _a++;
    }
  }

  if (_a == 0 && b_ == 0) {
    cout << in + max(ba - 1, 0) << endl;
  } else {
    cout << in + ba + min(_a, b_) << endl;
  }
}


#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif

#define getchar getchar_unlocked
#define putchar putchar_unlocked
int32_t nextint(void){ char c=getchar_unlocked(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar_unlocked(); bool s=false; if(c=='-'){s=true;c=getchar_unlocked();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar_unlocked(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar_unlocked(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar_unlocked(); int s=0; if(c=='-'){s=1;c=getchar_unlocked();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar_unlocked(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar_unlocked(); while(c==' '||c=='\n') c=getchar_unlocked(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar_unlocked(); } *s='\0'; return len; }

char s[11];
int main(void){
	int n=nextint();
	int a=0, b=0, c=0, d=0;
	for(int i=0; i<n; i++){
		int l=nextstr(s);
		a+=(s[0]=='B');
		b+=(s[l-1]=='A');
		d+=(s[0]=='B'&&s[l-1]=='A');
		for(int j=0; j<l-1; j++){
			if(s[j]=='A' && s[j+1]=='B') c++;
		}
	}
	int ans=c;
	if(a>b){
		ans+=b;
	}else if(a<b){
		ans+=a;
	}else{
		if(a>0){
			ans+=a-(a==d);
		}
	}
	printf("%d\n", ans);
}


#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 内部変数
static FILE *szpFpI;											// 入力

// 内部変数 - テスト用
#ifdef D_TEST
	static int siRes;
	static FILE *szpFpA;
	static int siTNo;
#endif

// 出力
int
fOut(
	char *pcpLine				// <I> １行
)
{
	char lc1Buf[1024];

#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, pcpLine)) {
		siRes = -1;
	}
#else
	printf("%s", pcpLine);
#endif

	return 0;
}

// 改行カット
// 戻り値：文字数
int
fCutCrLf(
	char *pcpStr				// <I> 文字列
)
{
	int i;

	for (i = 0; pcpStr[i] != '\0'; i++) {
		if (pcpStr[i] == '\n') {
			pcpStr[i] = '\0';
			break;
		}
	}

	return i;
}

// 実行メイン
int
fMain(
)
{
	int i, j;
	char lc1Buf[1024];

	// 文字列数 - 取得
	int liSCnt;
	fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
	sscanf(lc1Buf, "%d", &liSCnt);

	// 文字列 - 取得
	int liABCnt = 0;
	int liBCnt = 0;
	int liACnt = 0;
	int liBACnt = 0;
	for (i = 0; i < liSCnt; i++) {
		fgets(lc1Buf, sizeof(lc1Buf), szpFpI);

		// 改行カット
		int liLen = fCutCrLf(lc1Buf);

		// 文字列内のAB数
		for (j = 0; j < liLen - 1; j++) {
			if (lc1Buf[j] == 'A') {
				if (lc1Buf[j + 1] == 'B') {
					liABCnt++;
				}
			}
		}

		// 文字列種類
		if (lc1Buf[0] == 'B') {
			if (lc1Buf[liLen - 1] == 'A') {
				liBACnt++;
			}
			else {
				liBCnt++;
			}
		}
		else {
			if (lc1Buf[liLen - 1] == 'A') {
				liACnt++;
			}
		}
	}

	// BA文字列を連結
	if (liBACnt > 0) {
		liABCnt += liBACnt - 1;

		// 連結
		if (liACnt > 0) {
			liABCnt++;
		}
		else if (liBCnt > 0) {
			liABCnt++;
		}
	}

	// B文字列とA文字列を連結
	if (liACnt < liBCnt) {
		liABCnt += liACnt;
	}
	else {
		liABCnt += liBCnt;
	}

	return liABCnt;
}

// １回実行
int
fOne(
)
{
	int liRet;
	char lc1Buf[1024];

	// 入力 - セット
#ifdef D_TEST
	sprintf(lc1Buf, ".\\Test\\T%d.txt", siTNo);
	szpFpI = fopen(lc1Buf, "r");
	sprintf(lc1Buf, ".\\Test\\A%d.txt", siTNo);
	szpFpA = fopen(lc1Buf, "r");
	siRes = 0;
#else
	szpFpI = stdin;
#endif

	// 実行メイン
	liRet = fMain();

	// 出力
	sprintf(lc1Buf, "%d\n", liRet);
	fOut(lc1Buf);

	// 残データ有無
#ifdef D_TEST
	lc1Buf[0] = '\0';
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, "")) {
		siRes = -1;
	}
#endif

	// テストファイルクローズ
#ifdef D_TEST
	fclose(szpFpI);
	fclose(szpFpA);
#endif

	// テスト結果
#ifdef D_TEST
	if (siRes == 0) {
		printf("OK %d\n", siTNo);
	}
	else {
		printf("NG %d\n", siTNo);
	}
#endif

	return 0;
}

// プログラム開始
int
main()
{

#ifdef D_TEST
	int i;
	for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
		siTNo = i;
		fOne();
	}
#else
	fOne();
#endif

	return 0;
}


#include<stdio.h>
int MIN(int a,int b){return a<b?a:b;}
int main(){
  int n,i,j,c=0,d,b[4]={};
  char s[100010];
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%s",s);
    for(j=d=0;s[j+1];j++){
      if(s[j]=='A'&&s[j+1]=='B')c++;
    }
    if(s[0]=='B')d+=1;
    if(s[j]=='A')d+=2;
    b[d]++;
  }
  if(b[3]&&b[1]+b[2]==0)b[3]--;
  printf("%d\n",c+MIN(b[1],b[2])+b[3]);
  return 0;
}


#include <stdio.h>

int main(void) {
	int N;
	int i;
	int a = 0, b = 0, ab = 0, ba = 0;
	int kitaeri;
	if (scanf("%d", &N) != 1) return 1;
	for (i = 0; i < N; i++) {
		char s[16];
		int j;
		if (scanf("%15s", s) != 1) return 1;
		if (s[0] == 'B') b++;
		for (j = 0; s[j] != '\0'; j++) {
			if (s[j] == 'A' && s[j + 1] == 'B') ab++;
			if (s[j] == 'A' && s[j + 1] == '\0') {
				a++;
				if (s[0] == 'B') ba++;
			}
		}
	}
	kitaeri = a <= b ? a : b;
	printf("%d\n", ab + (a == ba && b == ba ? kitaeri - 1 : kitaeri));
	return 0;
}


#include <stdio.h>

int main(void) {
	int N;
	int i;
	int a = 0, b = 0, ab = 0, ba = 0;
	int kitaeri;
	if (scanf("%d", &N) != 1) return 1;
	for (i = 0; i < N; i++) {
		char s[16];
		int j;
		if (scanf("%15s", s) != 1) return 1;
		if (s[0] == 'B') b++;
		for (j = 0; s[j] != '\0'; j++) {
			if (s[j] == 'A' && s[j + 1] == 'B') ab++;
			if (s[j] == 'A' && s[j + 1] == '\0') {
				a++;
				if (s[0] == 'B') ba++;
			}
		}
	}
	kitaeri = a <= b ? a : b;
	printf("%d\n", ab + (kitaeri == ba ? kitaeri - 1 : kitaeri));
	return 0;
}


#include <stdio.h>

int main(void) {
	int N;
	int i;
	int a = 0, b = 0, ab = 0;
	int kitaeri;
	if (scanf("%d", &N) != 1) return 1;
	for (i = 0; i < N; i++) {
		char s[16];
		int j;
		if (scanf("%15s", s) != 1) return 1;
		if (s[0] == 'B') b++;
		for (j = 0; s[j] != '\0'; j++) {
			if (s[j] == 'A' && s[j + 1] == 'B') ab++;
			if (s[j] == 'A' && s[j + 1] == '\0') a++;
		}
	}
	kitaeri = a <= b ? a : b;
	printf("%d\n", ab + (kitaeri == N ? N -1 : kitaeri));
	return 0;
}


inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')
N = inp.shift() * 1
a = 0
b = 0
ab = 0
c = 0
for (i=0; i<N; i++) {
    s = inp[i]
    if (s[0] == 'B' && s[s.length - 1] == 'A') {
        ab += 1
    } else if (s[s.length - 1] == 'A') {
        a += 1
    } else if (s[0] == 'B') {
        b += 1
    }
    for (j=0; j<s.length-1; j++) {
        if (s[j] == 'A' && s[j+1] == 'B') {
            c++
        }
    }
}
if (a>0) {
    a--
    c += ab
    ab = 0
    if (b>0) {
        c++
        b--
    }
}
if (b>0) {
    b--
    c += ab
    ab = 0
    if (a>0) {
        c++
        a--
    }
}
if (ab > 0) {
    c += ab - 1
}
c += Math.min(a,b)
console.log(c)


var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var n = o.a();
  var s = o.r(n,1);
  var a = 0;
  var b = 0;
  var c = 0;
  var ans = 0;
  for(var i = 0; i < n; i++){
    var x = s[i][0];
    for(var j = 1; j < s[i].length; j++){
      if(x === "A" && s[i][j] === "B")ans++;
      x = s[i][j];
    }
    if(s[i][0] === "B"){
      if(s[i][s[i].length-1] === "A")c++;
      else b++;
    }else if(s[i][s[i].length-1] === "A")a++;
  }
  var mn = Math.min(a,b);
  var mx = Math.max(a,b);
  if(mx){
    if(c)ans += mn+c;
    else ans += mn;
  }else if(c)ans += c-1;
  return ans;
}


module.exports=function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e,r){"use strict";var n=r(1);r(2)(n.readFileSync("/dev/stdin","utf8"))},function(t,e){t.exports=require("fs")},function(t,e,r){"use strict";var n=r(3),i=r(5);t.exports=function(t){var e=new n(t);i(e)}},function(t,e,r){"use strict";var n=r(4);t.exports=class{constructor(t){var e=t.trim().split(/\s+/g);this.inp=new n(e)}inr(){return this.inp.deq()}in(){return parseInt(this.inp.deq(),10)}fin(){this.inp.clear()}}},function(t,e,r){"use strict";t.exports=class{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.size=t.length,this.items=t,this.ind=0}enq(t){this.size+=1,this.items.push(t)}deq(){var t=this.items[this.ind];return this.size-=1,this.ind+=1,t}clear(){this.items=[],this.size=0,this.ind=0}}},function(t,e,r){"use strict";t.exports=function(t){for(var e=t.in(),r=new Array(e),n=0;n<e;n++)r[n]=t.inr();for(var i=0,o=0,s=0,u=0,c=0;c<e;c++){for(var a=0;a<r[c].length-1;a++)"A"==r[c][a]&&"B"==r[c][a+1]&&i++;var f=r[c][0],l=r[c][r[c].length-1];"B"!=f||"A"!=l?("B"==f&&s++,"A"==l&&o++):u++}i+=0==u?Math.min(o,s):s+o>0?u+Math.min(o,s):u-1,console.log(i)}}]);


inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')
N = inp.shift() * 1
a = 0
b = 0
ab = 0
c = 0
for (i=0; i<N; i++) {
    s = inp[i]
    if (s[0] == 'B' && s[s.length - 1] == 'A') {
        ab += 1
    } else if (s[s.length - 1] == 'A') {
        a += 1
    } else if (s[0] == 'B') {
        b += 1
    }
    for (j=0; j<s.length-1; j++) {
        if (s[j] == 'A' && s[j+1] == 'B') {
            c++
        }
    }
}
if (b>0) {
    b--
    c += ab
    ab = 0
    if (a>0) {
        c++
        a--
    }
}
if (a>0) {
    a--
    c += ab
    ab = 0
    if (b>0) {
        c++
        b--
    }
}
c += Math.min(a,b)
console.log(c)


module.exports=function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e,r){"use strict";var n=r(1);r(2)(n.readFileSync("/dev/stdin","utf8"))},function(t,e){t.exports=require("fs")},function(t,e,r){"use strict";var n=r(3),i=r(5);t.exports=function(t){var e=new n(t);i(e)}},function(t,e,r){"use strict";var n=r(4);t.exports=class{constructor(t){var e=t.trim().split(/\s+/g);this.inp=new n(e)}inr(){return this.inp.deq()}in(){return parseInt(this.inp.deq(),10)}fin(){this.inp.clear()}}},function(t,e,r){"use strict";t.exports=class{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.size=t.length,this.items=t,this.ind=0}enq(t){this.size+=1,this.items.push(t)}deq(){var t=this.items[this.ind];return this.size-=1,this.ind+=1,t}clear(){this.items=[],this.size=0,this.ind=0}}},function(t,e,r){"use strict";t.exports=function(t){for(var e=t.in(),r=new Array(e),n=0;n<e;n++)r[n]=t.inr();for(var i=0,o=0,s=0,u=0,c=0;c<e;c++){for(var f=0;f<r[c].length-1;f++)"A"==r[c][f]&&"B"==r[c][f+1]&&i++;var a=r[c][0],l=r[c][r[c].length-1];"B"==a&&"A"==l&&u++,"B"==a&&s++,"A"==l&&o++}o>=s?(i+=s,u-s>=2&&(i+=Math.floor((u-s)/2))):(i+=o,u-o>=2&&(i+=Math.floor((u-o)/2))),console.log(i)}}]);


module.exports=function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e,r){"use strict";var n=r(1);r(2)(n.readFileSync("/dev/stdin","utf8"))},function(t,e){t.exports=require("fs")},function(t,e,r){"use strict";var n=r(3),i=r(5);t.exports=function(t){var e=new n(t);i(e)}},function(t,e,r){"use strict";var n=r(4);t.exports=class{constructor(t){var e=t.trim().split(/\s+/g);this.inp=new n(e)}inr(){return this.inp.deq()}in(){return parseInt(this.inp.deq(),10)}fin(){this.inp.clear()}}},function(t,e,r){"use strict";t.exports=class{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.size=t.length,this.items=t,this.ind=0}enq(t){this.size+=1,this.items.push(t)}deq(){var t=this.items[this.ind];return this.size-=1,this.ind+=1,t}clear(){this.items=[],this.size=0,this.ind=0}}},function(t,e,r){"use strict";t.exports=function(t){for(var e=t.in(),r=new Array(e),n=0;n<e;n++)r[n]=t.inr();for(var i=0,o=0,s=0,u=0;u<e;u++){for(var c=0;c<r[u].length-1;c++)"A"==r[u][c]&&"B"==r[u][c+1]&&i++;"B"==r[u][0]&&s++,"A"==r[u][r[u].length-1]&&o++}i+=o>=s?s:o,console.log(i)}}]);


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	iv, _ := strconv.Atoi(scanString())
	return iv
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 100001), 100001*100)
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func main() {
	n := scanInt()
	ans := 0
	cab, ca, cb := 0, 0, 0
	for i := 0; i < n; i++ {
		s := scanString()
		ans += strings.Count(s, "AB")
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			cab++
		} else if s[0] == 'B' {
			cb++
		} else if s[len(s)-1] == 'A' {
			ca++
		}
	}
	if ca > 0 && cab > 0 {
		ca--
		ans++
	}
	if cb > 0 && cab > 0 {
		cb--
		ans++
	}
	if cab > 0 {
		ans += cab - 1
	}
	ans += min(ca, cb)
	fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	iv, _ := strconv.Atoi(scanString())
	return iv
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 100001), 100001*100)
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	n := scanInt()
	ans := 0
	cab, ca, cb := 0, 0, 0
	for i := 0; i < n; i++ {
		s := scanString()
		ans += strings.Count(s, "AB")
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			cab++
		} else if s[0] == 'B' {
			cb++
		} else if s[len(s)-1] == 'A' {
			ca++
		}
	}
	if ca > 0 && cab > 0 {
		ca--
		ans++
	}
	if cb > 0 && cab > 0 {
		cb--
		ans++
	}
	if cab > 0 {
		ans += cab - 1
	}
	ans += min(ca, cb)
	fmt.Println(ans)
}


package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func minll(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func maxll(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

func main() {
	defer Flush()

	N := readi()
	s := make([]string, N)
	for i := range s {
		s[i] = reads()
	}

	var ab, xa, bx, bxa int
	for _, t := range s {
		ab += strings.Count(t, "AB")
		if t[0] == 'B' && t[len(t)-1] == 'A' {
			bxa++
		} else if t[0] == 'B' {
			bx++
		} else if t[len(t)-1] == 'A' {
			xa++
		}
	}

	ans := ab
	if 0 < bxa {
		ans += bxa - 1
		if 0 < xa {
			ans++
			xa--
		}
		if 0 < bx {
			ans++
			bx--
		}
	}
	ans += min(xa, bx)
	println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var (
	finv, inv, fac [MAX]int
)

func COM(n, k int) int {
	MOD := int(MOD)
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD
}

func init() {
	MOD := int(MOD)
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1
	inv[1] = 1
	for i := 2; i < MAX; i++ {
		fac[i] = fac[i-1] * i % MOD
		inv[i] = MOD - inv[MOD%i]*(MOD/i)%MOD
		finv[i] = finv[i-1] * inv[i] % MOD
	}
	//sc.Split(bufio.ScanLines)
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 500100)
}

const (
	MAX = 2000000
)

var MOD int64 = 1000000007

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	ans := a * b % MOD
	if ans < 0 {
		ans += MOD
	}
	return ans
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	value int
	index int
	K     int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *QS) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Q)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func GCD(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return GCD(b, a%b)
}

func LCM(a, b int64) int64 {
	return a * b / GCD(a, b)
}

type UnionFind struct {
	par  []int
	size []int
}

func NewUnionFind(size int) *UnionFind {
	return new(UnionFind).init(size)
}

func (uf *UnionFind) init(size int) *UnionFind {
	uf.par = make([]int, size)
	uf.size = make([]int, size)

	for i := 0; i < size; i++ {
		uf.par[i] = i
		uf.size[i] = 1
	}
	return uf
}

func (uf *UnionFind) Unite(p int, q int) {
	rp := uf.Root(p)
	rq := uf.Root(q)
	if rp == rq {
		return
	}
	if uf.size[rp] < uf.size[rq] {
		uf.par[rp] = uf.par[rq]
		uf.size[rq] += uf.size[rp]
	} else {
		uf.par[rq] = uf.par[rp]
		uf.size[rp] += uf.size[rq]
	}
}

func (uf *UnionFind) Root(p int) int {
	for uf.par[p] == p {
		return p
	}
	uf.par[p] = uf.Root(uf.par[p])
	return uf.par[p]
}

func (uf *UnionFind) Size(p int) int {
	return uf.size[uf.Root(p)]
}

func (uf *UnionFind) Same(p int, q int) bool {
	return uf.Root(p) == uf.Root(q)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	n, _ := strconv.Atoi(getStr())
	return n
}

func getStr() string {
	sc.Scan()
	return sc.Text()
}

func factor(result map[int]int, num, pnum int) map[int]int {
	if pnum*pnum > num {
		if num != 1 {
			result[num] += 1
		}
		return result
	}

	if num%pnum == 0 {
		num /= pnum
		result[pnum]++
	} else {
		pnum++
	}
	return factor(result, num, pnum)
}

type D struct {
	X, L int
}

type Time struct {
	X int
	T int
}

func main() {
	N := getInt()
	var ans int
	var AC, BC, ABC int
	for i := 0; i < N; i++ {
		R := []rune(getStr())
		if string(R[0]) == "B" && string(R[len(R)-1]) == "A" {
			ABC++
		} else if string(R[0]) == "B" {
			BC++
		} else if string(R[len(R)-1]) == "A" {
			AC++
		}
		var last string
		for j := 0; j < len(R); j++ {
			cur := string(R[j])
			if last == "A" && cur == "B" {
				ans++
			}
			last = string(R[j])
		}

	}
	var bonus int
	if AC == BC {
		bonus = AC
		if ABC > 0 {
			bonus += ABC - 1
		}
	} else if AC > BC {
		bonus = BC + ABC
	} else {
		bonus = AC + ABC
	}
	fmt.Println(ans + bonus)
}

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func Reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var (
	finv, inv, fac [MAX]int
)

func COM(n, k int) int {
	MOD := int(MOD)
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD
}

func init() {
	MOD := int(MOD)
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1
	inv[1] = 1
	for i := 2; i < MAX; i++ {
		fac[i] = fac[i-1] * i % MOD
		inv[i] = MOD - inv[MOD%i]*(MOD/i)%MOD
		finv[i] = finv[i-1] * inv[i] % MOD
	}
	//sc.Split(bufio.ScanLines)
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 500100)
}

const (
	MAX = 2000000
)

var MOD int64 = 1000000007

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	ans := a * b % MOD
	if ans < 0 {
		ans += MOD
	}
	return ans
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	value int
	index int
	K     int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *QS) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Q)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func GCD(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return GCD(b, a%b)
}

func LCM(a, b int64) int64 {
	return a * b / GCD(a, b)
}

type UnionFind struct {
	par  []int
	size []int
}

func NewUnionFind(size int) *UnionFind {
	return new(UnionFind).init(size)
}

func (uf *UnionFind) init(size int) *UnionFind {
	uf.par = make([]int, size)
	uf.size = make([]int, size)

	for i := 0; i < size; i++ {
		uf.par[i] = i
		uf.size[i] = 1
	}
	return uf
}

func (uf *UnionFind) Unite(p int, q int) {
	rp := uf.Root(p)
	rq := uf.Root(q)
	if rp == rq {
		return
	}
	if uf.size[rp] < uf.size[rq] {
		uf.par[rp] = uf.par[rq]
		uf.size[rq] += uf.size[rp]
	} else {
		uf.par[rq] = uf.par[rp]
		uf.size[rp] += uf.size[rq]
	}
}

func (uf *UnionFind) Root(p int) int {
	for uf.par[p] == p {
		return p
	}
	uf.par[p] = uf.Root(uf.par[p])
	return uf.par[p]
}

func (uf *UnionFind) Size(p int) int {
	return uf.size[uf.Root(p)]
}

func (uf *UnionFind) Same(p int, q int) bool {
	return uf.Root(p) == uf.Root(q)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	n, _ := strconv.Atoi(getStr())
	return n
}

func getStr() string {
	sc.Scan()
	return sc.Text()
}

func factor(result map[int]int, num, pnum int) map[int]int {
	if pnum*pnum > num {
		if num != 1 {
			result[num] += 1
		}
		return result
	}

	if num%pnum == 0 {
		num /= pnum
		result[pnum]++
	} else {
		pnum++
	}
	return factor(result, num, pnum)
}

type D struct {
	X, L int
}

type Time struct {
	X int
	T int
}

func main() {
	N := getInt()
	var ans int
	var AC, BC int
	for i := 0; i < N; i++ {
		R := []rune(getStr())
		if string(R[0]) == "B" {
			BC++
		}
		var last string
		for j := 0; j < len(R); j++ {
			cur := string(R[j])
			if last == "A" && cur == "B" {
				ans++
			}
			last = string(R[j])
		}
		if last == "A" {
			AC++
		}
	}
	bonus := AC
	if bonus > BC {
		bonus = BC
	}
	fmt.Println(ans + bonus)
}

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func Reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	N := ReadInt()
	var cnt, both, head, tail int
	for i := 0; i < N; i++ {
		s := ReadString()
		for j := 0; j < len(s)-1; j++ {
			if s[j] == 'A' && s[j+1] == 'B' {
				cnt++
			}
		}
		h := s[0] == 'B'
		t := s[len(s)-1] == 'A'
		if h && t {
			both++
		} else if h {
			head++
		} else if t {
			tail++
		}
	}

	cnt += Min(head, tail)
	head, tail = head-Min(head, tail), tail-Min(head, tail)
	cnt += Max(both-1, 0)
	if both > 0 && Max(head, tail) > 0 {
		cnt++
	}
	fmt.Println(cnt)
}

func Max(xs ...int) int {
	max := xs[0]
	for _, x := range xs[1:] {
		if max < x {
			max = x
		}
	}
	return max
}

func Min(xs ...int) int {
	min := xs[0]
	for _, x := range xs[1:] {
		if min > x {
			min = x
		}
	}
	return min
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}


n = gets.to_i
w = x = y = z = 0
n.times do |i|
  s = gets.chomp
  if s[0] == "B"
    if s[-1] == "A"
      x += 1
    else
      y += 1
    end
  elsif s[-1] == "A"
    z += 1
  end
  w += s.scan("AB").size
end
if x > 1
  w += x - 1
  x = 1
end
if [x, y, z].max == y
  w += x
  w += z
elsif [x, y, z].max == z
  w += x
  w += y
end
puts w


N=gets.to_i
ss=$<.read.split.map(&:chomp)

a = 0
b=0
ab=0
ret = 0
ss.each do |s|
  i = -1
  ret += 1 while i = s.index('AB',i+1)
  if s[0]=='B' && s[-1]=='A'
    ab+=1
  elsif s[0]=='B'
    b+=1
  elsif s[-1]=='A'
    a+=1
  end
end

if 0 < ab
  ret += ab-1
  if 0 < a
    a -= 1
    ret += 1
  end
  if 0 < b
    b -= 1
    ret += 1
  end
end

ret += [a,b].min
puts ret


def c_s(str)
    i = -2
    kk = 0
    while 1
        i = str.index('AB', i+2)
        break if i == nil
        kk += 1
    end
    kk
end

n=gets.split.map(&:to_i)
s=$<.map(&:chomp)

ab = s.map {|ss| c_s(ss)}.inject(:+)

s.map! do |m|
    mm = 0
    mm += 1 if m.end_with?('A')
    mm += 2 if m.start_with?('B')
    mm
end
a = s.count(1)
b = s.count(2)
a_b = s.count(3)
if a == 0 && b == 0 && a_b > 0
    puts ab + a_b - 1
else
    puts ab + [a,b].min + a_b
end


n = gets.to_i
hs = Hash.new(0)
res = 0
n.times do
  s = gets.chomp
  pr = s[0]
  su = s[-1]
  res += s.scan("AB").size
  if pr + su == "BA"
    hs["BA"] += 1
  elsif su == "A"
    hs[".*A"] += 1
  elsif pr == "B"
    hs["B.*"] += 1
  end
end

cnt = [hs[".*A"], hs["BA"], hs["B.*"]].min
res += 2 * cnt
hs[".*A"] -= cnt
hs["BA"] -= cnt
hs["B.*"] -= cnt

res += hs["BA"] + [hs[".*A"], hs["B.*"]].min
puts res


n = gets.to_i
s = Array.new(n) { gets.chomp }

min, max = [s.count { |e| e[-1] == 'A' && e[0] != 'B' }, s.count { |e| e[-1] != 'A' && e[0] == 'B' }].minmax
both = s.count { |e| e[-1] == 'A' && e[0] == 'B' }
count = max == 0 ? both - 1 : min + both

s.each do |e|
  idx = -2
  count += 1 while (idx = e.index('AB', idx + 2))
end

puts count


n = gets.to_i
s = Array.new(n) { gets.chomp }

min = [s.count { |e| e[-1] == 'A' && e[0] != 'B' }, s.count { |e| e[-1] != 'A' && e[0] == 'B' }].min
both = s.count { |e| e[-1] == 'A' && e[0] == 'B' }
count = min + both

s.each do |e|
  idx = -2
  count += 1 while (idx = e.index('AB', idx + 2))
end

puts count


// Try diverta 2019 Programming Contest
// author: Leonardone @ NEETSDKASU

fn main() {
	let mut stdin = String::new();
    std::io::Read::read_to_string(
    	&mut std::io::stdin(),
        &mut stdin).unwrap();
	let mut stdin = stdin.split_whitespace();
    let mut get = || stdin.next().unwrap();
    macro_rules! get {
    	($t:ty) => (get().parse::<$t>().unwrap());
        () => (get!(i64));
    }

    let n = get!();
    let mut ans = 0;
    let mut rem = vec![0; 4];
    for _ in 0..n {
    	let s = get().as_bytes();
        for i in 1..s.len() {
        	if s[i-1]==b'A' && s[i]==b'B' {
                ans += 1;
            }
        }
        let a = if s[s.len()-1]==b'A' { 1 } else { 0 };
        let b = if s[0]==b'B' { 1 } else { 0 };
        rem[a*2+b] += 1;
    }
    if rem[3] > 0 {
        ans += rem[3] - 1;
        if rem[1] > 0 {
            rem[1] -= 1;
            ans += 1;
        }
        if rem[2] > 0 {
            rem[2] -= 1;
            ans += 1;
        }
    }
    ans += std::cmp::min(rem[1], rem[2]);
    println!("{}", ans);
}


use std::io::*;

fn main() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.trim().split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();

    let mut ans = 0;
    let mut a = 0;
    let mut b = 0;
    let mut ba = 0;
    for _ in 0..n {
        let s: Vec<char> = itr.next().unwrap().chars().collect();
        for i in 0..s.len() - 1 {
            if s[i] == 'A' && s[i + 1] == 'B' {
                ans += 1;
            }
        }
        if s[0] == 'B' && s[s.len() - 1] == 'A' {
            ba += 1;
        } else if s[0] == 'B' {
            b += 1;
        } else if s[s.len() - 1] == 'A' {
            a += 1;
        }
    }
    if ba > 0 {
        ans += ba - 1;
        if a > 0 {
            a -= 1;
            ans += 1;
        }
        if b > 0 {
            b -= 1;
            ans += 1;
        }
    }
    ans += std::cmp::min(a, b);

    println!("{}", ans);
}


#![allow(unused_imports)]

#[macro_use]
mod _input {
    use std::fmt;
    use std::io::{self, Read};
    use std::str::{self, FromStr};

    macro_rules! input {
        ($($name:ident : $t:tt),*,) => {
            input!($($name: $t),*)
        };
        ($($name:ident : $t:tt),*) => {
            let mut _scanned = ::_input::Scanned::new(::std::io::stdin(), 1024);
            $(
                let $name = unsafe { _read_value!(_scanned, $t) };
            )*
        };
    }

    macro_rules! _read_value {
        ($scanned:expr, ($($t:tt),*)) => {
            ($(_read_value!($scanned, $t)),*)
        };
        ($scanned:expr, [$t:tt; $n:expr]) => {
            (0..$n).map(|_| _read_value!($scanned, $t)).collect::<Vec<_>>()
        };
        ($scanned:expr, _bytes) => {
            _read_value!($scanned, String).into_bytes()
        };
        ($scanned:expr, _1based) => {
            _read_value!($scanned, usize) - 1
        };
        ($scanned:expr, $t:ty) => {
            $scanned.next::<$t>()
        };
    }

    pub struct Scanned {
        buf: Vec<u8>,
        pos: usize,
    }

    impl Scanned {
        pub fn new<R: Read>(mut input: R, estimated: usize) -> Self {
            let mut buf_ = Vec::with_capacity(estimated);
            let _ = io::copy(&mut input, &mut buf_).unwrap();
            debug_assert!(str::from_utf8(&buf_).is_ok());
            debug_assert!(buf_.iter().all(|&c| u32::from(c) <= 0x7F));
            Scanned { buf: buf_, pos: 0 }
        }

        #[inline]
        pub unsafe fn next<T: FromStr>(&mut self) -> T
        where
            T::Err: fmt::Debug,
        {
            let mut start = None;
            loop {
                match (self.buf[self.pos], start.is_some()) {
                    (b' ', true) | (b'\n', true) => break,
                    (_, true) | (b' ', false) | (b'\n', false) => self.pos += 1,
                    (_, false) => start = Some(self.pos),
                }
            }
            let target = &self.buf[start.unwrap()..self.pos];
            str::from_utf8_unchecked(target).parse().unwrap()
        }
    }
}

use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::{self, BufWriter, Read, Stderr, StderrLock, Stdout, StdoutLock, Write};
use std::iter::{self, Product, Sum};
use std::num::{ParseFloatError, ParseIntError};
use std::ops::{
    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Deref,
    DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
};
use std::str::{self, FromStr};
use std::{char, cmp, f32, f64, fmt, i16, i32, i64, i8, mem, thread, u16, u32, u64, u8};

fn main() {
    input! {
        n: usize,
        ss: [_bytes; n],
    }

    let (b, a, ba, m) = {
        let (mut b, mut a, mut ba, mut m) = (0, 0, 0, 0);
        for s in &ss {
            m += s.windows(2).filter(|w| w == b"AB").count() as u64;
            match (s[0], s[s.len() - 1]) {
                (b'B', b'A') => ba += 1,
                (b'B', _) => b += 1,
                (_, b'A') => a += 1,
                _ => {}
            }
        }
        (b, a, ba, m)
    };

    let r = match (b, a, ba) {
        (0, 0, 0) => 0,
        (b, a, 0) => cmp::min(b, a),
        (0, 0, ba) => ba - 1,
        (_, 0, ba) | (0, _, ba) => ba,
        (b, a, ba) => cmp::min(b - 1, a - 1) + ba + 1,
    } + m;
    println!("{}", r);
}


#![allow(non_snake_case)]
#![allow(unused_imports)]
use ascii::AsciiChar;
use ascii::AsciiStr;
use itertools::Itertools as _;
use permutohedron::LexicalPermutation as _;
use petgraph::algo::dijkstra;
use petgraph::algo::min_spanning_tree;
use petgraph::data::FromElements;
use petgraph::graph::NodeIndex;
use petgraph::graph::UnGraph;
use petgraph::unionfind::UnionFind;
use proconio::fastout;
use proconio::input;
use proconio::marker::Chars;
use proconio::marker::Usize1;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use superslice::Ext as _;

#[fastout]
fn main() {
    input! {
        N: usize,
        Ss: [Chars; N],
    }

    // 元から文字列に入っているABをカウントしておく
    let mut ans: usize = 0;
    for vec in Ss.iter() {
        for i in 1..vec.len() {
            if vec[i - 1] == 'A' && vec[i] == 'B' {
                ans += 1;
            }
        }
    }

    let BAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] == 'A')
        .collect();
    let BXs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] != 'A')
        .collect();
    let XAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] != 'B' && s[s.len() - 1] == 'A')
        .collect();
    // let others: Vec<Vec<char>> = Ss
    //     .clone()
    //     .into_iter()
    //     .filter(|s| s[0] != 'B' && s[s.len() - 1] != 'A')
    //     .collect();

    let mut XAs_rest = XAs.len();
    let mut BXs_rest = BXs.len();
    let mut BAs_rest = BAs.len();

    // まず、XAとBXの小さいほうに合わせて消費
    let smaller = min(XAs_rest, BXs_rest);
    ans += smaller;
    XAs_rest -= smaller;
    BXs_rest -= smaller;

    // まだ余っている場合
    let bigger_rest = max(XAs_rest, BXs_rest);

    // BA同士でくっつける
    let BAs_comb = if BAs_rest >= 2 { BAs_rest - 1 } else { 0 };
    ans += BAs_comb;
    BAs_rest = if BAs_rest >= 1 { 1 } else { 0 };

    if bigger_rest > 0 && BAs_rest > 0 {
        ans += 1
    }

    println!("{}", ans);
}


#![allow(non_snake_case)]
#![allow(unused_imports)]
use ascii::AsciiChar;
use ascii::AsciiStr;
use itertools::Itertools as _;
use permutohedron::LexicalPermutation as _;
use petgraph::algo::dijkstra;
use petgraph::algo::min_spanning_tree;
use petgraph::data::FromElements;
use petgraph::graph::NodeIndex;
use petgraph::graph::UnGraph;
use petgraph::unionfind::UnionFind;
use proconio::fastout;
use proconio::input;
use proconio::marker::Chars;
use proconio::marker::Usize1;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use superslice::Ext as _;

#[fastout]
fn main() {
    input! {
        N: usize,
        Ss: [Chars; N],
    }

    // 元から文字列に入っているABをカウントしておく
    let mut ans: usize = 0;
    for vec in Ss.iter() {
        for i in 1..vec.len() {
            if vec[i - 1] == 'A' && vec[i] == 'B' {
                ans += 1;
            }
        }
    }

    let BAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] == 'A')
        .collect();
    let BXs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] != 'A')
        .collect();
    let XAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] != 'B' && s[s.len() - 1] == 'A')
        .collect();
    // let others: Vec<Vec<char>> = Ss
    //     .clone()
    //     .into_iter()
    //     .filter(|s| s[0] != 'B' && s[s.len() - 1] != 'A')
    //     .collect();

    let mut XAs_rest = XAs.len();
    let mut BXs_rest = BXs.len();
    let BAs_rest = BAs.len();

    // まず、XAとBXの小さいほうに合わせて消費
    let smaller = min(XAs_rest, BXs_rest);
    ans += smaller;
    XAs_rest -= smaller;
    BXs_rest -= smaller;

    // まだ余っている場合
    let bigger_rest = max(XAs_rest, BXs_rest);
    if bigger_rest > 0 {
        ans += 1 + if BAs_rest >= 2 { BAs_rest - 1 } else { 0 };
    } else {
        ans += if BAs_rest >= 2 { BAs_rest - 1 } else { 0 };
    }

    println!("{}", ans);
}


#![allow(non_snake_case)]
#![allow(unused_imports)]
use ascii::AsciiChar;
use ascii::AsciiStr;
use itertools::Itertools as _;
use permutohedron::LexicalPermutation as _;
use petgraph::algo::dijkstra;
use petgraph::algo::min_spanning_tree;
use petgraph::data::FromElements;
use petgraph::graph::NodeIndex;
use petgraph::graph::UnGraph;
use petgraph::unionfind::UnionFind;
use proconio::fastout;
use proconio::input;
use proconio::marker::Chars;
use proconio::marker::Usize1;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use superslice::Ext as _;

#[fastout]
fn main() {
    input! {
        N: usize,
        Ss: [Chars; N],
    }

    // let B_A = Ss.iter().filter(|s| s[0] == 'B' && s[s.len()-1] == 'A').count();
    // let B_X =Ss.iter().filter(|s| s[0] == 'B' ).count() - B_A;
    // let X_A =     Ss.iter().filter(|s| s[s.len()-1] == 'A').count() - B_A;

    let BAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] == 'A')
        .collect();
    let BXs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] != 'A')
        .collect();
    let XAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] != 'B' && s[s.len() - 1] == 'A')
        .collect();
    let others: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] != 'B' && s[s.len() - 1] != 'A')
        .collect();

    let mut ans_vv: Vec<Vec<char>> = others;

    let xa_is_bigger = XAs.len() >= BXs.len();
    let XAs_len = XAs.len();
    let BXs_len = BXs.len();
    let BAs_len = BAs.len();

    // 方針: インデックスで制御するのはバグの温床なので、イテレータ化して個数で管理する
    let mut BAs_iter = BAs.into_iter();
    let mut BXs_iter = BXs.into_iter();
    let mut XAs_iter = XAs.into_iter();

    if xa_is_bigger {
        // A
        let rest = XAs_len - BXs_len;

        for _ in 0..min(XAs_len, BXs_len) {
            let xa = XAs_iter.next().unwrap();
            let bx = BXs_iter.next().unwrap();

            ans_vv.push(xa);
            ans_vv.push(bx);
        }

        if rest >= BAs_len {
            // A-1
            for _ in 0..BAs_len {
                let xa = XAs_iter.next().unwrap();
                let ba = BAs_iter.next().unwrap();

                ans_vv.push(xa);
                ans_vv.push(ba);
            }

            for _ in 0..rest - BAs_len {
                let xa = XAs_iter.next().unwrap();

                ans_vv.push(xa);
            }
        } else {
            // A-2
            for _ in 0..rest {
                let xa = XAs_iter.next().unwrap();
                let ba = BAs_iter.next().unwrap();

                ans_vv.push(xa);
                ans_vv.push(ba);
            }

            for _ in 0..BAs_len - rest {
                let ba = BAs_iter.next().unwrap();
                ans_vv.push(ba);
            }
        }
    } else {
        // B
        let rest = BXs_len - XAs_len;

        for _ in 0..min(XAs_len, BXs_len) {
            let xa = XAs_iter.next().unwrap();
            let bx = BXs_iter.next().unwrap();

            ans_vv.push(xa);
            ans_vv.push(bx);
        }

        if rest >= BAs_len {
            // B-1

            for _ in 0..BAs_len {
                let ba = BAs_iter.next().unwrap();
                let bx = BXs_iter.next().unwrap();
                ans_vv.push(ba);
                ans_vv.push(bx);
            }

            for _ in 0..rest - BAs_len {
                let bx = BXs_iter.next().unwrap();

                ans_vv.push(bx);
            }
        } else {
            // B-2

            for _ in 0..rest {
                let ba = BAs_iter.next().unwrap();
                let bx = BXs_iter.next().unwrap();
                ans_vv.push(ba);
                ans_vv.push(bx);
            }

            for _ in 0..BAs_len - rest {
                let ba = BAs_iter.next().unwrap();
                ans_vv.push(ba);
            }
        }
    }

    // dbg!(&ans_vv);

    let ans_v = ans_vv.concat();

    let mut ans: i64 = 0;
    for i in 1..ans_v.len() {
        if ans_v[i - 1] == 'A' && ans_v[i] == 'B' {
            ans += 1;
        }
    }

    println!("{}", ans);
}


let N = Int(readLine()!)!
var ans = 0
var aCount = 0
var bCount = 0
var abCount = 0
for _ in 0..<N {
  var str = readLine()!.characters.map{String($0)}
  var len = str.count
  let hasA = str[len-1] == "A"
  let hasB = str[0] == "B"
  if hasA && hasB {
    abCount += 1
  } else {
    if hasA {
      aCount += 1
    }
    if hasB {
      bCount += 1
    }
  }
  for i in 1..<len {
    if str[i-1] == "A" && str[i] == "B" {
      ans += 1
    }
  }
}
if abCount == 0 || aCount + bCount > 0 {
  ans += min(aCount, bCount) + abCount
} else {
  ans += abCount - 1
}
print(ans)


let N = Int(readLine()!)!
var ans = 0
var aCount = 0
var bCount = 0
var abCount = 0
for _ in 0..<N {
  var str = readLine()!.characters.map{String($0)}
  var len = str.count
  let hasA = str[len-1] == "A"
  let hasB = str[0] == "B"
  if hasA && hasB {
    abCount += 1
  } else {
    if hasA {
      aCount += 1
    }
    if hasB {
      bCount += 1
    }
  }
  for i in 1..<len {
    if str[i-1] == "A" && str[i] == "B" {
      ans += 1
    }
  }
}
if aCount + bCount > 0 {
  ans += min(aCount, bCount) + abCount
} else {
  ans += abCount - 1
}
print(ans)


export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const n: number = Number(tmp[0]);
    let count: number = 0;
    let startB: number = 0;
    let endA: number = 0;
    let both: number = 0;
    for (let i: number = 1; i <= n; ++i) {
      const t: string = tmp[i];
      const f: string = t[0];
      const e: string = t[t.length - 1];
      if (f == "B" && e == "A") {
        ++both;
      } else if (f == "B") {
        ++startB;
      } else if (e == "A") {
        ++endA;
      }
      const m = t.match(/AB/g);
      if (m != null) {
        count += m.length;
      }
    }
    if (startB > 0 && endA > 0 && both) {
      count += both + 1;
      both = 0;
      --startB;
      --endA;
    }
    const [small, large]: number[] = [Math.min(startB, endA), Math.max(startB, endA)];
    const [s, l]: number[] = [Math.min(small, both), Math.max(small, both)];
    count += s * 2;
    count += small - s;
    const bothRemain: number = both - s;
    const remain: number = large - small;
    count += bothRemain > 0 ? bothRemain - 1 : 0;
    count += Math.min(remain, bothRemain > 0 ? 1 : 0);
    return `${count}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


class NormalInput{
  input: string[];
  pointer: number;
  constructor(raw:string){
    this.input=raw.split(/ |\n/);
    this.pointer=0;
  }
  int():number{
    const ret= parseInt(this.input[this.pointer], 10);
    this.pointer++;
    return ret;
  }
  str():string{
    const ret= this.input[this.pointer];
    this.pointer++;
    return ret;
  }
  strs(length:number):string[]{
    let ret:string[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.str());
    }
    return ret;
  }
  ints(length:number):number[]{
    let ret:number[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.int());
    }
    return ret;
  }
}
function countAB(str:string):number{
  let count=0;
  let pos=0;
  for(let c of str){
    if(pos==1 && c=="B"){count++;}
    if(c=="A")pos=1;
    else pos=0;
  }
  return count;
}
function xor(a:boolean, b:boolean){return (a && !b) ||(!a && b);}
function add(a:number,b:number):number{return a+b;}
const countIf=<V>(f:(V)=>boolean)=>(sum:number, current: V)=>{return sum+(f(current)?1:0);}
const countIfTrue=countIf<boolean>((value)=>value);
function solve(N:number,s:string[]){
  let inner=s.map(str=>countAB(str)).reduce(add,0);
  let startB=s.map(str=>str.startsWith("B")).reduce(countIfTrue,0);
  let endA=s.map(str=>str.endsWith("A")).reduce(countIfTrue,0);
  let existsHagure=s.map(str=>xor(str.startsWith("B"),str.endsWith("A"))).some((value)=>value);
  return inner + Math.max(0, Math.min(startB, endA) + (existsHagure?0:-1));
}
function Main(raw: string) {
  const input=new NormalInput(raw);
  const N=input.int();
  const s=input.strs(N);
  //出力
  console.log(solve(N,s));
}

//DO NOT EDIT
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


import * as fs from 'fs';

function Picker(input) {
  var lines = input.split('\n');
  var fields = lines.reduce(function(all, line) { return all.concat(line.split(' ')); }, []);
  var p = 0;

  return {
    int: function() {
      return parseInt(fields[p++], 10);
    },
    float: function() {
      return parseFloat(fields[p++]);
    },
    str: function() {
      return fields[p++];
    }
  };
}

const input = fs.readFileSync("/dev/stdin", "utf8");
const pick = Picker(input);

//////////////////////////////////////////

const n = pick.int();
let c = 0;
let start = 0, end = 0, both = 0;
for (let i = 0; i < n; ++i) {
  const s = pick.str();
  c += s.split('AB').length - 1;

  if (s[0] === 'B' && s[s.length - 1] === 'A') {
    both++;
  } else if (s[0] === 'B') {
    start++;
  } else if (s[s.length - 1] === 'A') {
    end++;
  }
}
// console.log(c, both, start, end);

if (start && end) {
  c += both;
  c += start < end ? start : end;
} else if (!start && !end) {
  c += both ? both - 1 : 0;
} else {
  c += both;
}

console.log(c);


class NormalInput{
  input: string[];
  pointer: number;
  constructor(raw:string){
    this.input=raw.split(/ |\n/);
    this.pointer=0;
  }
  int():number{
    const ret= parseInt(this.input[this.pointer], 10);
    this.pointer++;
    return ret;
  }
  str():string{
    const ret= this.input[this.pointer];
    this.pointer++;
    return ret;
  }
  strs(length:number):string[]{
    let ret:string[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.str());
    }
    return ret;
  }
  ints(length:number):number[]{
    let ret:number[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.int());
    }
    return ret;
  }
}
function xor(a:boolean, b:boolean){return (a && !b) ||(!a && b);}
function add(a:number,b:number):number{return a+b;}
const countIf=<V>(f:(V)=>boolean)=>(sum:number, current: V)=>{return sum+(f(current)?1:0);}
const countIfTrue=countIf<boolean>((value)=>value);
function solve(N:number,s:string[]){
  let inner=s.map(str=>str.includes("AB")).reduce(countIfTrue,0);
  let startB=s.map(str=>str.startsWith("B")).reduce(countIfTrue,0);
  let endA=s.map(str=>str.endsWith("A")).reduce(countIfTrue,0);
  let existsHagure=s.map(str=>xor(str.startsWith("B"),str.endsWith("A"))).some((value)=>value);
  return inner + Math.max(0, Math.min(startB, endA) + (existsHagure?0:-1));
}
function Main(raw: string) {
  const input=new NormalInput(raw);
  const N=input.int();
  const s=input.strs(N);
  //出力
  console.log(solve(N,s));
}

//DO NOT EDIT
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const p = (...args) => {
  process.env.NODE_ENV === "test" ? console.log(...args) : ""
}

const endA = (s) => {
  return s[s.length - 1] === "A"
}
const startB = (s) => {
  return s[0] === "B"
}

const reg = /AB/g
const solve = (rest) => {
  let r = 0
  const hasAB = rest.map((s) => {
    let z = s.match(reg)
    r += z ? z.length : 0
  })
  // ...
  let startBs = []
  let endAs = []
  let both = []
  rest.map((s) => {
    let a = endA(s)
    let b = startB(s)
    if (a && b) {
      both.push(s)
      return
    }
    if (a) {
      endAs.push(s)
      return
    }
    if (b) {
      startBs.push(s)
    }
  })
  // 10 , 5, 2
  // console.log(startBs, endAs, both, r)
  let bothlen = both.length
  let sblen = startBs.length
  let ealen = endAs.length
  if (bothlen > 0) {
    r = r + bothlen - 1
    bothlen = 1
    if (sblen + ealen > 0) {
      r = r + bothlen + Math.min(sblen, ealen)
    }
  }
  // if (bothlen > 0) {
  //   r = Math.floor(bothlen / 2) + r
  // }
  return r
}

const main = (input) => {
  const [n, ...rest] = input.split("\n")

  return solve(rest)
}

if (process.env.NODE_ENV !== "test") {
  const input = require("fs").readFileSync("/dev/stdin", "utf8")
  console.log(main(input.trim()))
}

if (process.env.NODE_ENV === "test") {
  // module.exports = (input) => solve(input.trim())
  // main(``)
  // solve(1, [2, 3, 4])
}


const p = (...args) => {
  process.env.NODE_ENV === "test" ? console.log(...args) : ""
}

const endA = (s) => {
  return s[s.length - 1] === "A"
}
const startB = (s) => {
  return s[0] === "B"
}

const reg = /AB/g
const solve = (rest) => {
  let r = 0
  const hasAB = rest.map((s) => {
    let z = s.match(reg)
    r += z ? z.length : 0
  })
  // ...
  let startBs = []
  let endAs = []
  let both = []
  rest.map((s) => {
    let a = endA(s)
    let b = startB(s)
    if (a && b) {
      both.push(s)
      return
    }
    if (a) {
      endAs.push(s)
      return
    }
    if (b) {
      startBs.push(s)
    }
  })
  // 10 , 5, 2
  // console.log(startBs, endAs, both, r)
  let bothlen = both.length
  let sblen = startBs.length
  let ealen = endAs.length
  if (bothlen > 0) {
    if (sblen + ealen == 0) {
      r = r + bothlen - 1
    } else {
      r = r + bothlen + Math.min(sblen, ealen)
    }
  }
  // if (bothlen > 0) {
  //   r = Math.floor(bothlen / 2) + r
  // }
  return r
}

const main = (input) => {
  const [n, ...rest] = input.split("\n")

  return solve(rest)
}

if (process.env.NODE_ENV !== "test") {
  const input = require("fs").readFileSync("/dev/stdin", "utf8")
  console.log(main(input.trim()))
}

if (process.env.NODE_ENV === "test") {
  // module.exports = (input) => solve(input.trim())
  // main(``)
  // solve(1, [2, 3, 4])
}


s = int(input())
def f(n):
  if n%2 == 0:
    return n//2
  else:
    return 3*n+1
a = [s]
i=1
while(1):
  i+=1
  x=f(a[-1])
  if (x in a):
    print(i)
    exit()
  a.append(x)


s = int(input())
L = [s]
cnt = 1
while True:
  cnt += 1
  if L[cnt-2]%2 == 0:
    L.append(L[cnt-2]//2)
  else:
    L.append(L[cnt-2]*3+1)
  if not len(set(L)) == cnt:
    print(cnt)
    exit()


def f(x):
    if x%2==0:
        return x//2
    else:
        return 3*x+1
s=int(input())
cnt=1
check={}
while s not in check:
    check[s]=1
    s=f(s)
    cnt+=1
print(cnt)


# ABC116
# B Collatz Problem
s = int(input())
S = [str(s)]
i = 1
while True:
    if s % 2 == 0:
        i += 1
        s = s//2
        S.append(str(s))
        if S.count(str(s)) == 2:
            print(i)
            print(S)
            exit()
    else:
        i += 1
        s = 3 * s + 1
        S.append(str(s))
        if S.count(str(s)) == 2:
            print(i)
            print(S)
            exit()
pass


# ABC116
# B Collatz Problem
s = int(input())
S = [str(s)]
i = 1
while True:
    if s % 2 == 0:
        i += 1
        s = s/2
        S.append(str(s))
        if S.count(str(s)) == 2:
            print(i)
            exit()
    else:
        i += 1
        s = 3 * s + 1
        S.append(str(s))
        if S.count(str(s)) == 2:
            print(i)
            exit()
pass


a = int(input())
s = set()

for i in range(10**6):
	if a % 2 == 0:
		# print("Process for even.")
		a = a//2
	else:
		# print("Process for odd.")
		a = 3*a + 1
	if a not in s:
		s.add(a)
	else:
		print(i+2)
		break


import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {

		FastScanner sc = new FastScanner();
		int s = sc.nextInt();
		int count = 1;
		while (s != 4 && s != 2 && s != 1) {
			count++;
			if (s % 2 == 0)
				s = s / 2;
			else
				s = 3 * s + 1;
		}
		System.out.println(count + 3);

	}
	//以下、自作ライブラリ

	//最大公約数
	public static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);
		long c = 0;
		c = a % b;
		if (c == 0)
			return b;
		return gcd(b, c);
	}

	//最小公倍数
	public static long lcm(long m, long n) {
		return m * n / gcd(m, n);
	}

	//素数判定
	public static boolean isPrime(int n) {
		if (n < 2)
			return false;
		if (n == 2)
			return true;
		if (n % 2 == 0)
			return false;

		for (int i = 3; i * i <= n; i += 2) {
			if (n % i == 0)
				return false;
		}
		return true;
	}
}

//以下、高速スキャナークラス
class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}

	private int readByte() {
		if (hasNextByte())
			return buffer[ptr++];
		else
			return -1;
	}

	private static boolean isPrintableChar(int c) {
		return 33 <= c && c <= 126;
	}

	public boolean hasNext() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
		return hasNextByte();
	}

	public String next() {
		if (!hasNext())
			throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while (isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	public long nextLong() {
		if (!hasNext())
			throw new NoSuchElementException();
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while (true) {
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isPrintableChar(b)) {
				return minus ? -n : n;
			} else {
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}

	public int nextInt() {
		long nl = nextLong();
		if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
			throw new NumberFormatException();
		return (int) nl;
	}

	public double nextDouble() {
		return Double.parseDouble(next());
	}
}


import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int s = sc.nextInt();
		if (s == 2 || s == 1) {
			System.out.println(4);
			return;
		}
		for (int i = 1;;i++) {
			if (s == 4) {
				System.out.println(i+3);
				return;
			} else if (s % 2 == 0) {
				s /= 2;
			} else {
				s = s * 3 + 1;
			}
		}
	}
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}


import java.text.DecimalFormat;
import java.util.stream.LongStream;
import java.util.stream.IntStream;
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        AtCoder problem = new AtCoder(sc);
        problem.solve(out);

        out.flush();
    }

}

class AtCoder {

    int s;

    AtCoder(FastScanner sc) {
        s = sc.nextInt();
    }

    void solve(PrintWriter out) {
        int a = s;
        int m = 0;
        for (int i = 1; i <= 1000000; i++) {
            if (a == 4 || a == 2 || a == 1) {
                m = i + 3;
                break;
            }
            a = func(a);
        }
        out.println(m);
    }

    int func(int n) {
        return n % 2 == 0 ? n / 2 : 3 * n + 1;
    }

}

// https://qiita.com/p_shiki37/items/a0f6aac33bf60f5f65e4
class FastScanner {

    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte()) {
            return buffer[ptr++];
        } else {
            return -1;
        }
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr])) {
            ptr++;
        }
        return hasNextByte();
    }

    public String next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) {
            throw new NumberFormatException();
        }
        return (int) nl;
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}


package pracltice;

import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static PrintWriter out;

    public static void main(String[] args) {
        Main.run();
    }

    private static void run() {
        out = new PrintWriter(new BufferedOutputStream(System.out));
        Scanner sc = new Scanner(System.in);
        int s = Integer.parseInt(sc.next());
        ArrayList<Integer> list = new ArrayList<>();
        list.add(s);
        for (int i = 1, answer = 0;; i++) {
            answer = Main.calcF(list.get(i - 1));
            if (list.contains(answer)) {
                out.println(i + 1);
                break;
            }
            list.add(answer);
        }
        out.close();
        sc.close();
    }

    private static int calcF(int pnum) {
        int n = pnum;
        if (n % 2 == 0) {
            return n / 2;
        } else {
            return 3 * n + 1;
        }
    }
}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
		int N = nextInt();
		HashSet<Integer> used = new HashSet<Integer>();
		used.add(N);
		while(true){
			int ato = F(N);
			if(used.contains(ato)){
				myout(used.size());
				return;
			}
			used.add(ato);
			N = ato;
		}
	}
	//Method addition frame start

static int F(int v){
	if(v % 2 == 0){
		return v / 2;
	}else{
		return 3 * v + 1;
	}
}

	//Method addition frame end
}


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int s = sc.nextInt();
        if(s == 1) {
            System.out.println(4);
            return;
        }

        int ans = 1;
        while(true) {
            if(s == 1) {
                ans++;
                break;
            }
            if(s % 2 == 0) {
                s /= 2;
            } else {
                s = s * 3 + 1;
            }
            ans++;
        }
        System.out.println(ans);
    }
}


#define __USE_MINGW_ANSI_STDIO 0
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <numeric>
#include <bitset>
#include <map>
#include <limits.h>

using namespace std;

/// 各桁の和
int sumdigit(int x){
   int sum = 0;
    while(x != 0){
        sum += x % 10;
        x /= 10;
    }
    return sum;
}
/// 最大公約数
int gcd(int x, int y){
      if(x<y){
          int temp = x;
          x = y;
          y = temp;
      }
      int r = x % y;
       while(r!=0){
           x = y;
           y = r;
           r = x % y;
       }
      return y;
   }

int main(){
int s;
cin >> s;
int cnt = 1;
while(1){
    if(s==4 || s == 2 || s==1){
        cnt=cnt+3;
        cout << cnt << endl;
        return 0;
    }
    if(s%2==0){
        s /=2;
        cnt += 1;
    }
    else{
        s=3*s+1;
        cnt++;
    }
}
}


#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i <= n; i++)
#define FORR(i, m, n) for(int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v+n);
#define VSORT(v) sort(v.begin(), v.end());

using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<ll, ll>;

int main(){
	ll s;
    cin >> s;
    map<ll, ll> mp;
    ll ans = 0;
    while(1){
        ans++;
        mp[s]++;
        if(mp[s] == 2){
            cout << ans << endl;
            return 0;
        }
        if(s % 2) s = 3 * s + 1;
        else s /= 2;
    }
}


#include<bits/stdc++.h>
using namespace std;using int32=int_fast32_t;using uint32=uint_fast32_t;using int64=int_fast64_t;using uint64=uint_fast64_t;using pi=pair<int32,int32>;using pll=pair<int64,int64>;using vi=vector<int32>;using vvi=vector<vector<int32>>;using vll=vector<int64>;using ll=int64;using ull=uint64;constexpr int32 INF=1<<30;constexpr ll INFLL=1LL<<62;
#define all(x) x.begin(),x.end()
#define LB(V,x) lower_bound(all(V),x)-V.begin()
#define uint uint32
inline int f(int x){
    return x%2==0 ? x/2 : x*3+1;
}
void Main(){
    int s;
    cin >> s;
    map<int, int> R;
    for(int n=1;n<=1000000;n++){
        if(R[s]!=0){
            cout << n;
            return;
        }
        R[s] = n;
        s = f(s);
    }

}
int main(){cin.tie(0);ios::sync_with_stdio(false);Main();return 0;}


#include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define reps(i,n) for(int i=1;i<(int)(n);i++)

typedef long long ll;
using namespace std;

ll gcd(ll a, ll b) { //最大公約数
  if (b==0) return a;
  else return gcd(b, a%b);
}

ll lcm(ll a, ll b) { //最小公倍数
  return a * b / gcd(a, b);
}

ll digit_sum(ll a){ //10進桁和
  ll ans=0;
  while(a>0){
    ans+=a%10;
    a/=10;
  }
  return ans;
}

int main()
{

  ll s;
  cin>>s;

  ll ans=0;
  while(s>1){
    ans++;
    if(s%2==0){
      s=s/2;
    }else{
      s=3*s+1;
    }
  }

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


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

int main(){
    int s, i;
    cin >> s;

    i = 0;
    while (s != 1) {
        s = (s%2 == 0 ? s/2 : 3*s + 1);
        i++;
    }

    cout << i << endl;
    return (0);
}


#include<iostream>
using namespace std;

int main(){
    int a[100];
    int s;
    cin>>s;
    a[0]=s;
    int flag=1;
    for (int i = 1; i < 100; i++)
    {
        if (a[i-1]%2==0)
        {
            a[i] = a[i-1]/2;
        }
        else
        {
            a[i] = 3 * a[i-1] +1;
        }

        for (int j = 0; j < i; j++)
        {
            if (a[j]==a[i])
            {
                cout<<i+1;
                flag=0;
                break;
            }

        }
        if (flag==0)
        {
            break;
        }

    }

}


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
    int s;
    scanf("%d", &s);

    int index = 1;
    if (3 <= s){
        while(1){
        if (s == 4) break;
        index++;
        if (s%2 == 0) s /= 2;
        else s = 3*s + 1;
        }
    }
    else index = 1;
    printf("%d\n", index+3);
    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include "time.h"
#include "unistd.h"
#include "string.h"
#include <math.h>
int ans;
int i=0;
int main(int argc, char* argv[]){
  long int a=0,b=0,c=0;
  scanf("%ld",&a);
  if (a>=3) {
    for (i++; a != 4; i++) {
      if (a%2==0) {
        a/=2;
      }else{
        a=3*a+1;
      }
    }
    printf("%d",i+3);
  }else{
    printf("4");
  }
}


#include<stdio.h>

int main(void)
{
   int a, i=1;

   scanf("%d",&a);

   while((a!=1)&&(a!=2)&&(a!=4)){
      if(a%2==0)
         a=a/2;
      else
         a=3*a+1;
      i++;
   }

   printf("%d\n",i+3);
   return 0;
}


#include <stdio.h>

int f(int s,int i){
  if(i==0){
    return s;
  }int temp=f(s,i-1);
  if(temp%2==0){
    return (temp/2);
  }else{
    return (3*temp+1);
  }
}

int main(void){
  int s=0;
  scanf("%d", &s);
  int i=0,j=0,m=0;
  int a[1000005];
  int flag=0;
  while(1){
    a[i]=f(s,i+1);
    for(j=0;j<i;j++){
      if(a[j]==a[i]) {
        flag=1;
         m=i+1;
        break;
      }
    }
    if(flag) break;
    i++;
  }
    printf("%d", m+1);
    return 0;
  }


#include<stdio.h>
int main(){
  int s;
  int a[1000000];
 	scanf("%d",&s);
  a[0] = s;
  int i = 1;
  while(1){
    if(s % 2 == 0){
      a[i] = s / 2;
    }else{
      a[i] = 3 * s + 1;
    }

    for(int j = 0; j < i; j++){
      if(a[j] == a[i]){
	printf("%d", i+1);
	return 0;
      }
    }
   i++;
  }

  return 0;
}


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

#define rep(i, n) for(int i=0; i<(n); ++i)
#define max  200001

//qsort(str, n, sizeof(int), up_comp);
int up_comp(const void *a, const void *b){return *(int*)a - *(int*)b;}
int down_comp(const void *a, const void *b){return *(int*)b - *(int*)a;}
int int_sort( const void * a , const void * b ) {return strcmp(( char * )a , ( char * )b );}
int count_digit(int a){int i=0;while(a!=0){a=a/10;i++;}return i;}
int euclid( int a, int b ){int temp;if(a<b){temp=a;a=b;b=temp;}if(b<1)return -1;if(a%b==0) return b;return euclid(b,a%b);}

int main(void){

    int s;

    scanf("%d", &s);

    if (s==4||s==2||s==1) {
        printf("%d\n", i+3);
        return 0;
    }

    for (int i=2; i<=1000000; i++) {
        if (s%2==0) {
            s=s/2;
        } else {
            s=3*s+1;
        }

        if (s==4||s==2||s==1) {
            printf("%d\n", i+3);
            return 0;
        }
    }

    return 0;
}


function Main(input) {
  input = input.split("\n");
  var s = parseInt(input[0]);
  a = [s];
  for(var i=1;i>0;i++){

    if(a[i-1]%2==0){
      b=a[i-1]/2;
    if(a.indexOf(b)!=-1){
      var ans=i+1;
      break;
    }
      a.push(a[i-1]/2);
    }else{
      b=a[i-1]*3+1;
    if(a.indexOf(b)!=-1){
      var ans=i+1;
      break;
    }
      a.push(a[i-1]*3+1)
    }
  }

  console.log('%s', ans);
}

// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(){
  var input = document.getElementById("input").value;
  Main(input);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
    var arr = [,,input-0];
    for(var i=2;arr[i-2]+arr[i-1]+arr[i]!=7;i++){
        arr.push(arr[i]%2===0?arr[i]/2:3*arr[i]+1);
    }
    console.log(arr.length-1)
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


input = require('fs').readFileSync('/dev/stdin', 'utf8')
s = input.split('\n').shift() * 1
o = []
i = 1
while (o[s] === undefined) {
    o[s] = 1
    if (s%2) {
        s = 3 * s + 1
    } else {
        s = s / 2
    }
    i++
    if (o[s] == 1) {
        break;
    }
}
console.log(i)


const collatz = (n) => {
  if (n % 2 === 0) {
    n /= 2
  } else {
    n = 3 * n + 1
  }

  return n
}

const main = stdin => {
  const input = stdin.trim().split('\n')
  const s = parseInt(input[0])

  let tmp = s
  let first = 0
  let second = 0
  for (let i = 1; ; i++) {
    if (tmp === 4 && first === 0) {
      first = i
    } else if (tmp === 4 && first !== 0) {
      second = i
      break
    }
    tmp = collatz(tmp)
  }

  console.log(second)
}
// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))


const collatz = (n) => {
  if (n % 2 === 0) {
    n /= 2
  } else {
    n = 3 * n + 1
  }

  return n
}

const main = stdin => {
  const input = stdin.trim().split('\n')
  const s = parseInt(input[0])

  let tmp = s
  let first = 0
  let second = 0
  for (let i = 1; ; i++) {
    if (tmp === 4 && first === 0) {
      first = i
    } else if (tmp === 4 && first !== 0) {
      second = i
      break
    }
    tmp = collatz(tmp)
    console.log(tmp)
  }

  console.log(second)
}
// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))


var reader = require('readline').createInterface ({
    input: process.stdin,
    output: process.stdout
});

var lines = [];
reader.on('line', (line) => {
    lines.push(line);
});

reader.on('close', () => {
    var line = lines[0];
      var a = [line];
  for (var i = 0; i < 100; i++) {
      if (a[i] % 2 == 0)  {
         var T = a[i] / 2
         a.push(T)
      }else if (a[i] % 2 == 1) {
         var T = 3*a[i]-2;
         a.push(T)
      }
    for(var j=0; j<i;j++){
     if (a[j] == a[i]){
       console.log(i+1);
     return;
     }
    }
  }
  });


package main

import (
	"fmt"
)

func main() {
	var s int
	fmt.Scan(&s)

  	a := make([]int,0)
  	a = append(a, s)

	for i := 1; ; i++ {
		if a[i-1] % 2 == 0 {
			a = append(a, a[i-1] / 2)
		} else {
			a = append(a, 3 * a[i-1] + 1)
		}
		for j := 0; j < i; j++ {
			if a[i] == a[j] {
				fmt.Println(i+1)
				return
			}
		}
	}
}