jiahuimbzuai/CoQuIR huggingface dataset:
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

#define fastio 			ios::sync_with_stdio(0);	cin.tie(0); cout.tie(0);  cout<<fixed;  cout<<setprecision(12);
#define randomINT 		mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
#define	newl 			cout<<"\n"
#define DISP(as)		for(auto it : as) cout<<it<<" ";newl;
#define all(x)         	(x).begin(),(x).end()
#define mset(x,val)    	memset(x,val,sizeof(x))
#define newl           	cout<<"\n"
#define pb             	push_back
#define mp             	make_pair
#define f 				first
#define s 				second
#define dline          cerr<<"///REACHED///\n";
#define deb1(x)        cerr<<#x<<" = "<<x<<'\n';
#define deb2(x,y)      cerr<<'['<<#x<<','<<#y<<"] = "<<'['<<x<<','<<y<<']'<<'\n';
#define deb3(x,y,z)    cerr<<'['<<#x<<','<<#y<<','<<#z<<"] = "<<'['<<x<<','<<y<<','<<z<<']'<<'\n';

typedef long long 				ll;
typedef long double 			ld;
typedef vector<ll> 				vll;
typedef pair<ll , ll> 			pll;
typedef pair<ld, ld> 			pld;
typedef unordered_map<ll, ll> 	um;
typedef vector<pll> 			vpll;

const ll 	MAX5 	= 	1e+5 + 7;
const ll 	MAX7 	= 	1e+7 + 7;
const ll 	MAXN 	= 	MAX7;
const ll   	INF   	=  	0x7f7f7f7f7f7f7f7f;
const int  	INFi 	=  	0x7f7f7f7f;
const ll 	MOD		=  	1e+9 + 7;

vll adj[MAXN]; ll visit[MAXN] = {};
int dx8[] = {0, 1, 1, 1, 0, -1, -1, -1}, dy8[] = {1, 1, 0, -1, -1, -1, 0, 1};
int dx4[] = {0, 1, 0, -1}, dy4[] = {1, 0, -1, 0};

// <------------- Declare Variables Here ------------> //

ll T = 1;
ll n, x, m, y, k;
string s, t;


// <------------- Implement Functions Here ----------> //


// <------------- Start of main() -------------------> //

void MAIN() {
	cin >> s >> t;
	sort(all(s));
	sort(all(t));
	reverse(all(t));

	if(s < t) cout<<"Yes";
	else cout<<"No";
}

