jiahuimbzuai/CoQuIR huggingface dataset:
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1];}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const objvs =(a)=>{const b=[];for(const v in a){b.push(a[v])}return b};
const main=()=>{
  let [a,b]=[ts().split(''),ts().split('')]
  a.sort()
  b = b.sort().reverse()
  to(a<b?'Yes':'No')
}
main()
//  [typescript]
const log = console.log;

const parseLines = (s: string) => s.trim().split("\n");

const dictionarySorter = (strA: string, strB: string) =>
  strA.localeCompare(strB);

const dictionarySorterReversed = (strA: string, strB: string) =>
  strB.localeCompare(strA);

const sortCharacters = (
  str: string,
  sorter?: (strA: string, strB: string) => number
) =>
  str
    .split("")
    .sort(sorter || dictionarySorter)
    .join();

// ----

function Main(input: string): void {
  const [s, t] = parseLines(input);

  const sortedS = sortCharacters(s, dictionarySorter);
  const sortedT = sortCharacters(t, dictionarySorterReversed);

  log(sortedS.localeCompare(sortedT) < 0 ? "Yes" : "No");
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
// const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

const stdin = `ratcode
atlas`

const [s, t] = stdin.split('\n')

const ans = () => {
  const sd = s.split('').sort().join('')
  const td = t.split('').sort().reverse().join('')

  console.log(sd < td ? 'Yes' : 'No')
}

ans()
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

const [s, t] = stdin.split('\n')

const ans = () => {
  const sd = s.split('').sort().join('')
  const td = t.split('').sort().reverse().join('')

  console.log(sd, td)

  console.log(sd < td ? 'Yes' : 'No')
}

ans()
//  [python]
#!/usr/bin/env python3
t = open(0).read()
c1 = c2 = c3 = 0
for s in t.split():
    if s[-1] == "A" and s[0] == "B":
        c1 += 1
    elif s[-1] == "A":
        c2 += 1
    elif s[0] == "B":
        c3 += 1
if c1:
    a = c1 + min(c2, c3) if c2 + c3 > 0 else c1 - 1
else:
    a = min(c2, c3)

print(t.count("AB") + a)
//  [python]
n,*t=open(0).read().split()
n=int(n)
a=0
b=0
c=0

ans=0
for i in t:
    if i[0]=="B"and i[-1]=="A":
        a+=1
    elif i[0]=="B":
        b+=1
    elif i[-1]=="A":
        c+=1
    ans+=i.count("AB")
if a>0 and b>0 and c>0:
    ans+=a+1
    a=0
    b-=1
    c-=1
if a>0 and b>0:
    ans+=a
    a=0
    b-=1
if a>0 and c>0:
    ans+=a
    a=0
    c-=1
if a>0:
    ans+=a-1
    a=0
if b>0 and c>0:
    ans+=min(b,c)
print(ans)
//  [python]
# div2019C - AB Substrings
def main():
    N, *S = open(0).read().split()
    ans, ab, start_b, end_a = 0, 0, 0, 0
    for s in S:
        if s[0] == "B" and s[-1] == "A":
            ab += 1
        elif s[0] == "B":
            start_b += 1
        elif s[-1] == "A":
            end_a += 1
        ans += s.count("AB")
    if start_b + end_a == 0:
        ans += max(0, ab - 1)
    else:
        ans += ab + min(start_b, end_a)
    print(ans)


if __name__ == "__main__":
    main()
//  [python]
n = int(input())
s = [input() for _ in range(n)]

ab, a, b, b_a = 0, 0, 0, 0
for i in s:
  ab += i.count('AB')
  if i[-1] == 'A':
    a += 1
  if i[0] == 'B':
    b += 1
  if i[0] == 'B' and i[-1] == 'A':
    b_a +=1

a -= b_a
b -= b_a
print(ab + min(a, b) + b_a)
//  [python]
n = int(input())
s = [input() for _ in range(n)]

ab, a, b, b_a = 0, 0, 0, 0
for i in s:
  if 'AB' in i:
    ab += 1
  if i[-1] == 'A':
    a += 1
  if i[0] == 'B':
    b += 1
  if i[0] == 'B' and i[-1] == 'A':
    b_a +=1

a -= b_a
b -= b_a
print(ab + min(a, b) + b_a)
//  [python]
N = int(input())
S = [input().strip() for _ in range(N)]
C = {"A":0,"B":0,"BA":0}
cnt = 0
for i in range(N):
    s = S[i]
    for j in range(len(s)-2+1):
        if s[j:j+2]=="AB":
            cnt += 1
    if s[0]=="B" and s[-1]=="A":
        C["BA"] += 1
    elif s[0]=="B":
        C["B"] += 1
    elif s[-1]=="A":
        C["A"] += 1
if C["BA"]>0:
    cnt += C["BA"]-1
cnt += min(C["B"],C["A"])
if C["BA"]>0 and C["B"]!=C["A"]:
    cnt += 1
print(cnt)
//  [java]
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;
            if (A > 0 || B > 0) {
                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;
        }
    }
}
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main {
	
	public static void main(String[] args) throws NumberFormatException, IOException
	{
		new Main().run();
	}
	
	public void run() throws NumberFormatException, IOException
	{
		BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(file.readLine());
		char[][] strs = new char[N][];
		int b = 0;
		int ba = 0;
		int a = 0;
		int cnt = 0;
		for(int i = 0;i<N;i++)
		{
			strs[i] = file.readLine().trim().toCharArray();
			if(strs[i][0] == 'B'){
				if(strs[i][strs[i].length-1]=='A')
					ba++;
				else
					b++;
			}
			else if(strs[i][strs[i].length-1]=='A')
				a++;
			for(int j = 0;j<strs[i].length-1;j++)
			{
				if(strs[i][j]=='A' &&strs[i][j+1] == 'B')
					cnt++;
			}
		}
		if(a!=0)
		{
			a--;
			cnt+=ba;//now ends with a
			if(b!=0)
			{
				b--;
				cnt++;
			}
			cnt+=Math.min(a,b);
		}else if(ba!=0){
			cnt+=ba-1;
			if(b!=0)
				cnt++;
		}
		System.out.println(cnt);
	}
	
}
//  [java]
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 - 1, 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;
        }
    }
}
//  [java]
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;
        }
    }
}
//  [java]
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;
        }
    }
}
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [cpp]
#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;
  }
}
//  [cpp]
#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;
  }
}
//  [cpp]
#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;
  }
}
//  [c]
#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);
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [javascript]
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)
//  [javascript]
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;
}
//  [javascript]
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)}}]);
//  [javascript]
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)
//  [javascript]
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)}}]);
//  [javascript]
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)}}]);
//  [go]
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)
}
//  [go]
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)
}
//  [go]
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
}
//  [ruby]
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
//  [ruby]
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
//  [ruby]

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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [rust]
// 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);
}
//  [rust]
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);
}
//  [rust]
#![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);
}
//  [rust]
#![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);
}
//  [swift]
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)
//  [swift]
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)
//  [typescript]
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")));