int main() {
	fastio; randomINT;
	//cin >> T;
	while (T--) {
		MAIN();
	}
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define int long long
int inf = 10e17;
#define mod 1000000007
int findLowerBound(
    vector<pair<int, int>> &arr,
    pair<int, int> &p)
{

    auto low = lower_bound(arr.begin(),
                           arr.end(), p);

    return low - arr.begin();
}
int findUpperBound(
    vector<pair<int, int>> &arr,
    pair<int, int> &p)
{
    auto up = upper_bound(arr.begin(),
                          arr.end(), p);

    return up - arr.begin();
}
bool vis[200005];
vector<int> vec[2000005];
int child[2000005];
int parent[2000005];
int div1[100005];
void dfs(int node)
{
    vis[node] = 1;
    for (int i = 0; i < vec[node].size(); i++)
    {
        if (!vis[vec[node][i]])
        {
            parent[vec[node][i]] = node;
            dfs(vec[node][i]);
            //   child[node] += child[vec[node][i]];
        }
    }
}
void bfs(int node)
{
    queue<int> qu;
    qu.push(node);
    vis[1] = 1;
    while (!qu.empty())
    {
        int top = qu.front();
        //cout << qu.front() << "\n";
        qu.pop();
        vis[top] = 1;
        for (int i = 0; i < vec[top].size(); i++)
        {
            if (!vis[vec[top][i]])
            {
                parent[vec[top][i]] = top;
                qu.push(vec[top][i]);
                vis[vec[top][i]] = 1;
            }
        }
    }
}
void belman(int n, int m, vector<pair<int, pair<int, int>>> vec, int dis[])
{
    for (int i = 0; i <= n + m - 1; i++)
    {
        for (int j = 0; j < vec.size(); j++)
        {
            int u = vec[j].second.first;
            int v = vec[j].second.second;
            int w = vec[j].first;

            if (dis[u] + w < dis[v])
            {
                dis[v] = dis[u] + w;
            }
        }
    }
}
int fun(int a, int b)
{
    if (a > b)
        return 0;
    if (a == b)
        return 1;
    else
    {
        return fun(a + 1, b) + fun(a, b - a);
    }
}
int32_t main()
{
    // ios_base::sync_with_stdio(false);
    // cin.tie(NULL);
    // cout.tie(NULL);

    string str1, str2;
    cin >> str1 >> str2;
    sort(str1.begin(), str1.end(), greater<char>());
    sort(str2.begin(), str2.end(), greater<char>());
    //  cout << str1 << " " << str2 << "\n";
    //cerr << "kcsc"
    //   << "\n";

    for (int i = 0; i < str1.length(); i++)
    {
        for (int j = 0; j < str2.length(); j++)
        {
            if (str2[j] > str1[i])
            {
                cout << "Yes"
                     << "\n";
                return 0;
            }
        }
    }
    if (str2 > str1)
    {
        cout << "Yes"
             << "\n";
    }
    else

        cout << "No"
             << "\n";

    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

char a[110],b[110];

bool cmpMin(char A,char B){
	return A<B;
}

bool cmpMax(char A,char B){
	return A>B;
}

int main(){
	scanf("%s %s",a,b);
	sort(a,a+strlen(a),cmpMin);
	sort(b,b+strlen(b),cmpMax);
	if(strcmp(a,b)<0)
		printf("Yes\n");
	else
		printf("No\n");
	return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

int main(void){

    char s[101], t[101];

    scanf("%s%s", s, t);

    int lens = strlen(s), lent = strlen(t);

    for(int i = 0; i < lens; i++){
        for(int j = i+1; j < lens; j++){
            char k[2];
            if(s[i] > s[j]){
                k[0] = s[i];
                s[i] = s[j];
                s[j] = k[0];
            }
        }
    }

    for(int i = 0; i < lent; i++){
        for(int j = i+1; j < lent; j++){
            char l[2];
            if(t[i] < t[j]){
                l[0] = t[i];
                t[i] = t[j];
                t[j] = l[0];
            }
        }
    }

    if(strcmp(s, t) < 0){
        printf("Yes\n");
    }else{
        printf("No\n");
    }

    return 0;
}
//  [c]
#include <stdio.h>
#define MAX 100

int main(void){
  char s[MAX],t[MAX];
  int i,j,save,l,judge=0;
  scanf("%s %s",s,t);
  for(i=0;i<strlen(s);i++){
    for(j=i+1;j<strlen(s);j++){
      if(s[i] > s[j]){
        save = s[i];
        s[i] = s[j];
        s[j] = save;
      }
    }
  }
  for(i=0;i<strlen(t);i++){
    for(j=i+1;j<strlen(t);j++){
      if(t[i] < t[j]){
        save = t[i];
        t[i] = t[j];
        t[j] = save;
      }
    }
  }
  if(strlen(s) <= strlen(t)){
    l = strlen(s);
  }
  else{
    l = strlen(t);
  }
  for(i=0;i<l;i++){
    if(s[i] <t[i]){
      printf("Yes");
      judge++;
      break;
    }
    else if(s[i] >t[i]){
      printf("No");
      judge++;
      break;
    }
  }
  if(judge == 0 && strlen(s) < strlen(t)){
    printf("Yes");
  }
  else if(judge == 0){
    printf("No");
  }
  return 0;
}
//  [c]
#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 lens, lent;
    char s[max], t[max], tmp;
    
    scanf("%s%s", s, t);
    
    lens=strlen(s);
    lent=strlen(t);
    
    for (int i=0; i<lens; i++) {
        for (int j=i+1; j<lens; j++) {
            if (s[i]>s[j]) {
                tmp=s[i];
                s[i]=s[j];
                s[j]=tmp;
            }
        }
    }
    
    for (int i=0; i<lent; i++) {
        for (int j=i+1; j<lent; j++) {
            if (t[i]<t[j]) {
                tmp=t[i];
                t[i]=t[j];
                t[j]=tmp;
            }
        }
    }

    if (strcmp(s, t)<0) {
        printf("Yes");
    } else {
        printf("No");
    }

    return 0;
}
//  [javascript]
function Main(input) {
	input = input.split("\n");
	var s = input[0].split("").sort();
	var t = input[1].split("").sort().reverse();
	var i = 0;	
	while(1){
        if( typeof t[i] === 'undefined'){
			console.log("No");
			break;
		}
		if( typeof s[i] === 'undefined'){
			console.log("Yes");
			break;
		}
		if ( s[i] == t[i] ){
          	i++;
        	continue; 
        }
		else if ( s[i] < t[i] ){
			console.log("Yes");
			break;
		}
      	else if ( s[i] > t[i] ){
        	console.log("No");
			break;
        }
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
  var inp = input.split('\n');  // Windows版Nodejsでは \n -> \r\nにする
  var s = inp[0].split('');
  var t = inp[1].split('');

  var sortS = s.sort((a, b) => {
    return a < b ? -1 : 1;
  });
  sortS = sortS.join('');

  var sortT = t.sort((a, b) => {
    return a < b ? 1 : -1;
  });
  sortT = sortT.join('');
  
  sortS < sortT ? console.log('Yes') : console.log('No');
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
const main = args => {
  const [s, t] = args.split('\n').map(arg => arg.split(''));
  console.log(s.sort() < t.sort().reverse() ? 'Yes' : 'No');
};
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

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

func main() {
	scanInit()

	s := nextStr()
	t := nextStr()
	s = sortString(s)
	t = reverse(sortString(t))

	if s < t {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
	return
}

// 文字列単体を昇順にする
func sortString(s string) string {
	r := []rune(s)
	sort.Slice(r, func(i, j int) bool { return r[i] < r[j] })
	s = string(r)
	return s

}

// 文字列単体を逆順にする
func reverse(s string) string {
	rns := []rune(s)
	for i, j := 0, len(rns)-1; i < j; i, j = i+1, j-1 {
		rns[i], rns[j] = rns[j], rns[i]
	}
	return string(rns)
}

// ---- readfunc
var sc = bufio.NewScanner(os.Stdin)

func scanInit() {
	const cap = 200 * 1024 // default=64*1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

import (
        "fmt"
        "sort"
)

func solution(s, t string) string {
        sb := make([]byte, len(s))
        tb := make([]byte, len(t))
        for i := range s {
                sb[i] = s[i]
        }
        for i := range t {
                tb[i] = t[i]
        }

        sort.SliceStable(sb, func(i, j int) bool { return sb[i] < sb[j] })
        sort.SliceStable(tb, func(i, j int) bool { return tb[i] > tb[j] })

        if string(sb) < string(tb) {
                return "Yes"
        }
        return "No"
}

func main() {
        var s, t string
        fmt.Scan(&s, &t)
        fmt.Println(solution(s, t))
}
//  [ruby]
_=`dd`.split.map{|_|_.chars.sort}
puts _[0].join<_[1].reverse.join ? :Yes: :No
//  [ruby]
s = gets.chomp
t = gets.chomp

s.length.times do
  s = s.split("").rotate!(1).join
  t.length.times do
    t = t.split("").rotate!(1).join
    if s < t
      puts "Yes"
      exit
    end
  end
end

puts "No"
//  [ruby]
require 'prime'
require 'set'
require 'tsort'
include Math
ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
def max(a,b);              a > b ? a : b                              end
def min(a,b);              a < b ?  a : b                             end
def swap(a,b);             a, b = b, a                                end
def gif;                   gets.to_i                                  end
def gff;                   gets.to_f                                  end
def gsf;                   gets.chomp                                 end
def gi;                    gets.split.map(&:to_i)                     end
def gf;                    gets.split.map(&:to_f)                     end
def gs;                    gets.chomp.split.map(&:to_s)               end
def gc;                    gets.chomp.split('')                       end
def pr(num);               num.prime_division                         end
def pr?(num);              Prime.prime?(num)                          end
def digit(num);            num.to_s.length                            end
def array(s,ini=nil);      Array.new(s){ini}                          end
def darray(s1,s2,ini=nil); Array.new(s1){Array.new(s2){ini}}          end
def rep(num);              num.times{|i|yield(i)}                     end
def repl(st,en,n=1);       st.step(en,n){|i|yield(i)}                 end

s = gc
t = gc

s.sort!
t.sort!.reverse!
a = [s.join,t.join];

a.sort!
puts a[0] == s.join  && s.join != t.join ? 'Yes' : 'No'
//  [rust]
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars};
#[allow(unused_imports)]
use std::cmp::{min, max};

fn main() {
	input! {
		mut s: Chars,
		mut t: Chars,
	}

	s.sort();
	t.sort_by_key(|&x| std::cmp::Reverse(x));

	if s < t {
		println!("Yes");
	}
	else {
		println!("No");
	}
}
//  [rust]
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let s:String = read();
    let t:String = read();
    let mut s = s.chars().collect::<Vec<char>>();
    s.sort();
    let mut t = t.chars().collect::<Vec<char>>();
    t.sort_by(|a, b| b.cmp(a));
    if s < t {
        println!("Yes");
    } else {
        println!("No");
    }
}
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const s = input[0][0]
    .split("")
    .sort((a, b) => (a === b ? 0 : a > b ? 1 : -1))
    .join("");
  const t = input[1][0]
    .split("")
    .sort((a, b) => (a === b ? 0 : a > b ? -1 : 1))
    .join("");

  return s < t ? "Yes" : "No";
};

console.log(main(read()));
//  [python]
import numpy as np

N = int(input())

cnt_AB = 0
xA = 0
Bx = 0
BA = 0
xx = 0
for i in range(N):
  s = input()
  cnt_AB += s.count('AB')
  if s[0] == 'B':
    if s[-1] == 'A':
      BA += 1
    else:
      Bx += 1
  else:
    if s[-1] == 'A':
      xA += 1
    else:
      xx += 1

A = xA + BA
B = Bx + BA
ans = cnt_AB

if A > B:
  ans += B
elif A < B:
  ans += A
elif A > 0:
  ans += A
  if xA == 0:
    ans -= 1

print(ans)
//  [python]
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits



def input(): return sys.stdin.readline().strip()


def INT(): return int(input())


def MAP(): return map(int, input().split())


def LIST(): return list(map(int, input().split()))



sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n = INT()
s = [input() for _ in range(n)]

lis1 = []
lis2 = []
lis3 = []
lis4 = []

for x in s:
    if (x[0] == 'B' and x[-1] == 'A'):
        lis1.append(x)
        
    if (x[-1] == 'A' and x not in lis1):
        lis2.append(x)

    if (x[0] == 'B' and x not in lis1):
        lis3.append(x)
        
for x in s:
    if 'AB' in x and x not in lis1 and x not in lis2 and x not in lis3:
        lis4.append(x)

#print(lis1)
#print(lis2)
#print(lis3)
#print(lis4)

ct = 0
for x in lis1:
    ct += x.count('AB')
for x in lis2:
    ct += x.count('AB')
for x in lis3:
    ct += x.count('AB')
for x in lis4:
    ct += x.count('AB')


if lis2 == [] and lis3 != []:
    p = len(lis1)
    q=max(len(lis1)-p-1,0)

    #print(ct,p)

    print(ct + p)

elif lis2 == [] and lis3 == []:
    print(max(len(lis1) - 1,0) + ct)

else :        
    p = min(len(lis2), len(lis3))
    q = len(lis1)

    #print(ct,p,q)

    print(ct + p + q)
//  [python]
n = int(input())
S = [input() for i in range(n)]

ans = 0
start_b = 0
end_a = 0
ab = 0

for i in range(n):
    for j in range(len(S) - 1):
        if S[i][j:j+2] == 'AB':
            ans += 1

    if S[i][0] == 'B' and S[i][-1] == 'A':
        ab += 1
        continue 
    if S[i][0] == 'B':
        start_b += 1
    if S[i][-1] == 'A':
        end_a += 1
    

if ab > 0:
    ans += ab - 1
    if start_b > 0:
        ans += 1
        start_b -= 1
    if end_a > 0:
        ans += 1
        end_a -= 1
        
ans += min(start_b, end_a)

print(ans)
//  [java]
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
	public static void main(String[] args){
		// TODO 自動生成されたメソッド・スタブ
		Scanner scan=new Scanner(System.in);
		int a=scan.nextInt();
		List <String>LA=new ArrayList<String>();//LastA
		List <String>FB=new ArrayList<String>();//FirstB
		List <String>FBLA=new ArrayList<String>();//FirstALastA
		List <String>O=new ArrayList<String>();//Other
		for(int i=0;i<a;i++) {
			String s=scan.next();
			if(s.charAt(0)=='B') {
				if(s.charAt(s.length()-1)=='A') {
					FBLA.add(s);
				}
				else {
					FB.add(s);
				}
			}
			else if(s.charAt(s.length()-1)=='A') {
				LA.add(s);
			}
			else {
				O.add(s);
			}
		}
		String ans="";
		if(LA.size()!=0) {
			ans+=LA.get(0);
			LA.remove(0);
		}
		for(;FBLA.size()!=0;) {
			ans+=FBLA.get(0);
			FBLA.remove(0);
		}
		for(;FB.size()!=0&&LA.size()!=0;) {
			ans+=FB.get(0);
			FB.remove(0);
			ans+=LA.get(0);
			LA.remove(0);
		}
		for(;LA.size()!=0;) {
			ans+=LA.get(0);
			LA.remove(0);
		}
		for(;FB.size()!=0;) {
			ans+=FB.get(0);
			FB.remove(0);
		}
		for(;O.size()!=0;) {
			ans+=O.get(0);
			O.remove(0);
		}
		int ANS=0;
		for(int i=1;i<ans.length();i++) {
			char ch=ans.charAt(i-1);
			char ch2=ans.charAt(i);
			if(ch=='A'&&ch2=='B') {
				ANS++;
			}
		}
		System.out.println(ANS);
	}
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        String[] words = new String[N];
        for (int i = 0; i < N; i++) {
            words[i] = sc.next();
        }
        long c1 = Arrays.stream(words).filter(s -> s.startsWith("B") && s.endsWith("A")).count();
        long c2 = Arrays.stream(words).filter(s -> s.startsWith("B") && !s.endsWith("A")).count();
        long c3 = Arrays.stream(words).filter(s -> !s.startsWith("B") && s.endsWith("A")).count();
        long containsAB = cotntains(words);

        long min = Math.min(c3 + c1, c2 + c1);

        if (c3 + c2 == 0 && c1 > 0) {
            System.out.println(containsAB + c1 - 1);
        } else {
            System.out.println(containsAB + min);
        }
    }

    private static long cotntains(String[] words) {
        long cnt = 0;
        for (String string : words) {
            int size = string.length();
            for (int i = 0; i < size; i++) {
                if (string.charAt(i) == 'A' & i + 1 < size && string.charAt(i + 1) == 'B') {
                    cnt++;
                }
            }
        }
        return cnt;
    }
}
//  [java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

public class Main {
    private static final Scanner scanner = new Scanner(System.in);
    private static final Consumer<List<String>> consumer = solve();

    public static void main(String[] args) {
        consumer.accept(readInput());
    }

    private static List<String> readInput() {
        final List<String> lineList = new ArrayList<>();
        while (scanner.hasNextLine()) {
            lineList.add(scanner.nextLine());
        }
        return lineList;
    }

    private static Consumer<List<String>> solve() {
        return args -> {
            List<String> strList = args.stream().skip(1).collect(toList());
            long ab = strList.stream()
                    .mapToLong(s -> {
                        long ans = 0;
                        for (int i = 0; i < s.length() - 1; i++) {
                            if (s.charAt(i) == 'A' && s.charAt(i + 1) == 'B') {
                                ans++;
                            }
                        }
                        return ans;
                    }).sum();
            long endA = strList.stream().filter(s -> s.endsWith("A")).count();
            long startB = strList.stream().filter(s -> s.startsWith("B")).count();
            long endAAndStartB = strList.stream().filter(s -> s.startsWith("B") && s.endsWith("A")).count();
            long plus = (endA == endAAndStartB && startB == endAAndStartB) ? endA - 1 : Math.min(endA, startB);
            System.out.println(ab + Math.max(0, plus));
        };
    }

}
//  [cpp]
#include <bits/stdc++.h>

using namespace std;
string a[10005];
int check[10005],n;
void DFS(int i,long long &res,int start){
	int chon=0;
    for(int j=1;j<=n;j++){

        if(check[j]==0){
            //cout<<i<<" "<<start<<" "<<j<<" "<<a[i][a[i].size()-1]<<" "<<a[j][0]<<endl;
            if(start==0){
            	if((a[i][a[i].size()-1]=='A')&&((a[j][0]=='B'))){
                    res++;
                    check[j]=1;
	                chon=j;

	                break;
                }


            }
            else{
                if((a[i][0]=='B')&&((a[j][a[j].size()-1]=='A'))){
                    res++;
                    check[j]=1;
	                chon=j;
	                //cout<<i<<" "<<start<<" "<<j<<endl;
	                break;
                }
            }
        }
    }
    if(chon!=0){
    	//cout<<i<<" "<<chon<<endl;
    	DFS(chon,res,start);
    }
}
int main()
{
    long long ans=0;
    cin>>n;
    vector<int>v;
    int start=0;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if((a[i][a[i].size()-1]=='A')||(a[i][0]=='B')){
            v.push_back(i);
        }
        if((a[i][a[i].size()-1]=='A')&&(a[i][0]=='B')){
            start=i;
        }
        for(int j=1;j<a[i].size();j++){
            if((a[i][j]=='B')&&(a[i][j-1]=='A')){
                ans++;
            }
        }
    }
    if(start!=0){
        check[start]=1;
        DFS(start,ans,0);
        DFS(start,ans,1);
    }
    //cout<<start<<endl;
    int kt=0;

	for(int i=0;i<v.size();i++){
		start=v[i];
        if(check[start]==0){
        	check[start]=1;
        	int temp=ans;
        	/*if(kt==0){
                if((a[start][a[start].size()-1]=='A')&&(a[start][0]=='B'))
                DFS(start,ans,0);
                if(ans==temp){
                    check[start]=0;
                }
                DFS(start,ans,1);
                if(ans==temp){
                    check[start]=0;
                }
                kt=1;
                continue;
        	}*/
            if(a[start][a[start].size()-1]=='A'){
                DFS(start,ans,0);
                if(ans==temp){
                    check[start]=0;
                }
                //continue;
            }
            if(a[start][0]=='B'){
                DFS(start,ans,1);
                if(ans==temp){
                    check[start]=0;
                }
                //continue;
            }

        }
    }
    cout<<ans<<endl;
}
//  [cpp]
#include <bits/stdc++.h>

using namespace std;
string a[10005];
int check[10005],n;
void DFS(int i,long long &res,int start){
	int chon=0;
    for(int j=1;j<=n;j++){

        if(check[j]==0){
            //cout<<i<<" "<<start<<" "<<j<<" "<<a[i][a[i].size()-1]<<" "<<a[j][0]<<endl;
            if(start==0){
            	if((a[i][a[i].size()-1]=='A')&&((a[j][0]=='B'))){
                    res++;
                    check[j]=1;
	                chon=j;

	                break;
                }


            }
            else{
                if((a[i][0]=='B')&&((a[j][a[j].size()-1]=='A'))){
                    res++;
                    check[j]=1;
	                chon=j;
	                //cout<<i<<" "<<start<<" "<<j<<endl;
	                break;
                }
            }
        }
    }
    if(chon!=0){
    	//cout<<i<<" "<<chon<<endl;
    	DFS(chon,res,start);
    }
}
int main()
{
    long long ans=0;
    cin>>n;
    vector<int>v;
    int start=0;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if((a[i][a[i].size()-1]=='A')||(a[i][0]=='B')){
            v.push_back(i);
        }
        if((a[i][a[i].size()-1]=='A')&&(a[i][0]=='B')){
            start=i;
        }
        for(int j=1;j<a[i].size();j++){
            if((a[i][j]=='B')&&(a[i][j-1]=='A')){
                ans++;
            }
        }
    }
    if(start!=0){
        check[start]=1;
        DFS(start,ans,0);
        DFS(start,ans,1);
    }
    //cout<<start<<endl;
    int kt=0;

	for(int i=0;i<v.size();i++){
		start=v[i];
        if(check[start]==0){
        	check[start]=1;
        	int temp=ans;
        	/*if(kt==0){
                if((a[start][a[start].size()-1]=='A')&&(a[start][0]=='B'))
                DFS(start,ans,0);
                if(ans==temp){
                    check[start]=0;
                }
                DFS(start,ans,1);
                if(ans==temp){
                    check[start]=0;
                }
                kt=1;
                continue;
        	}*/
            if(a[start][a[start].size()-1]=='A'){
                DFS(start,ans,0);
                if(ans==temp){
                    check[start]=0;
                }
                //continue;
            }
            if(a[start][0]=='B'){
                DFS(start,ans,1);
                if(ans==temp){
                    check[start]=0;
                }
               // continue;
            }

        }
    }
    cout<<ans<<endl;
}
//  [cpp]
#include<iostream>
#include<vector>
using namespace std;

int main(){
    int N;
    cin >> N;
    vector<string> s(N);
    string end_a[N];
    string first_b[N];
    string all[N];
    int cou_a = 0;
    int cou_b = 0;
    int cou_all = 0;
    int numb = N;

    for(int i = 0; i < N; i++){
        cin >> s[i];
    }

    for(int i = 0; i < numb; i++){
        if(s[i].substr(0,1) == "B" && s[i].substr(s[i].length() - 1, 1) == "A"){
            all[cou_all] = s[i];
            cou_all++;
            s.erase(s.begin() + i);
            numb--;
            i--;
        }else if(s[i].substr(0,1) == "B"){
            first_b[cou_b] = s[i];
            cou_b++;
            s.erase(s.begin() + i);
            numb--;
            i--;
        }else if(s[i].substr(s[i].length() - 1, 1) == "A"){
            end_a[cou_a] = s[i];
            cou_a++;
            s.erase(s.begin() + i);
            numb--;
            i--;
        }
    }

    string q;
    int ka = 0;
    int kb = 0;
    int kall = 0;

    if(cou_a != 0){
        q += end_a[ka];
        ka++;
    }else if(cou_all != 0){
        q += all[kall];
        kall++;
    }

    int ju = 0;

    while((cou_a + cou_all + cou_b) != (ka + kb + kall)){
        if((cou_all - kall) != 0){
            q+= all[kall];
            kall++;
            continue;
        }
        
        if((cou_b - kb) != 0 && ju == 0){
            q += first_b[kb];
            kb++;
            ju = 1;
        }else if((cou_a - ka)!= 0 && ju == 1){
            q += end_a[ka];
            ka++;
            ju = 0;
        }else{
            if((cou_a - ka) != 0){
                q += end_a[ka];
                ka++;
            }else{
                q += first_b[kb];
                kb++;
            }
        }
    }

    for(int i = 0; i < numb; i++){
        q += s[i];
    }

    int ans = 0;

    for(int i = 0; i < (q.length() - 1); i++){
        if(q.substr(i, 2) == "AB"){
            ans++;
        }
    }
    cout << ans << endl;

    /*cout << "nokori" << endl;
    for(int i = 0; i < numb; i++){
        cout << s[i] << endl;
    }

    cout << endl << "A" << endl;
    for(int i = 0; i < cou_a; i++){
        cout << end_a[i] << endl;
    }

    cout << endl << "B" << endl;
    for(int i = 0; i < cou_b; i++){
        cout << first_b[i] << endl;
    }

    cout << endl << "all" << endl;
    for(int i = 0; i < cou_all; i++){
        cout << all[i] << endl;
    }*/
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
typedef long long LL;
typedef long double Lf;
#define Rep(i,a,n)for(int i=(int)(a);i<(int)(n);i++)
//#define Rep(i,a,n)for(LL i=(LL)(a);i<(LL)(n);i++)
#define rep(i,n)Rep(i,0,n)
#define Repp(i,l,r,k)for(int i=(int)(l);i<(int)(r);i+=(int)(k))
//#define Repp(i,l,r,k)for(LL i=(LL)(l);i<(LL)(r);i+=(LL)(k))
#define Ma(x,y) ((x)>(y)?(x):(y))
#define mi(x,y) ((x)<(y)?(x):(y))
#define MOD 1000000007//998244353,1000000007,1000000009
int upi(const void* a, const void* b) { return*(int*)a<*(int*)b ? -1 : *(int*)a> * (int*)b ? 1 : 0; }
int downi(const void* a, const void* b) { return*(int*)a<*(int*)b ? 1 : *(int*)a> * (int*)b ? -1 : 0; }
void sortupi(int* a, int n) { qsort(a, n, sizeof(int), upi); } //1,2,3,4,...
void sortdowni(int* a, int n) { qsort(a, n, sizeof(int), downi); }
int upLL(const void* a, const void* b) { return*(LL*)a<*(LL*)b ? -1 : *(LL*)a> * (LL*)b ? 1 : 0; }
int downLL(const void* a, const void* b) { return*(LL*)a<*(LL*)b ? 1 : *(LL*)a> * (LL*)b ? -1 : 0; }
void sortupLL(LL* a, int n) { qsort(a, n, sizeof(LL), upLL); }
void sortdownLL(LL* a, int n) { qsort(a, n, sizeof(LL), downLL); }
int cmp_char(const void* a, const void* b) { return *(char*)a - *(char*)b; } // a,b,c,d
int cmp_str(const void* a, const void* b) { return strcmp(*(const char**)a, *(const char**)b); } // aaa,aab
LL gcd(LL p, LL q) { while (q) { LL t = p % q; p = q; q = t; }return p; }
LL modpow(LL a, LL n, int m) {LL x=1;for(a%=m;n;n/=2)n&1?x=x*a%m:0,a=a*a%m;return x; }
#define invmodpow(b,p)modpow(b,p-2,p)// a/b≡a*b^{-1}(mod p)...return b^{-1}(mod p)
typedef struct fac { LL n, exp; }F;
LL fact(LL n,F*a){LL x,i,j,c=0;x=n;for(i=2;i*i<=x;i++){for(j=1;x%i==0;j++)x/=i;if(j>1){a[c].n=i;a[c++].exp=j-1;}}if(x-1){a[c].n=x;a[c++].exp=1;}return c;}
//snippet

#define N 10009

int main() {
	char s[11];
	int n, inAB = 0, B_A = 0, B_x = 0, x_A = 0;
	scanf("%d", &n);
	rep(i, n) {
		scanf("%s", s);
		int l = strlen(s);
		rep(j, l - 1)if (s[j] == 'A' && s[j + 1] == 'B')inAB++;
		if (s[0] == 'B' && s[l - 1] == 'A')B_A++;
		else if (s[0] == 'B' && s[l - 1] != 'A')B_x++;
		else if (s[0] != 'B' && s[l - 1] == 'A')x_A++;
	}
	//書いてみた結果
	if (B_A) {
		inAB += B_A + mi(B_x, x_A);
		if (B_x + x_A == 0)inAB--;
	}
	else inAB += mi(B_x, x_A);

	printf("%d\n", inAB);
}
//  [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 && ba > 0 ? kitaeri - 1 : kitaeri));
	return 0;
}
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
  // 1行目がinput[0], 2行目がinput[1], …に入る
  input = input.split("\n");
  tmp0 = input[0].split(" ");
  N = Number(input[0]);

  var ans = 0;
  var lastA_cnt = 0;
  var firstB_cnt = 0;
  var firstB_lastA_cnt = 0;
  for (var i = 1; i <= N; i++) {
    var s = input[i];
    ab_cnt = (s.match(/AB/g) || []).length;
    ans += ab_cnt;
    if (s[0] === "B" && s[s.length - 1] === "A") {
      firstB_lastA_cnt++;
      continue;
    }
    ///
    if (s[0] === "B") {
      firstB_cnt++;
    }
    if (s[s.length - 1] === "A") {
      lastA_cnt++;
    }
  }
  if (firstB_lastA_cnt > 0) {
    ans += firstB_lastA_cnt - 1;
    if (lastA_cnt > 0) {
      firstB_cnt++;
    }
    if (firstB_cnt > 0) {
      lastA_cnt++;
    }
  }
  ans += Math.min(firstB_cnt, lastA_cnt);

  console.log(ans);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// Main("1\nBA\n");
//  [javascript]
"use strict";

// read lines from stdin
const input = require("fs")
  .readFileSync("/dev/stdin", "utf8")
  .split("\n");

const N = parseInt(input[0], 10);

let startWithB = 0;
let endWithA = 0;
let startWithBandEndWithA = 0;
let ans = 0;

for (let i = 1; i <= N; i++) {
  const s = input[i];
  let foundA = false;
  let firstIsB = false;
  let lastIsA = false;

  for (let j = 0; j < s.length; j++) {
    if (s[j] === 'A') {
      foundA = true;
      if (j === (s.length - 1)) {
        lastIsA = true;
      }
    } else if (s[j] === 'B') {
      if (foundA) {
        ans++;
        foundA = false;
      } else if (j === 0) {
        firstIsB = true;
      }
    } else {
      foundA = false;
    }
  }

  if (firstIsB && lastIsA) {
    startWithBandEndWithA++;
  } else if (firstIsB) {
    startWithB++;
  } else if (lastIsA) {
    endWithA++;
  }
}

const diff = Math.abs(startWithB - endWithA);

ans += Math.min(startWithB, endWithA);

if (startWithBandEndWithA) {
  ans += startWithBandEndWithA - 1;
  if (startWithB || endWithA) { ans++; }
}

console.log(ans);
//  [javascript]
"use strict";
function Main(input) {
  const args = input.split('\n');
  const N = parseInt(args.shift());
  let count = 0;
  let countA = 0;
  let countB = 0;
  let both = 0;
  args.forEach(f => {
    count += (f.length - f.replace(/AB/g, '').length) / 2;
    let endB = f.charAt(0) === 'B';
    if (endB) {
      countB ++;
    }
    let startA = f.charAt(f.length - 1) === 'A';
    if (startA) {
      countA ++;
    }
    if (startA && endB) {
      both ++;
    }
  });
  count += countA < countB ? countA : countB;
  count += (both > 0 && both === countA && both === countB) ? -1 : 0;
  console.log(count);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"fmt"
	"strings"
)

type container struct {
	data []string
}

func (c *container) queue(s string) {
	c.data = append(c.data, s)
}
func (c *container) dequeue() string {
	if len(c.data) > 0 {
		r := c.data[0]
		c.data = c.data[1:len(c.data)]
		return r
	}
	return ""
}

func main() {
	var N int
	fmt.Scan(&N)
	var aq, bq, baq, oq container
	for i := 0; i < N; i++ {
		var s string
		fmt.Scan(&s)
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			baq.queue(s)
		} else if s[0] == 'B' {
			bq.queue(s)
		} else if s[len(s)-1] == 'A' {
			aq.queue(s)
		} else {
			oq.queue(s)
		}
	}
	//fmt.Println("N", N, "AQ", aq, "BQ", bq, "BAQ", baq, "OQ", oq)
	ans := ""
	ans += aq.dequeue()
	for len(baq.data) > 0 {
		ans += baq.dequeue()
	}
	//fmt.Println("step1 done: ans", ans)
	for len(bq.data) > 0 {
		ans += bq.dequeue()
		if len(aq.data) > 0 {
			ans += aq.dequeue()
		} else {
			break
		}
	}
	// fmt.Println("step2 done: ans", ans)
	for len(bq.data) > 0 {
		ans += bq.dequeue()
	}
	// fmt.Println("step3 done: ans", ans)
	for len(aq.data) > 0 {
		ans += aq.dequeue()
	}
	// fmt.Println("step4 done: ans", ans)
	for len(oq.data) > 0 {
		ans += oq.dequeue()
	}
	// fmt.Println("ans", ans)
	fmt.Println(strings.Count(ans, "AB"))
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

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

	A := 0
	B := 0
	BA := 0

	ans := 0
	for i := 0; i < N; i++ {
		var S string
		fmt.Scan(&S)
		ans += strings.Count(S, "AB")
		if S[0] == 'B' && S[len(S)-1] == 'A' {
			BA++
		} else if S[0] == 'B' {
			B++
		} else if S[len(S)-1] == 'A' {
			A++
		}
	}
	if BA > 1 {
		ans += BA-1
		BA = 1
	}

	if BA > 0 {
		if A > 0 {
			ans++
			A--
		}
		if B > 0 {
			ans++
			B--
		}
	}
	if A > B {
		ans += B
	} else {
		ans += A
	}
	fmt.Println(ans)
}
//  [ruby]
N = gets.to_i
s = Array.new(N)
for i in 0..(N-1)
  s[i] = gets.chomp.split("")
end
ab = Array.new(N).map{Array.new(3, 0)}
nAB = nBA = nA = nB = 0

for i in 0..(N-1)
  for j in 0..(s[i].size - 1)
    if j == 0 && s[i][j] == "B"
      ab[i][2] = 1
    elsif j == s[i].size - 1 && s[i][j] == "A"
      ab[i][1] = 1
    end
    if j < s[i].size - 1
      if s[i][j..(j+1)].join == "AB"
        ab[i][0] += 1
      end
    end
  end
  nAB += ab[i][0]
  if ab[i][1] == 1 && ab[i][2] == 1
    nBA += 1
  elsif ab[i][1] == 1
    nA += 1
  elsif ab[i][2] == 1
    nB += 1
  end
end

if nBA == 0
  puts nAB + [nA, nB].min
else
  if nA == 0 && nB == 0
    puts nAB + nBA - 1
  elsif nA == 0 || nB == 0
    puts nAB + nBA
  else
    puts nAB + nBA + 1 + [nA, nB].min - 1
  end
end
//  [ruby]
n=gets.to_i
array=[]
n.times{
    array.push(gets.chomp.split(''))
}

ans=0
righta=0
leftb=0
double=0

array.map{|str|
    str.map.with_index{ |char,index|
       if str[index+1] && str[index]=="A" && str[index+1]=="B"
           ans+=1
       end
    }
    
    if str[0]=="B"
        leftb+=1
    end
    
    if str[-1]=="A"
        righta+=1
    end
    
    if str[-1]=="A" && str[0]=="B"
        double+=1
    end
}

if double==leftb && double==righta && double>0
    puts ans+double-1
else
   puts ans+[leftb,righta].min 
end
//  [ruby]
n = gets.to_i
hs = Hash.new(0)
n.times do
  s = gets.chomp
  pr = s[0]
  su = s[-1]
  hs["AB"] += 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

if hs["_A"] > 0 && hs["B_"] > 0
  cnt = [hs["_A"], hs["B_"]].min
  hs["_A"] -= cnt
  hs["B_"] -= cnt
  hs["AB"] += cnt
elsif hs["_A"] > 0 && hs["BA"] > 0
  cnt = [hs["_A"], hs["BA"]].min
  hs["_A"] -= cnt
  hs["BA"] -= cnt
  hs["AB"] += cnt
elsif hs["B_"] > 0 && hs["BA"] > 0
  cnt = [hs["_A"], hs["BA"]].min
  hs["BA"] -= cnt
  hs["B_"] -= cnt
  hs["AB"] += cnt
elsif hs["BA"] > 1
  hs["AB"] += hs["BA"] - 1
  hs["BA"] = 0
else
  puts hs["AB"]
  exit
end
puts hs["AB"] + (hs["BA"] + [hs["B_"], hs["A_"]].min)
//  [rust]
use std::io::*;
use std::str::FromStr;
use std::cmp::min;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("faild to read char") as char)
        .take_while(|c| !c.is_whitespace())
        .collect();
    token
        .parse()
        .ok()
        .expect("faild to parse token")
}

fn main(){
    let n: u64 = read();
    let s: Vec<Vec<char>> = (0..n).map(|_| read::<String>().chars().collect()).collect();

    let mut start_b: u64 = 0;
    let mut end_a: u64 = 0;
    let mut both: u64 = 0;
    let mut ret: u64 = 0;

    for c in &s {
        if c[0] == 'B' && c[c.len() -1] == 'A' {
            both += 1;
        } else if c[c.len() - 1] == 'A' {
            end_a += 1;
        } else if c[0] == 'B' {
            start_b += 1;
        }

        for i in 1..(c.len()) {
            if c[i - 1] == 'A' && c[i] == 'B' {
                ret += 1;
            }
        }
    }

    if both == 0 {
        ret += min(start_b, end_a);
    } else if start_b == 0 && end_a == 0 {
        ret += both - 1;
    } else {
        ret += both + min(end_a, start_b);
    }
    println!("{}", ret);
}
//  [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);
    if smaller > 0 && bigger_rest == 0 {
        // 最初でぴったり消費できた場合
        // 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 };

        // BAのかたまりをXA-BXに挟み込んで消勝することができる
        if BAs_rest > 0 {
            ans += 1;
        }
    } else {
        // まだ余っている場合

        // 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);
}
//  [python]
s=int(input())
a=[s]
for i in range(1000000):
    if a[i]%2==0:
        a.append(int(a[i]/2))
    else:
        a.append(int(3*a[i]+1))
a_duplicate=sorted([j for j in set(a) if a.count(j)>1],key=a.index)
a[a.index(a_duplicate[0])]=0
print(a.index((a_duplicate[0]))+1)
//  [python]
# ABC116
# B
import numpy as np
s = int(input())

a = s
idx = 1
a_list = [a]
while(idx < 1000000):
    idx += 1
    if a % 2 == 0:
        a = int(a / 2)
    else:
        a = 3*a+1
    if a in a_list:
        print(idx)
        break
    else:
        a_list.append(a)
//  [python]
import numpy as np
import sys
input = sys.stdin.readline
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

s = I()
l = [0]*10000000
l[0] = s

for i in range(1,10000000):
    if l[i-1] % 2 == 0:
        l[i] = l[i-1]//2
    else:
        l[i] = l[i-1]*3+1
    if l[i] in l[:i-1]:
        ans = i+1
        break

print(ans)
//  [java]
import java.util.Scanner;
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int s = sc.nextInt();
        List<Integer> a = new ArrayList<>();
        a.add(s);
        int len = 1000000;
        for (int i = 1; i <= len; i++) {
            int f;
            if (a.get(i - 1) % 2 == 0) {
                f = a.get(i - 1) / 2;
            } else {
                f = 3 * a.get(i - 1) + 1;
            }
            a.add(f);
        }
        int ans = 0;
        for (int i = 0; i <= len; i++) {
            for (int j = i + 1; j <= len; j++) {
                if (a.get(i) == a.get(j)) {
                    // System.out.printf("i = %d,j = %d %n", i, j);
                    // System.out.printf("a = %d,a = %d %n", a.get(i), a.get(j));
                    ans = j + 1;
                    System.out.println(ans);
                    return;
                }
            }
        }
    }
}
//  [java]
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		final Scanner sc = new Scanner(System.in);
		
		final int s = sc.nextInt();
		
		int i = 1;
		final List<Integer> a = new ArrayList<>();
		a.add(s);
		int tail = s;
		while (true) {
			i++;
			final int an = f(tail);
			
			final boolean satisfy = a.stream().anyMatch(j -> j == an);
			
			if (satisfy) {
				break;
			}
			
			tail = an;
			a.add(an);
		}
		
		System.out.println(i);
	}
	
	private static int f(int n) {
		if (n % 2 == 0) {
			return n / 2;
		} else {
			return 3 * n + 1;
		}
	}

}
//  [java]
import java.util.*;
public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int s = sc.nextInt();
		int[] data = new int[1000000];
		data[0] = s;
		int min = 100;

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

		for (int i = 0;i<1000000 ;i++ ) {
			for (int j = i+1;j<1000000 ;j++ ) {
				if (data[i]==data[j]) {
					System.out.println(j+1);
					System.exit(0);
				}
			}
		}
		}
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

int func(int N){
  if(N%2==0){
    return N/2;
  }
  else{
    return 3*N+1;
  }
}

int main(){
  int S;
  cin >> S;
  vector<int> A(100000000);
  A.at(0)=S;
  for(int i=1;i<10000000;i++){
    A.at(i)=func(A.at(i-1));
  }
  bool a=false;
  for(int i=0;i<10000000;i++){
    for(int j=i+1;j<10000000;j++){
      if(A.at(i)==A.at(j)){
        cout << j+1 << endl;
        a=true;
        break;
      }
    }
    if(a){
      break;
    }
  }
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

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

  for(int i = 0; i < N; i++){
    for(int j = i+1; j < N; j++){
      if(a[i] == a[j]){
        cout << j+1 << endl;
        return 0;
      }
    }
  }
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using LL = long long;
using P = pair<int,int>;
const int mx = 10000000;
vector<int> a(mx);

int clllats(int N){
	if(N%2==0) return N / 2;
	else return 3 * N + 1;
}

int main(){
	cin >> a[0];
	for(int i = 1;i<mx;i++) {
		a[i] = clllats(a[i-1]);
	}
	int ans = mx;
	rep(i,mx-2){
		int tmp = 100;
		for(int j = i + 1;j <= mx -1; j++){

			if(a[i] == a[j]){
				tmp = j + 1;
				ans = min(ans, tmp);
				break;
			}
		}
	}	
	cout << ans << endl;
	return 0;
}
//  [c]

#include <stdio.h>

int main(){
    int s;
    int i, j, a[10000], min = 10000, ansj;

    scanf("%d", &s);

    a[0] = s;

    for(i=1; i<10000; i++){
        if(a[i-1] % 2 == 0)
            a[i] = a[i-1] / 2;
        else
            a[i] = 3 * a[i-1] + 1;
    }

    for(i=0; i<10000; i++){
        for(j=0; j<10000; j++){
            if(j > i && a[i] == a[j]){
                if((j-i) < min){
                    min = j - i;
                    ansj = j;
                }
            }
        }
    }

    printf("%d\n", ansj + 1);

    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef long long ll;
typedef double keytype;

void quicksort(keytype a[], int first, int last)
{
    int i, j;
    keytype x, t;

    x = a[(first + last) / 2];
    i = first;  j = last;
    for ( ; ; ) {
        while (a[i] < x) i++;
        while (x < a[j]) j--;
        if (i >= j) break;
        t = a[i];  a[i] = a[j];  a[j] = t;
        i++;  j--;
    }
    if (first  < i - 1) quicksort(a, first , i - 1);
    if (j + 1 < last) quicksort(a, j + 1, last);
}

int main(){
    int s;
    int a[1000000];

    scanf("%d", &s);

    a[0] = s;
    for(int i = 0; i < 1000000; ++i){
        //printf("%d\n", a[i]);
        if(a[i] % 2 == 0){
            a[i+1] = a[i] / 2;
            //printf("%d\n", a[i]);
        }else{
            a[i+1] = 3 * a[i] + 1;
            //printf("%d\n", a[i]);
        }
    }
    //printf("%d\n", a[4]);

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

    return 0;
}
//  [javascript]
function calc(n)
{
  if(n % 2 === 0){
    return n / 2
  }else{
    return 3 * n + 1
  }
}

// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
  tmp = input[0].split(" ");
  var s = parseInt(tmp[0], 10)
  var arr = []

  arr.push(s)
  for(var i=1; i <= 1000000; i++)
  {
    arr.push(calc(arr[i-1]))
  }

  for(var m=1; m <= arr.length; m++)
  {
    for(var n=0; n < m; n++)
    {
      if(arr[m] === arr[n]){
        console.log(m+1)
        return;
      }
    }
  }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));