#include <iostream>
#include <map>
#include <vector>

int main() {
  int n;
  std::cin >> n;

  std::map<int, std::vector<int>> m;

  int a[300001];
  a[0] = 0;
  m[0].push_back(0);
  for (int i = 1; i <= n; i++) {
    std::cin >> a[i];
    a[i] = a[i] ^ a[i - 1];
    m[a[i]].push_back(i);
  }

  int count = 0;
  for (int i = 0; i <= n; i++) {
    for (int x : m[a[i]]) {
      if (i < x && (x - i) % 2 == 0) {
        count++;
        break;
      }
    }
  }

  std::cout << count << "\n";

  return 0;
}


#include <iostream>

int main() {
  int n;
  std::cin >> n;

  int a[300000];
  a[0] = 0;
  for (int i = 1; i <= n; i++) {
    std::cin >> a[i];
    a[i] = a[i] ^ a[i - 1];
  }

  int count = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = i - 1; j >= 1; j -= 2) {
      if ((a[i] ^ a[j - 1]) == 0) {
        count++;
      }
    }
  }

  std::cout << count << "\n";

  return 0;
}


#include <iostream>
#include <map>
#include <vector>

int main() {
  int n;
  std::cin >> n;

  std::map<int, std::vector<int>> m;

  int a[300001];
  a[0] = 0;
  m[0].push_back(0);
  for (int i = 1; i <= n; i++) {
    std::cin >> a[i];
    a[i] = a[i] ^ a[i - 1];
    m[a[i]].push_back(i);
  }

  int count = 0;
  for (int i = 0; i <= n; i++) {
    for (int x : m[a[i]]) {
      if (i < x && (x - i) % 2 == 0) {
        count++;
      }
    }
  }

  std::cout << count << "\n";

  return 0;
}


#include <array>
#include <iostream>
#include <map>

int main() {
  int n;
  std::cin >> n;

  std::map<int, std::array<int, 2>> m;

  int a[300001];
  a[0] = 0;
  m[0][0]++;
  for (int i = 1; i <= n; i++) {
    std::cin >> a[i];
    a[i] = a[i] ^ a[i - 1];
    if (i % 2 == 0) {
      m[a[i]][0]++;
    } else {
      m[a[i]][1]++;
    }
  }

  long long count = 0;
  for (int i = 0; i <= n; i++) {
    if (i % 2 == 0) {
      count += m[a[i]][0] - 1;
    } else {
      count += m[a[i]][1] - 1;
    }
  }

  std::cout << count / 2 << "\n";

  return 0;
}


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

	#define pb push_back
	#define debug(x) cerr << "[" << #x << ": "<< x << "]" << endl;
	#define debug2(x, y) cerr << "[" << #x << ": "<< x << "  " << #y << ": "<< y << "]" << endl;
	#define all(x) (x).begin(), (x).end()
	#define rall(x) (x).rbegin(), (x).rend()
	#define fi first
	#define ar array
	#define se second
	#define sz(x) ((int)(x).size())
	#define ends "\n"
	#define sp ' '

	const int N=3e5;

	int a[N], dp[2][1<<20];

	int n, ans=0, sf=0;

	void solve(){
		cin >> n;
		for(int i=0; i<n; ++i) cin >> a[i];
		dp[1][0]=1;
		for(int i=0; i<n; ++i){
			sf^=a[i];
			ans+=dp[i&1][sf];
			++dp[i&1][sf];
			debug2(sf, ans);
		}

		cout << ans << ends;
	}

	int main(){
		ios_base::sync_with_stdio(false);
	    cin.tie(nullptr);
	    cout.tie(nullptr);

	    // int q;
	    // cin >> q;
	    // for(int i=1; i<=q; ++i)
			solve();
	}


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

	#define pb push_back
	#define debug(x) cerr << "[" << #x << ": "<< x << "]" << endl;
	#define debug2(x, y) cerr << "[" << #x << ": "<< x << "  " << #y << ": "<< y << "]" << endl;
	#define all(x) (x).begin(), (x).end()
	#define rall(x) (x).rbegin(), (x).rend()
	#define fi first
	#define ar array
	#define se second
	#define sz(x) ((int)(x).size())
	#define ends "\n"
	#define sp ' '

	const int N=3e5;

	int a[N];
	long long dp[2][1<<20];

	int n, sf=0;
	long long ans=0;

	void solve(){
		cin >> n;
		for(int i=0; i<n; ++i) cin >> a[i];
		dp[1][0]=1LL;
		for(int i=0; i<n; ++i){
			sf^=a[i];
			ans+=dp[i%2][sf];
			++dp[i%2][sf];
		}

		cout << ans << ends;
	}

	int main(){
		ios_base::sync_with_stdio(false);
	    cin.tie(nullptr);
	    cout.tie(nullptr);

	    // int q;
	    // cin >> q;
	    // for(int i=1; i<=q; ++i)
			solve();
	}


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

	#define pb push_back
	#define debug(x) cerr << "[" << #x << ": "<< x << "]" << endl;
	#define debug2(x, y) cerr << "[" << #x << ": "<< x << "  " << #y << ": "<< y << "]" << endl;
	#define all(x) (x).begin(), (x).end()
	#define rall(x) (x).rbegin(), (x).rend()
	#define fi first
	#define ar array
	#define se second
	#define sz(x) ((int)(x).size())
	#define ends "\n"
	#define sp ' '

	const int N=3e5;

	int a[N], dp[2][1<<20];

	int n, ans=0, sf=0;

	void solve(){
		cin >> n;
		for(int i=0; i<n; ++i) cin >> a[i];
		dp[1][0]=1;
		for(int i=0; i<n; ++i){
			sf^=a[i];
			ans+=dp[i&1][sf];
			++dp[i&1][sf];
		}

		cout << ans << ends;
	}

	int main(){
		ios_base::sync_with_stdio(false);
	    cin.tie(nullptr);
	    cout.tie(nullptr);

	    // int q;
	    // cin >> q;
	    // for(int i=1; i<=q; ++i)
			solve();
	}


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

	#define pb push_back
	#define debug(x) cerr << "[" << #x << ": "<< x << "]" << endl;
	#define debug2(x, y) cerr << "[" << #x << ": "<< x << "  " << #y << ": "<< y << "]" << endl;
	#define all(x) (x).begin(), (x).end()
	#define rall(x) (x).rbegin(), (x).rend()
	#define fi first
	#define ar array
	#define se second
	#define sz(x) ((int)(x).size())
	#define ends "\n"
	#define sp ' '

	const int N=3e5;

	int a[N], dp[2][1<<20];

	int n, ans=0, sf=0;

	void solve(){
		cin >> n;
		for(int i=0; i<n; ++i) cin >> a[i];
		dp[1][0]=1;
		for(int i=0; i<n; ++i){
			sf^=a[i];
			ans+=dp[i&1][sf];
			++dp[i&1][sf];
			debug2(sf, ans);
		}

		cout << ans << ends;
	}

	int main(){
		ios_base::sync_with_stdio(false);
	    cin.tie(nullptr);
	    cout.tie(nullptr);

	    // int q;
	    // cin >> q;
	    // for(int i=1; i<=q; ++i)
			solve();
	}


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

int main(){
    ll n,ans(0),k(0),a;
    map<ll,ll>m[2];
    m[0][0];
    cin>>n;
    for(ll i=0;i<n;i++){
        cin>>a;
        k^=a;
        ans+=m[i&1][k];
        m[i&1][k]++;
    }
    cout<<ans<<endl;
    return 0;
}


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

int main(){
    ll n,ans,k(0),a;
    map<ll,ll>m[2];
    m[0][0];
    cin>>n;
    for(ll i=0;i<n;i++){
        cin>>a;
        k^=ka;
        ans+=m[i&1][k];
        m[i&1][k]++;
    }
    cout<<ans<<endl;
    return 0;
}


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

int main(){
    ll n,ans,k(0),a;
    map<ll,ll>m[2];
    m[0][0];
    cin>>n;
    for(ll i=0;i<n;i++){
        cin>>a;
        k=k^a;
        ans+=m[i&1][k];
        m[i&1][k]++;
    }
    cout<<ans<<endl;
    return 0;
}


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

int main(){
    ll n,ans(0),k(0),a;
    map<ll,ll>m[2];
    cin>>n;
    m[0][0]=1;
    for(ll i=0;i<n;i++){
        cin>>a;
        k=^a;
        ans+=m[(i+1)&1][k];
        m[(i+1)&1][k]++;
    }
    cout<<ans<<endl;
    return 0;
}


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

int main(){
    ll n,ans(0),k(0),a;
    map<ll,ll>m[2];
    cin>>n;
    m[0][0]=1;
    for(ll i=0;i<n;i++){
        cin>>a;
        k^=a;
        ans+=m[(i+1)&1][k];
        m[(i+1)&1][k]++;
    }
    cout<<ans<<endl;
    return 0;
}


import re
s=str(input())
ab=len(list(re.finditer('AB',s)))
ba=len(list(re.finditer('BA',s)))

if ab==0 and ba==0:
        print("NO")
        exit()

aba=len(list(re.finditer('ABA',s)))
bab=len(list(re.finditer('BAB',s)))
#abab=len(list(re.finditer('ABAB',s)))
#baba=len(list(re.finditer('BABA',s)))
if aba>1 or bab>1:
        print("YES")
        exit()
if len(list(re.finditer('BABAB',s)))>=1 or len(list(re.finditer('ABABA',s)))>=1:
        print("YES")
        exit()
if bab==1 or aba==1:
        if ab>1 or ba>1:
                print("YES")
        else:
                print("NO")
elif bab==0 and aba==0:
        if ab>0 and ba>0:
                print("YES")
        else:
                print("NO")


import re
s=str(input())

ab=len(list(re.finditer('AB',s)))
ba=len(list(re.finditer('BA',s)))
aba=len(list(re.finditer('ABA',s)))
bab=len(list(re.finditer('BAB',s)))
abab=len(list(re.finditer('ABAB',s)))
baba=len(list(re.finditer('BABA',s)))

if ab-(aba+bab-abab-baba)<=0 and ba-(aba+bab-abab-baba)<=0  and (bab>0 or aba>0):
        print("NO")
else:
        print("YES")


import re
s=str(input())
ab=len(list(re.finditer('AB',s)))
ba=len(list(re.finditer('BA',s)))

if ab==0 and ba==0:
        print("NO")
        exit()

aba=len(list(re.finditer('ABA',s)))
bab=len(list(re.finditer('BAB',s)))
abab=len(list(re.finditer('ABAB',s)))
baba=len(list(re.finditer('BABA',s)))
if aba>1 or bab>1:
        print("YES")
        exit()
if len(list(re.finditer('BABAB',s)))>=1 or len(list(re.finditer('ABABA',s)))>=1:
        print("YES")
        exit()
if (abab==1 and baba==0)  or (baba==1 and abab==0):
        print("NO")
        exit()
if bab==1 or aba==1:
        if ab>1 or ba>1:
                print("YES")
        else:
                print("NO")
elif bab==0 and aba==0:
        if ab>0 and ba>0:
                print("YES")
        else:
                print("NO")


import re
s=str(input())
ab=len(list(re.finditer('AB',s)))
ba=len(list(re.finditer('BA',s)))

if ab==0 and ba==0:
        print("NO")
        exit()

aba=len(list(re.finditer('ABA',s)))
bab=len(list(re.finditer('BAB',s)))
abab=len(list(re.finditer('ABAB',s)))
baba=len(list(re.finditer('BABA',s)))
if aba>1 or bab>1:
        print("YES")
        exit()
if len(list(re.finditer('BABAB',s)))>=1 or len(list(re.finditer('ABABA',s)))>=1:
        print("YES")
        exit()
if (abab==1 and baba==0)  or (baba==1 and abab==0):
        print("NO")
if bab==1 or aba==1:
        if ab>1 or ba>1:
                print("YES")
        else:
                print("NO")
elif bab==0 and aba==0:
        if ab>0 and ba>0:
                print("YES")
        else:
                print("NO")


import re
s=str(input())
ab=len(list(re.finditer('AB',s)))
ba=len(list(re.finditer('BA',s)))

if ab==0 and ba==0:
        print("NO")
        exit()

aba=len(list(re.finditer('ABA',s)))
bab=len(list(re.finditer('BAB',s)))
abab=len(list(re.finditer('ABAB',s)))
baba=len(list(re.finditer('BABA',s)))
if aba>1 or bab>1:
        print("YES")
        exit()
if len(list(re.finditer('BABAB',s)))>=1 or len(list(re.finditer('ABABA',s)))>=1:
        print("YES")
        exit()
if (abab==1 and baba==0 and ab<3 and ba<2)  or (baba==1 and abab==0 and ab<2 and ba <3):
        print("NO")
        exit()
if bab==1 or aba==1:
        if ab>1 or ba>1:
                print("YES")
        else:
                print("NO")
elif bab==0 and aba==0:
        if ab>0 and ba>0:
                print("YES")
        else:
                print("NO")


import re
s=str(input())
ab=[]
ba=[]
aba=[]
bab=[]
cnta=0
cntb=0
for a in list(re.finditer('AB',s)):
    ab.append(a.start())
for b in list(re.finditer('BA',s)):
    ba.append(b.start())
for c in list(re.finditer('ABA',s)):
    if c.start() in ab:
        cnta=cnta+1
for d in list(re.finditer('BAB',s)):
    if d.start() in ba:
        cntb=cntb+1
# print(ab)
# print(ba)
# print(aba)
# print(bab)
if len(ab)-cnta==0 or len(ba)-cntb==0:
    print("NO")
else:
    print("YES")


import re
s=str(input())
ab=len(list(re.finditer('AB',s)))
ba=len(list(re.finditer('BA',s)))

if ab==0 and ba==0:
        print("NO")
        exit()

aba=len(list(re.finditer('ABA',s)))
bab=len(list(re.finditer('BAB',s)))
abab=len(list(re.finditer('ABAB',s)))
baba=len(list(re.finditer('BABA',s)))
if aba>1 or bab>1:
        print("YES")
        exit()
if len(list(re.finditer('BABAB',s)))>=1 or len(list(re.finditer('ABABA',s)))>=1:
        print("YES")
        exit()
if (abab==1 and baba==0 and ab<3 and ba<2)  or (baba==1 and abab==0 and ab<2 and ba <3):
        print("NO")
else:
        print("YES")
        exit()
if bab==1 or aba==1:
        if ab>1 or ba>1:
                print("YES")
        else:
                print("NO")
elif bab==0 and aba==0:
        if ab>0 and ba>0:
                print("YES")
        else:
                print("NO")


import re
s=str(input())
ab=len(list(re.finditer('AB',s)))
ba=len(list(re.finditer('BA',s)))

if ab==0 and ba==0:
        print("NO")

aba=len(list(re.finditer('ABA',s)))
bab=len(list(re.finditer('BAB',s)))
#abab=len(list(re.finditer('ABAB',s)))
#baba=len(list(re.finditer('BABA',s)))
if aba>1 or bab>1:
        print("YES")
if len(list(re.finditer('BABAB',s)))>=1 or len(list(re.finditer('ABABA',s)))>=1:
        print("YES")
if bab==1 or aba==1:
        if ab>1 or ba>1:
                print("YES")
        else:
                print("NO")
elif bab==0 and aba==0:
        if ab>0 and ba>0:
                print("YES")
        else:
                print("NO")


''' ===============================
	-- @uthor : Kaleab Asfaw
	-- Handle : kaleabasfaw2010
	-- Bio    : High-School Student
	==============================='''

# Fast IO
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
	newlines = 0
	def __init__(self, file): self._fd = file.fileno(); self.buffer = BytesIO(); self.writable = "x" in file.mode or "r" not in file.mode; self.write = self.buffer.write if self.writable else None
	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b: break
			ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines = 0; return self.buffer.read()
	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)); self.newlines = b.count(b"\n") + (not b); ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines -= 1; return self.buffer.readline()
	def flush(self):
		if self.writable: os.write(self._fd, self.buffer.getvalue()); self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
	def __init__(self, file): self.buffer = FastIO(file); self.flush = self.buffer.flush; self.writable = self.buffer.writable; self.write = lambda s: self.buffer.write(s.encode("ascii")); self.read = lambda: self.buffer.read().decode("ascii"); self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout); input = lambda: sys.stdin.readline().rstrip("\r\n")
# Others
# from math import floor, ceil, gcd
# from decimal import Decimal as d
mod = 10**9+7
def lcm(x, y): return (x * y) / (gcd(x, y))
def fact(x, mod=mod):
	ans = 1
	for i in range(1, x+1): ans = (ans * i) % mod
	return ans
def arr2D(n, m, default=0):
	lst = []
	for i in range(n): temp = [default] * m; lst.append(temp)
	return lst
def sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])}

def solve(lst):
	n = len(lst)
	overlap = 0
	i = 0
	while i <= n-1:
		if i+2 < n and lst[i] == "A" and lst[i+1] == "B" and lst[i+2] == "A":
			overlap += 1
			i += 3
		elif i+2 < n and lst[i] == "B" and lst[i+1] == "A" and lst[i+2] == "B":
			overlap += 1
			i += 3
		else:
			i += 1
	if overlap >= 2: return "YES"
	count = [0] * 2
	for i in range(n-1):
		if lst[i] == "A" and lst[i+1] == "B":
			if i+2 >= n or lst[i+2] != "A":
				if i-1 < 0 or lst[i-1] != "B":
					count[0] += 1
		if lst[i] == "B" and lst[i+1] == "A":
			if i+2 >= n or lst[i+2] != "B":
				if i-1 < 0 or lst[i-1] != "A":
					count[1] += 1
	if count[0] >= 1 and count[1] >= 1: return "YES"
	if overlap == 1 and count[0] + count[1] >= 1: return "YES"
	return "NO"
lst = input()
print(solve(lst))


''' ===============================
	-- @uthor : Kaleab Asfaw
	-- Handle : kaleabasfaw2010
	-- Bio    : High-School Student
	==============================='''

# Fast IO
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
	newlines = 0
	def __init__(self, file): self._fd = file.fileno(); self.buffer = BytesIO(); self.writable = "x" in file.mode or "r" not in file.mode; self.write = self.buffer.write if self.writable else None
	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b: break
			ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines = 0; return self.buffer.read()
	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)); self.newlines = b.count(b"\n") + (not b); ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines -= 1; return self.buffer.readline()
	def flush(self):
		if self.writable: os.write(self._fd, self.buffer.getvalue()); self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
	def __init__(self, file): self.buffer = FastIO(file); self.flush = self.buffer.flush; self.writable = self.buffer.writable; self.write = lambda s: self.buffer.write(s.encode("ascii")); self.read = lambda: self.buffer.read().decode("ascii"); self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout); input = lambda: sys.stdin.readline().rstrip("\r\n")
# Others
# from math import floor, ceil, gcd
# from decimal import Decimal as d
mod = 10**9+7
def lcm(x, y): return (x * y) / (gcd(x, y))
def fact(x, mod=mod):
	ans = 1
	for i in range(1, x+1): ans = (ans * i) % mod
	return ans
def arr2D(n, m, default=0):
	lst = []
	for i in range(n): temp = [default] * m; lst.append(temp)
	return lst
def sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])}

def solve(lst):
	n = len(lst)
	overlap = 0

	for i in range(n):
		if i+2 < n and lst[i] == "A" and lst[i+1] == "B" and lst[i+2] == "A":
			overlap += 1
		elif i+2 < n and lst[i] == "B" and lst[i+1] == "A" and lst[i+2] == "B":
			overlap += 1
	if overlap >= 2: return "YES"
	count = [0] * 2
	for i in range(n-1):
		if lst[i] == "A" and lst[i+1] == "B":
			if i+2 >= n or lst[i+2] != "A":
				if i-1 < 0 or lst[i-1] != "B":
					count[0] += 1
		if lst[i] == "B" and lst[i+1] == "A":
			if i+2 >= n or lst[i+2] != "B":
				if i-1 < 0 or lst[i-1] != "A":
					count[1] += 1
	if count[0] >= 1 and count[1] >= 1: return "YES"
	if overlap == 1 and count[0] + count[1] >= 1: return "YES"
	return "NO"
lst = input()
print(solve(lst))


''' ===============================
    -- @uthor : Kaleab Asfaw
    -- Handle : kaleabasfaw2010
    -- Bio    : High-School Student
    ==============================='''

# Fast IO
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file): self._fd = file.fileno(); self.buffer = BytesIO(); self.writable = "x" in file.mode or "r" not in file.mode; self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b: break
            ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0; return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)); self.newlines = b.count(b"\n") + (not b); ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1; return self.buffer.readline()
    def flush(self):
        if self.writable: os.write(self._fd, self.buffer.getvalue()); self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file): self.buffer = FastIO(file); self.flush = self.buffer.flush; self.writable = self.buffer.writable; self.write = lambda s: self.buffer.write(s.encode("ascii")); self.read = lambda: self.buffer.read().decode("ascii"); self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout); input = lambda: sys.stdin.readline().rstrip("\r\n")
# Others
# from math import floor, ceil, gcd
# from decimal import Decimal as d
mod = 10**9+7
def lcm(x, y): return (x * y) / (gcd(x, y))
def fact(x, mod=mod):
	ans = 1
	for i in range(1, x+1): ans = (ans * i) % mod
	return ans
def arr2D(n, m, default=0):
	lst = []
	for i in range(n): temp = [default] * m; lst.append(temp)
	return lst
def sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])}

def solve(lst):
	n = len(lst)
	overlap = 0

	for i in range(0, n, 3):
		if i+2 < n and lst[i] == "A" and lst[i+1] == "B" and lst[i+2] == "A":
			overlap += 1
		elif i+2 < n and lst[i] == "B" and lst[i+1] == "A" and lst[i+2] == "B":
			overlap += 1
	if overlap >= 2: return "YES"
	count = [0] * 2
	for i in range(0, n-1, 2):
		if lst[i] == "A" and lst[i+1] == "B":
			if i+2 >= n or lst[i+2] != "A":
				count[0] += 1
		if lst[i] == "B" and lst[i+1] == "A":
			if i+2 >= n or lst[i+2] != "B":
				count[1] += 1
	if count[0] >= 1 and count[1] >= 1: return "YES"
	if overlap == 1 and count[0] + count[1] >= 1: return "YES"
	return "NO"
lst = input()
print(solve(lst))


''' ===============================
	-- @uthor : Kaleab Asfaw
	-- Handle : kaleabasfaw2010
	-- Bio    : High-School Student
	==============================='''

# Fast IO
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
	newlines = 0
	def __init__(self, file): self._fd = file.fileno(); self.buffer = BytesIO(); self.writable = "x" in file.mode or "r" not in file.mode; self.write = self.buffer.write if self.writable else None
	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b: break
			ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines = 0; return self.buffer.read()
	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)); self.newlines = b.count(b"\n") + (not b); ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines -= 1; return self.buffer.readline()
	def flush(self):
		if self.writable: os.write(self._fd, self.buffer.getvalue()); self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
	def __init__(self, file): self.buffer = FastIO(file); self.flush = self.buffer.flush; self.writable = self.buffer.writable; self.write = lambda s: self.buffer.write(s.encode("ascii")); self.read = lambda: self.buffer.read().decode("ascii"); self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout); input = lambda: sys.stdin.readline().rstrip("\r\n")
# Others
# from math import floor, ceil, gcd
# from decimal import Decimal as d
mod = 10**9+7
def lcm(x, y): return (x * y) / (gcd(x, y))
def fact(x, mod=mod):
	ans = 1
	for i in range(1, x+1): ans = (ans * i) % mod
	return ans
def arr2D(n, m, default=0):
	lst = []
	for i in range(n): temp = [default] * m; lst.append(temp)
	return lst
def sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])}

def solve(lst):
	n = len(lst)
	overlap = 0
	i = 0
	while i <= n-1:
		if i+2 < n and lst[i] == "A" and lst[i+1] == "B" and lst[i+2] == "A":
			overlap += 1
			i += 3
		elif i+2 < n and lst[i] == "B" and lst[i+1] == "A" and lst[i+2] == "B":
			overlap += 1
			i += 3
		else:
			i += 1
	if overlap >= 2: return "YES"
	count = [0] * 2
	i = 0
	while i < n-1:
		if lst[i] == "A" and lst[i+1] == "B":
			if i+2 >= n or lst[i+2] != "A":
				count[0] += 1
				i += 2
			else: i += 3
		elif lst[i] == "B" and lst[i+1] == "A":
			if i+2 >= n or lst[i+2] != "B":
				count[1] += 1
				i += 2
			else: i += 3
		else: i += 1
	if count[0] >= 1 and count[1] >= 1: return "YES"
	if overlap == 1 and count[0] + count[1] >= 1: return "YES"
	return "NO"
lst = input()
print(solve(lst))


s=input()
if ("AB" in s) and ("BA" in s) and (s!="ABAB" and s!="BABA"):
    if s.count("AB")>1 or s.count("BA")>1:
        print("YES")
    elif ("ABA" not in s) and ("BAB" not in s):
        print("YES")
    else:
        print("NO")
else:
    print("NO")


s=input()
if ("AB" in s) and ("BA" in s):
    if (s.count("AB")==s.count("BA")) and (s.count("ABA")+s.count("BAB")<s.count("AB")):
        print("YES")
    else:
        print("NO")
else:
    print("NO")


#fed up.....test case ki mkb
s=input()
if ("AB" in s) and ("BA" in s):
    if (s.count("A")==2 and s.count("B")==2):
        if s.count("AABB")!=0 or s.count("ABBA")!=0 or s.count("BBAA")!=0 or s.count("BABA") or s.count("AABB"):
            print("NO")
        else:
            print("YES")
    elif s.count("AB")>1 or s.count("BA")>1:
        print("YES")
    elif ("ABA" not in s) and ("BAB" not in s):
        print("YES")
    else:
        print("NO")
else:
    print("NO")


s=input()
if ("AB" in s) and ("BA" in s):
    if s.count("AB")>1 or s.count("BA")>1:
        print("YES")
    elif ("ABA" not in s) and ("BAB" not in s):
        print("YES")
    else:
        print("NO")
else:
    print("NO")


#fed up
s=input()
if ("AB" in s) and ("BA" in s):
    if (s.count("A")==2 and s.count("B")==2) and (s.count("ABBA")==0 and s.count("BAAB")==0):
        print("NO")
    elif s.count("AB")>1 or s.count("BA")>1:
        print("YES")
    elif ("ABA" not in s) and ("BAB" not in s):
        print("YES")
    else:
        print("NO")
else:
    print("NO")


#fed up
s=input()
if ("AB" in s) and ("BA" in s):
    if (s.count("A")==2 and s.count("B")==2):
        if s.count("AABB")!=0 or s.count("ABAB")!=0 or s.count("BBAA")!=0 or s.count("BABA") or s.count("AABB"):
            print("NO")
        else:
            print("YES")
    elif s.count("AB")>1 or s.count("BA")>1:
        print("YES")
    elif ("ABA" not in s) and ("BAB" not in s):
        print("YES")
    else:
        print("NO")
else:
    print("NO")


s=input()
ai=0
bi=0
flag1,flag2=0,0
if "AB" in s:
    ai=s.index("AB")
else:
    flag1=1
if "BA" in s:
    bi=s.index("BA")
else:
    flag2=1

if ((ai < s.find('BA',ai+2)) or (bi < s.find('AB',bi+2)) and flag1==0 and flag2==0):
    print("YES")
else:
    print("NO")


s=input()
ai=0
bi=0
flag1,flag2=0,0
if "AB" in s:
    ai=s.index("AB")
else:
    flag1=1
if "BA" in s:
    bi=s.index("BA")
else:
    flag2=1

if (((ai < s.find('BA',ai+2)) or (bi < s.find('AB',bi+2))) and flag1==0 and flag2==0):
    print("YES")
else:
    print("NO")


s=input()
ai=0
bi=0
if "AB" in s:
    ai=s.index("AB")
if "BA" in s:
    bi=s.index("BA")

if (ai < s.find('BA',ai+2)) or (bi < s.find('AB',bi+2)):
    print("YES")
else:
    print("NO")


s=input()
ai=0
bi=0

ai=s.index("AB")
bi=s.index("BA")

if (ai < s.find('BA',ai+2)) or (bi < s.find('AB',bi+2)):
    print("YES")
else:
    print("NO")


s=input()
ai=0
bi=0
if "AB" in s:
    ai=s.index("AB")
if "BA" in s:
    bi=s.index("BA")

if ai>bi+1 or bi>ai+1:
    print("YES")
else:
    print("NO")


s=input()
if 'AB' in s and 'BA' in s:
    x=s.index('AB')
    y=s.index('BA')
    if s.count('AB')<=1 or s.count('BA')<=1:
        if y>(x+1) or y<(x-1):
            print('YES')
        else:
            print('NO')
    else:
        print('YES')
else:
    print('NO')


s=input()
if 'AB' in s and 'BA' in s:
    x=s.index('AB')
    y=s.index('BA')
    if s.count('AB')<=1 and s.count('BA')<=1:
        if y>(x+1) or y<(x-1):
            print('YES')
        else:
            print('NO')
    else:
        print('YES')


s=input()
a,b=list(),list()
for i in range(len(s)-1):
    if s[i]=='A' and s[i+1]=='B':
        a.append(i)
    if s[i]=='B' and s[i+1]=='A':
        b.append(i)
if len(a)==0 or len(b)==0:
    print('NO')
elif len(a)==1 or len(b)==1:
    f=0
    for i in a:
        if ((i+1) not in b) and ((i-1) not in b):
            f=1
    if f==1:
        print('YES')
    else:
        print('NO')
else:
    print('YES')


s=input()
a,b=list(),list()
for i in range(len(s)-1):
    if s[i]=='A' and s[i+1]=='B':
        a.append(i)
    if s[i]=='B' and s[i+1]=='A':
        b.append(i)
if len(a)==0 or len(b)==0:
    print('NO')
else:
    f=0
    for i in a:
        for j in b:
            if (i-1)!=j and (i+1)!=j:
                f=1
                break
        if f==1:
            break
    if f==1:
        print('YES')
    else:
        print('NO')


#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################

s = input()
n = len(s)
if n < 4:
	print("NO")
	exit()
ind = -1
for i in range(n-1):
	if s[i] == "A" and s[i+1] == "B":
		ind = i+1
ind2 = -1
for i in range(n-1):
	if s[i] == "B" and s[i+1] == "A":
		ind2 = i
if ind == -1 or ind2 == -1:
	print("NO")
else:
	if ind != ind2:
		print("YES")
	else:
		print("NO")


#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################

s = input()
#print(s)
n = len(s)
if n < 4:
	print("NO")
	exit()

#print(ind,ind3,ind2,ind4)
def check(a):
	ind = -1
	ind3 = -1
	for i in range(n-1):
		if s[i] == a[0] and s[i+1] == a[1]:
			ind3 = i
			ind = i+1
			break
	ind2 = -1
	ind4 = -1
	k = i+1
	for i in range(k,n-1):
		if s[i] == a[1] and s[i+1] == a[0]:
			ind4 = i+1
			ind2 = i
	if ind == -1 or ind2 == -1 or ind3 == -1 or ind4 == -1:
		return False
	else:
		if ind != ind2 and ind3 != ind4:
			return True
		else:
			return False

if check("AB") and check("BA"):
	print("YES")
else:
	print("NO")


#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################

s = input()
#print(s)
n = len(s)
if n < 4:
	print("NO")
	exit()
ind = -1
ind3 = -1
for i in range(n-1):
	if s[i] == "A" and s[i+1] == "B":
		ind3 = i
		ind = i+1
ind2 = -1
ind4 = -1
for i in range(n-1):
	if s[i] == "B" and s[i+1] == "A":
		ind4 = i+1
		ind2 = i
#print(ind,ind3,ind2,ind4)
if ind == -1 or ind2 == -1 or ind3 == -1 or ind4 == -1:
	print("NO")
else:
	if ind != ind2 and ind3 != ind4:
		print("YES")
	else:
		print("NO")


#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################

s = input()
#print(s)
n = len(s)
if n < 4:
	print("NO")
	exit()
ind = -1
ind3 = -1
for i in range(n-1):
	if s[i] == "A" and s[i+1] == "B":
		ind3 = i
		ind = i+1
ind2 = -1
ind4 = -1
for i in range(n-1):
	if s[i] == "B" and s[i+1] == "A":
		ind4 = -1
		ind2 = i
#print(ind,ind2)
if ind == -1 or ind2 == -1 or ind3 == -1 or ind4 == -1:
	print("NO")
else:
	if ind != ind2 and ind3 != ind4:
		print("YES")
	else:
		print("NO")


#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################

s = input()
#print(s)
n = len(s)
if n < 4:
	print("NO")
	exit()

def check(a):
	ind = -1
	ind3 = -1
	for i in range(n-1):
		if s[i] == a[0] and s[i+1] == a[1]:
			ind3 = i
			ind = i+1
			break
	ind2 = -1
	ind4 = -1
	k = i+1
	for i in range(k,n-1):
		if s[i] == a[1] and s[i+1] == a[0]:
			ind4 = i+1
			ind2 = i
	#print(ind,ind3,ind2,ind4)
	if ind == -1 or ind2 == -1 or ind3 == -1 or ind4 == -1:
		return False
	else:
		if ind != ind2 and ind3 != ind4:
			return True
		else:
			return False

if check("AB") or check("BA"):
	print("YES")
else:
	print("NO")


#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

#input = sys.stdin.readline

########################################

s = input()
n = len(s)
if n < 4:
	print("NO")
	exit()
ind = -1
for i in range(n-1):
	if s[i] == "A" and s[i+1] == "B":
		ind = i+1
ind2 = -1
for i in range(n-1):
	if s[i] == "B" and s[i+1] == "A":
		ind2 = i
if ind == -1 or ind2 == -1:
	print("NO")
else:
	if ind != ind2:
		print("YES")
	else:
		print("NO")


#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################

s = input()
#print(s)
n = len(s)
if n < 4:
	print("NO")
	exit()
ind = -1
ind3 = -1
for i in range(n-1):
	if s[i] == "A" and s[i+1] == "B":
		ind3 = i
		ind = i+1
		break
ind2 = -1
ind4 = -1
for i in range(n-1):
	if s[i] == "B" and s[i+1] == "A":
		ind4 = i+1
		ind2 = i
#print(ind,ind3,ind2,ind4)
if ind == -1 or ind2 == -1 or ind3 == -1 or ind4 == -1:
	print("NO")
else:
	if ind != ind2 and ind3 != ind4:
		print("YES")
	else:
		print("NO")


st = input()
ab = False
ba = False
b = False
a = False

for ch in st:
    if ch == 'B':
        if a:
            ab = True
            a = False
            if ba:
                break
        else:
            b = True
    elif ch == 'A':
        if b:
            ba = True
            b = False
            if ab:
                break
        else:
            a = True
    else:
        a, b = False, False
print(["NO", "YES"][ab and ba])


st = input()
ab1 = st.find("AB")
ba1 = st.find("BA")
ab2 = st.rfind("AB")
ba2 = st.rfind("BA")

#print(ab1, ab2, ba1, ba2)

if (ab1 == -1) or (ba1 == -1):
    print("NO")
elif (ab1 == ab2) and (ba1 == ba2) and (abs(ba1 - ab1) < 2):
    print("NO")
else:
    print("YES")


st = input()
ab = False
ba = False
b = False
a = False

for ch in st:
    if ch == 'B':
        if a:
            ab = True
            a = False
            if ba:
                break
        else:
            b = True
    if ch == 'A':
        if b:
            ba = True
            b = False
            if ab:
                break
        else:
            a = True
    a, b = False, False
print(["NO", "YES"][ab and ba])


st = input()
ab1 = st.find("AB")
ba1 = st.find("BA")
ab2 = st.rfind("AB")
ba2 = st.rfind("BA")

#print(ab1, ab2, ba1, ba2)

if (ab1 == -1) or (ba1 == -1):
    print("NO")
elif (ab1 == ab2) and (ba1 == ba2) and (abs(ba1 - ab1) < 2):
    print("NO")
elif (ab1 + 2 == ab2) and (ba1 == ba2):
    print("NO")
elif (ba1 + 2 == ba2) and (ab1 == ab2):
    print("NO")
else:
    print("YES")


import re

st = input()
print(["NO", "YES"][bool(re.match("(AB.*?BA|BA.*?AB)", st))])


import re

st = input()
print(["NO", "YES"][bool(re.match("(AB.*BA|BA.*AB)", st))])


st = input()
ab = False
ba = False
b = False
a = False

for ch in st:
    if ch == 'B':
        if a and not ab:
            ab = True
            a = False
            if ba:
                break
        else:
            b = True
    elif ch == 'A':
        if b and not ba:
            ba = True
            b = False
            if ab:
                break
        else:
            a = True
    else:
        a, b = False, False
print(["NO", "YES"][ab and ba])


"""
    Author - Satwik Tiwari .
    27th Sept , 2020  - Sunday
"""

#===============================================================================================
#importing some useful libraries.

from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil

from copy import deepcopy
from collections import deque

# from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate

from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect

#==============================================================================================
#fast I/O region
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 10**9+7
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for pp in range(t):
        solve(pp)
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))

def solve(case):
    a = inp()
    cnt1 = 0
    cnt2 = 0
    cnt3 = 0
    n = len(a)
    prev = -1
    for i in range(1,n):
        if(i <=n-1 and a[i-1:i+2] == 'ABA' or a[i-1:i+2] == 'BAB' and i>prev+1):
            prev = i
            cnt3 +=1
        elif(a[i-1:i+1] == 'AB' and a[i-2]!='B'):
            cnt1+=1
        elif(a[i-1:i+1] == 'BA' and a[i-2]!='A'):
            cnt2+=1
        # print(cnt1,cnt2,cnt3)
    if(cnt1>0):
        if(cnt2>0):
            print('YES')
        else:
            if(cnt3>0):
                print('YES')
            else:
                print("NO")
    else:
        if(cnt2>0):
            if(cnt3>0):
                print("YES")
            else:
                print("NO")
        else:
            if(cnt3>1):
                print("YES")
            else:
                print("NO")

testcase(1)
# testcase(int(inp()))


"""
    Author - Satwik Tiwari .
    27th Sept , 2020  - Sunday
"""

#===============================================================================================
#importing some useful libraries.

from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil

from copy import deepcopy
from collections import deque

# from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate

from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect

#==============================================================================================
#fast I/O region
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 10**9+7
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for pp in range(t):
        solve(pp)
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))

def solve(case):
    a = inp()
    cnt1 = 0
    cnt2 = 0
    cnt3 = 0
    n = len(a)

    for i in range(1,n):
        if(i <=n-1 and a[i-1:i+2] == 'ABA' or a[i-1:i+2] == 'BAB'):
            cnt3 +=1
        elif(a[i-1:i+1] == 'AB' and a[i-2]!='B'):
            cnt1+=1
        elif(a[i-1:i+1] == 'BA' and a[i-2]!='A'):
            cnt2+=1
        # print(cnt1,cnt2,cnt3)
    if(cnt1>0):
        if(cnt2>0):
            print('YES')
        else:
            if(cnt3>0):
                print('YES')
            else:
                print("NO")
    else:
        if(cnt2>0):
            if(cnt3>0):
                print("YES")
            else:
                print("NO")
        else:
            if(cnt3>1):
                print("YES")
            else:
                print("NO")

testcase(1)
# testcase(int(inp()))


"""
    Author - Satwik Tiwari .
    27th Sept , 2020  - Sunday
"""

#===============================================================================================
#importing some useful libraries.

from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil

from copy import deepcopy
from collections import deque

# from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate

from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect

#==============================================================================================
#fast I/O region
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 10**9+7
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for pp in range(t):
        solve(pp)
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))

def solve(case):
    a = inp()
    cnt1 = 0
    cnt2 = 0
    cnt3 = 0
    n = len(a)
    prev = -1
    for i in range(1,n):
        if(i <=n-1 and (a[i-1:i+2] == 'ABA' or a[i-1:i+2] == 'BAB') and i>prev+1):
            prev = i
            cnt3 +=1
        elif(a[i-1:i+1] == 'AB' and a[i-2]!='B'):
            cnt1+=1
        elif(a[i-1:i+1] == 'BA' and a[i-2]!='A'):
            cnt2+=1
        # print(cnt1,cnt2,cnt3,prev)
    if(cnt1>0):
        if(cnt2>0):
            print('YES')
        else:
            if(cnt3>0):
                print('YES')
            else:
                print("NO")
    else:
        if(cnt2>0):
            if(cnt3>0):
                print("YES")
            else:
                print("NO")
        else:
            if(cnt3>1):
                print("YES")
            else:
                print("NO")

testcase(1)
# testcase(int(inp()))


data = input()
ab_found = False
ba_found = False
count = 0
while count < len(data) - 1 and (not ab_found or not ba_found):
    if data[count: count + 2] == "AB" and not ab_found:
        ab_found = True
        count += 2
    elif data[count: count + 2] == "BA" and not ba_found:
        ba_found = True
        count += 2
    else:
        count += 1
print("YES" if ab_found and ba_found else "NO")


data = input()
abs = []
bas = []

for i in range(len(data) - 1):
    if data[i: i + 2] == "AB":
        abs.append(i)
    elif data[i: i + 2] == "BA":
        bas.append(i)

def is_valid(l1, l2):
    for i in l1:
        for j in l2:
            if j > i + 1:
                return True
    return False

print("YES" if is_valid(abs, bas) or is_valid(bas, abs) else "NO")


data = input()
ab_found = False
ba_found = False
count = 0
while count < len(data) - 1 and (not ab_found or not ba_found):
    if data[count: count + 2] = "AB":
        ab_found = True
        count += 2
    elif data[count: count + 2] = "BA":
        ba_found = True
        count += 2
    else:
        count += 1
print("YES" if ab_found and ba_found else "NO")


data = input()
ab_found = False
ba_found = False
count = 0
while count < len(data) - 1 and (not ab_found or not ba_found):
    if data[count: count + 2] == "AB":
        ab_found = True
        count += 2
    elif data[count: count + 2] == "BA":
        ba_found = True
        count += 2
    else:
        count += 1
print("YES" if ab_found and ba_found else "NO")


s = input()
ab = set()
ba = set()

i = 0
while i < len(s):
    j = s.find('AB', i)
    if j < 0: break
    ab.add(j + 1)
    i = j + 1

i = 0
while i < len(s):
    j = s.find('BA', i)
    if j < 0: break
    ba.add(j)
    i = j + 1

c = ab & ba
d = ab ^ ba

if len(c) > 1 or (ab and ba - c) or (ba and ab - c):
    print('YES')
else:
    print('NO')


def find(s, p, d):
    i = 0
    c = set()

    while i < len(s):
        j = s.find(p, i)
        if j < 0: break
        c.add(j + d)
        i = j + 1

    return c

def check(a, b):
    c = a & b
    d = a ^ b

    return len(c) > 1 or (a and b - c) or (b and a - c)

s = input()

ab1 = find(s, 'AB', 1)
ba1 = find(s, 'BA', 0)

ab2 = find(s, 'AB', 0)
ba2 = find(s, 'BA', 1)

if check(ab1, ba1) and check(ab2, ba2):
    print('YES')
else:
    print('NO')


s = input()
p = s.find('AB')
q = s.find('BA')

if p >= 0 and q >= 0 and (s.find('BA', p + 2) >= 0 or s.find('AB', q + 2) >= 0):
    print('YES')
else:
    print('NO')


s = input()
p = s.find('AB')
q = s.find('BA')

if s.find('BA', p + 2) >= 0 or s.find('AB', q + 2) >= 0:
    print('YES')
else:
    print('NO')


a = input()
q,w= a.count("ABA"),a.count("BAB")
r,t = a.count("AB"),a.count("BA")
if min(r,t)==0 or r+t-(w+q)<2:
	print("NO")
else:
	print("YES")


a = input()
q= a.count("ABA")+a.count("BAB")
if q>1:print("YES")
elif q==1:
	w =  max(a.count("AB"),a.count("BA"))
	if w>1:print("YES")
	else:print("NO")
else:
	x =["A","B"]
	z = None
	for i in range(len(a)-1):
		if a[i] and a[i+1] in x and a[i]!=a[i+1]:
			z = a[i]+a[i+1]
			a = a[:i]+a[i+2:]
			break
	if z :
		if z=="BA":
			e = a.count("AB")
			if e>0:print("YES")
			else:print("NO")
		else:
			e = a.count("BA")
			if e>0:print("YES")
			else:print("NO")
	else:print("NO")


a = input()
q = a.count("AB")
a = a.replace("AB","")
w = a.count("BA")
if min(q,w)>0:print("YES")
else:print("NO")


a = input()
q= a.count("ABA")+a.count("BAB")
r,t = a.count("AB"),a.count("BA")
if q>1:print("YES")
elif q==1:
	w =  max(r,t)
	if w>1:print("YES")
	else:print("NO")
else:
	if min(r,t)>0:print("YES")
	else:print("NO")


s = input()
n = len(s)
b, b1 = [], []
for i in range(n - 1):
    if s[i] == "B" and s[i + 1] == "A":
        b1.append(i)
    if s[i] == "A" and s[i + 1] == "B" :
        b.append(i)
if len(b) >= 2 or len(b1) >= 2 :
    print("YES")
elif len(b) == 1 and len(b1) == 1:
    if b[0] != b1[0] - 1 and b[0] != b1[0] + 1:
        print("YES")
    else :
        print("NO")
else :
    print("NO")


s = input()
n = len(s)
b, b1 = [], []
for i in range(n - 1):
    if s[i] == "B" and s[i + 1] == "A":
        b1.append(i)
    if s[i] == "A" and s[i + 1] == "B" :
        b.append(i)
if len(b) >= 2 or len(b1) >= 2 :
    print("YES")
elif len(b) == 1 and len(b1) == 1:
    if b[0] != b1[0] - 1 :
        print("YES")
    else :
        print("NO")
else :
    print("NO")


s = input()
n = len(s)
b, b1 = [], []
for i in range(n - 1):
    if s[i] == "B" and s[i + 1] == "A":
        b1.append(i)
    if s[i] == "A" and s[i + 1] == "B" :
        b.append(i)
if len(b) >= 2 or len(b1) >= 2 :
    print("YES")
elif len(b) == 1 and len(b1) == 1:
    if b[0] != b1[0] + 1 :
        print("YES")
    else :
        print("NO")
else :
    print("NO")


s = input()
n = len(s)
b, b1 = [], []
for i in range(n - 1):
    if s[i] == "B" and s[i + 1] == "A":
        b1.append(i)
    if s[i] == "A" and s[i + 1] == "B" :
        b.append(i)
for i in range(len(b)):
    c = 0
    if  b[i] - 1 in b1 :
        c += 1
    if b[i] + 1 in b1 :
        c += 1
    if len(b1) > c :
        print("YES")
        exit()
print("NO")


string=input()
s=-1
ans="NO"
if len(string)<2:
    print("NO")

else:
    for i in range(len(string)-1):
        if string[i:i+2]=="AB":
            break

    for j in range(i+2,len(string)-1):
        if string[j:j+2]=="BA":
            ans="YES"

    for i in range(len(string)-1):
        if string[i:i+2]=="BA":
            break

    for j in range(i+2,len(string)-1):
        if string[j:j+2]=="AB":
            ans="YES"

    print(ans)


string=input()
flag=0
s=-1
for i in range(len(string)-1):
    if string[i:i+2]=="AB":
        flag=1
        s=i
        break

if flag==0:
    pass
else:
    for i in range(len(string)-1):
        if string[i:i+2]=="BA" and i!=s-1 and i!=s+1:
            flag=2
if flag==2:
    print("YES")
else:
    print("NO")


string=input()
s=-1
ans="NO"

for i in range(len(string)-1):
    if string[i:i+2]=="AB":
        break

for j in range(i+2,len(string)-1):
    if string[j:j+2]=="BA":
        ans="YES"

for i in range(len(string)-1):
    if string[i:i+2]=="BA":
        break

for j in range(i+2,len(string)-1):
    if string[j:j+2]=="AB":
        ans="YES"

print(ans)


string=input()
s=-1
l1=""
for i in range(len(string)-1):
    if string[i:i+2]=="AB":
        l1+="AB"
    if string[i:i+2]=="BA":
        l1+="BA"

ans="NO"
if l1.find("ABBA")!=-1:
    ans="YES"
if l1.find("BAAB")!=-1:
    ans="YES"
print(ans)


string=input()
flag=0
s=-1
for i in range(len(string)-1):
    if string[i:i+2]=="AB":
        flag=1
        s=i
        break

if flag==0:
    print("NO")
else:
    for i in range(len(string)-1):
        if string[i:i+2]=="BA" and i!=s-1 and i!=s+1:
            flag=2
if flag==2:
    print("YES")
else:
    print("NO")


string=input()
s=-1
ans="NO"
if len(string)<2:
    print("NO")

    else:
    for i in range(len(string)-1):
        if string[i:i+2]=="AB":
            break

    for j in range(i+2,len(string)-1):
        if string[j:j+2]=="BA":
            ans="YES"

    for i in range(len(string)-1):
        if string[i:i+2]=="BA":
            break

    for j in range(i+2,len(string)-1):
        if string[j:j+2]=="AB":
            ans="YES"

    print(ans)


s=str(input())
ab_ba=0
ba_ab=0

i=0
n=len(s)
while i<n-1:
    if s[i]+s[i+1]=="AB":
        if ab_ba==0:
            ab_ba=1
            i+=2
            continue
    if s[i]+s[i+1]=="BA":
        if ab_ba==1:
            ab_ba=2
            i+=2
            continue
    i+=1
i=0
while i<n-1:
    if s[i]+s[i+1]=="BA":
        if ba_ab==0:
            ba_ab=1
            i+=2
            continue
    if s[i]+s[i+1]=="AB":
        if ba_ab==1:
            ba_ab=2
            i+=2
            continue
    i+=1

if ab_ba==2 or ba_ab==2:
    print("YES")
else:
    print("NO")


s=str(input());i=0
flag=False
if s.count('AB')!=0:
    h=s.index('AB')
    for i in range(h+2,len(s)-1):
        if s[i]+s[i+1]=='BA':flag=True
if s.count('BA')!=0:
    h=s.index('BA')
    for i in range(h+2,len(s)-1):
        if s[i]+s[i+1]=='AB':flag=True
if flag:print('YES')
else:
    print('NO')


s=str(input());i=0
ba=False;ab=False;
while i<len(s)-1:
    if s[i]=='A'and s[i+1]=='B'and not ab:
        ab=True;i+=1
    elif s[i]=='B'and s[i+1]=='A'and not ba:
        ba=True;i+=1
    i+=1
if ba*ab:
    print('YES')
else:
    print('NO')


s=str(input())
ba=False;ab=False;p=True
for i in range(len(s)-1):
    if s[i]=='A' and s[i+1]=='B' and p:
        ab=True;p=False
    elif s[i]=='B' and s[i+1]=='A' and p:
        ba=True;p=False
    else:
        p=True
if ba*ab:
    print('YES')
else:
    print('NO')


s=input()
a=s.find('AB')
b=s.rfind('AB')
c=s.find('BA')
d=s.rfind('BA')
if 'AB' in s and 'BA' in s:
    if abs(a-d)>=2 or abs(b-c)>=2:
        print('YES')
    else:
        print('NO')


s=input()
flag=0
if 'AB' in s:
    flag+=1
    i=s.index('AB')
    s=s[:i]+s[i+2:]
if 'BA' in s and flag==1:
    print('YES')
else:
    print('NO')


s=input()
flag=0
if 'AB' in s:
    s=s.replace('AB','')
if 'BA' in s:
    print('YES')
else:
    print('NO')


s=input()
a=s.find('AB')
b=s.rfind('AB')
c=s.find('BA')
d=s.rfind('BA')
if 'AB' in s and 'BA' in s:
    if abs(a-d)>=2 or abs(b-c)>=2:
        print('YES')
    else:
        print('NO')
else:
    print('NO')


s=input()
if 'AB' in s and 'BA' in s:
    print('YES')
else:
    print('NO')


s = list(input())
ind = set()
for i in range(len(s)-1):
    if s[i] == 'A' and s[i+1] == 'B':
        ind.add(i+1)
        break
for j in range(len(s)):
    if j not in ind:
        if s[j] == 'B' and s[j+1] =='A':
            print("YES")
            exit()
print('NO')


s = list(input())
ind = set()
for i in range(len(s)-1):
    if s[i] == 'A' and s[i+1] == 'B':
        ind.add(i+1)
for j in range(len(s)):
    if j not in ind:
        if s[j] == 'B' and s[j+1] =='A':
            print("YES")
            exit()
print('NO')


s = input()
a = s.find("AB")
b = s[a+2:].find("BA")
c = s.find("BA")
d = s[c+2:].find("AB")
if (a >= 0 and b >= 0) or (c >= 0 and d >= 0):
    print("YES")
else:
    print("NO")


s = input()
for i in range(len(s)-1):
    if s[i:i+2] == 'AB':
        x = s.replace('AB', '**', 1)
        if "BA" not in x:
            print('NO')
            exit()
for i in range(len(s)-1):
    if s[i:i+2] == "BA":
        x = s.replace('BA', '**', 1)
        if "AB" not in x:
            print('NO')
            exit()
if s.count('AB') == 0:
    print('NO')
else:
    print('YES')


s = list(input())
ind = set()
for i in range(len(s)-1):
    if s[i] == 'A' and s[i+1] == 'B':
        ind.add(i+1)
        break
for j in range(len(s)-1):
    if j not in ind:
        if s[j] == 'B' and s[j+1] =='A':
            print("YES")
            exit()
print('NO')


def noverlap(s):
    ab = s.count("AB")
    ba = s.count("BA")
    aba = s.count("ABA")
    bab = s.count("BAB")

    if (ab > 1 and ba > 1) or (ab == 1 and ba > 1 and aba + bab == 1) or (ab > 1 and ba == 1 and aba + bab == 1) or (ab == 1 and ba == 1 and aba + bab == 0):
        return "YES"
    return "NO"

print(noverlap(input()))


def noverlap(s):
    ab = s.count("AB")
    ba = s.count("BA")
    aba = s.count("ABA")
    bab = s.count("BAB")

    if (ab > 1 and ba > 1) or (ab > 0 and ba > 0 and aba + bab == 0):
        return "YES"
    return "NO"

print(noverlap(input()))


def noverlap(s):
    ab = s.count("AB")
    ba = s.count("BA")
    aba = s.count("ABA")
    bab = s.count("BAB")
    abab = s.count("ABAB")
    baba = s.count("BABA")

    if (ab > 1 and ba > 1) or (ab == 1 and ba == 2 and baba == 0) or (ab == 2 and ba == 1 and abab == 0) or (ab == 1 and ba > 2) or (ab > 2 and ba == 1) or (ab == 1 and ba == 1 and aba + bab == 0):
        return "YES"
    return "NO"

print(noverlap(input()))


def noverlap(s):
    ab = s.count("AB")
    ba = s.count("BA")
    aba = s.count("ABA")
    bab = s.count("BAB")

    if (ab > 1 and ba > 1) or (ab == 1 and ba > 1 and aba + bab > 0) or (ab > 1 and ba == 1 and aba + bab  > 0) or (ab == 1 and ba == 1 and aba + bab == 0):
        return "YES"
    return "NO"

print(noverlap(input()))


t = input()

if 'BA' not in t:
    print('NO')
elif 'AB' not in t:
    print('NO')
else:
    u=[]
    v=[]
    for k in range(len(t)-1):

        if t[k]=='A' and t[k+1]=='B':
            u.append(k)
        elif t[k]=='B' and t[k+1]=='A':
            v.append(k)

    if min( abs(min(u)-max(v)), abs(min(v)-max(u)) ) >1:
        print('YES')
    else:
        print('NO')


t = input()

if 'BA' not in t:
    print('NO')
elif 'AB' not in t:
    print('NO')
else:
    u=[]
    v=[]
    for k in range(len(t)-1):

        if t[k]=='A' and t[k+1]=='B':
            u.append(k)
        elif t[k]=='B' and t[k+1]=='A':
            v.append(k)

    if  abs(min(u)-max(v))>1 or  abs(min(v)-max(u))  >1:
        print('YES')
    else:
        print('NO')


t = input()

if 'AB' in t:
    if 'BA' in t:
        print('YES')
    else:
        print('NO')
else:
    print('NO')


def func(n):
    a = n.index('AB')
    b = n.index('BA')
    for i in range(a+2,len(n)-1):
        if n[i]+n[i+1] == 'BA':
            print('YES')
            return
    for i in range(b+2,len(n)-1):
        if n[i]+n[i+1] == 'AB':
            print('YES')
            return
    print('NO')
n = input()
func(n)


def func(n):
    if 'AB' in n:
        index = n.index('AB')
        n = n[:index] + n[index+2:]
    else:
        print('NO')
        return
    if 'BA' in n:
        print('YES')
        return
    else:
        print('NO')
        return
n = input()
func(n)


def func(n):
    if 'AB' not in n or 'BA' not in n:
        print('NO')
        return
    a = n.index('AB')
    b = n.index('BA')
    for i in range(a+2,len(n)-1):
        if n[i]+n[i+1] == 'BA':
            print('YES')
            return
    for i in range(b+2,len(n)-1):
        if n[i]+n[i+1] == 'AB':
            print('YES')
            return
    print('NO')
n = input()
func(n)


s = input().strip()
flag = 0
flag1 = 0
i = 0
while i < len(s)-1:
    if s[i:i+2] == 'AB':
        flag = 1
        i += 1
    if s[i:i+2] == 'BA':
        flag1 = 1
        i += 1
    i += 1
if flag and flag1:
    print("YES")
else:
    print("NO")


s = input().strip()
flag = 0
flag1=0
i = 0
while i<n-1:
    if s[i:i+1]=='AB':
        flag=1
        i+=1
    if s[i:i+1]=='BA':
        flag1=1
        i+=1
    i+=1
if flag and flag1:
    print("YES")
else:
    print("NO")


s = input().strip()
flag = 0
flag1 = 0
i = 0
while i < len(s)-1:
    if s[i:i+1] == 'AB':
        flag = 1
        i += 1
    if s[i:i+1] == 'BA':
        flag1 = 1
        i += 1
    i += 1
if flag and flag1:
    print("YES")
else:
    print("NO")


s = input().strip()
l1 = s.find("AB")
l2 = s.find("BA")
if l1==-1 or l2 == -1:
    print("NO")
else:
    k = s[l1+2:].find("BA")
    if k==-1:
        k = s[l2+2:].find("AB")
        if k==-1:
            print("NO")
        else:
            print("YES")
    else:
        print("YES")


s = input().strip()
flag = 0
flag1 = 0
i = 0
while i < len(s)-1:
    if s[i:i+2] == 'AB':
        flag = 1
        i += 1
    elif s[i:i+2] == 'BA':
        flag1 = 1
        i += 1
    i += 1
    # print(i)
if flag and flag1:
    print("YES")
else:
    print("NO")


s=input()
x,y,m,n=-1,-1,-1,-1
x=s.find('AB')
y=s.find('BA',x+2)
m=s.find('BA')
n=s.find('AB',m+2)
if((m>=0 and n>=0) or (x>=0 and y>=0)):
 print("YES")
else:
 print("NO")


X = input()
if "AB" in X:
    Z=X.replace("AB",'1',1)
    Y=X[::-1].replace("BA",'1',1)
    if "BA" in Z or "AB" in Y:
        print("YES")
    else:
        print("NO")
else:
    print("NO")


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        Array.Sort(h);
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            //if (!a[t1] && !a[t2]) { continue; }
            if (IsExists(h, t1)) {
                break;
            } else if (IsExists(h, t2)) {
                Swap(ref a[t1], ref a[t2]);
                break;
            } else {
                Swap(ref a[t1], ref a[t2]);
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }

    private static void Swap(ref bool a, ref bool b) {
        var temp = a;
        a = b;
        b = temp;
    }

    private static bool IsExists<T>(T[] array, int value) {
        var index = Array.BinarySearch(array, value);
        var result = false;
        if (index >= 0) {
            result = true;
        }
        return result;
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        Array.Sort(h);
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            if (!a[t1] && !a[t2]) { continue; }
            if (IsExists(h, t1)) {
                break;
            } else if (IsExists(h, t2)) {
                Swap(ref a[t1], ref a[t2]);
                break;
            } else {
                Swap(ref a[t1], ref a[t2]);
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }

    private static void Swap(ref bool a, ref bool b) {
        var temp = a;
        a = b;
        b = temp;
    }

    private static bool IsExists<T>(T[] array, int value) {
        var index = Array.BinarySearch(array, value);
        var result = false;
        if (index >= 0) {
            result = true;
        }
        return result;
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            if ((h.Contains(t1) && a[t1]) || (h.Contains(t2) && a[t2])) {
                break;
            }
            var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            if (!a[t1] && !a[t2]) { continue; }
            if (Array.BinarySearch(h, t1) >= 0) {
                break;
            } else if (Array.BinarySearch(h, t2) >= 0) {
                var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
                break;
            } else {
                var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        Array.Sort(h);
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            //if (!a[t1] && !a[t2]) { continue; }
            if (a[t1] && Array.BinarySearch(h, t1) >= 0 ) {
                break;
            } else if ((a[t1] || a[t2]) && Array.BinarySearch(h, t2) >= 0 ) {
                Swap(ref a[t1], ref a[t2]);
                break;
            } else {
                Swap(ref a[t1], ref a[t2]);
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }

    private static void Swap(ref bool a, ref bool b) {
        var temp = a;
        a = b;
        b = temp;
    }

    private static bool IsExists<T>(T[] array, int value) {
        var index = Array.BinarySearch(array, value);
        var result = false;
        if (index >= 0) {
            result = true;
        }
        return result;
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        Array.Sort(h);
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            //if (!a[t1] && !a[t2]) { continue; }
            if (IsExists(h, t1) && a[t1]) {
                break;
            } else if (IsExists(h, t2) && a[t2]) {
                Swap(ref a[t1], ref a[t2]);
                break;
            } else {
                Swap(ref a[t1], ref a[t2]);
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }

    private static void Swap(ref bool a, ref bool b) {
        var temp = a;
        a = b;
        b = temp;
    }

    private static bool IsExists<T>(T[] array, int value) {
        var index = Array.BinarySearch(array, value);
        var result = false;
        if (index >= 0) {
            result = true;
        }
        return result;
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            if (!a[t1] && !a[t2]) { continue; }
            if (h.Any(x => x == t1)) {
                break;
            } else if (h.Any(x => x == t2)) {
                var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
                break;
            } else {
                var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            if (!a[t1] && !a[t2]) { continue; }
            if (h.Any(x => x == t1 || x == t2)) {
                break;
            }
            var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(),
            h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true;
        Array.Sort(h);
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1];
            if (!a[t1] && !a[t2]) { continue; }
            if (Array.BinarySearch(h, t1) >= 0) {
                break;
            } else if (Array.BinarySearch(h, t2) >= 0) {
                var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
                break;
            } else {
                var swap = a[t1]; a[t1] = a[t2]; a[t2] = swap;
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(), h = Console.ReadLine().ToIntArray();
        int n = s[0], m = s[1], k = s[2], i = 0;
        var a = new bool[n]; a[0] = true;
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntArray(); int t1 = t[0], t2 = t[1];
            if (h.Contains(t1)) {
                Console.WriteLine(t1); return;
            } else if (h.Contains(t2)) {
                Console.WriteLine(t2); return;
            } else {
                var swap = a[t1 - 1]; a[t1 - 1] = a[t2 - 1]; a[t2 - 1] = swap;
            }
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }
}


using System;
using System.Linq;
static class P {
    static int[] ToIntArray(this string s) { return s.Split().Select(int.Parse).ToArray(); }
    static int[] ToIntDecrementArray(this string s) { return s.Split().Select(x => int.Parse(x) - 1).ToArray(); }
    static void Main() {
        int[] s = Console.ReadLine().ToIntArray(), h = Console.ReadLine().ToIntDecrementArray();
        int n = s[0], k = s[2], i = 0; var a = new bool[n]; a[0] = true; Array.Sort(h);
        while (i++ < k) {
            int[] t = Console.ReadLine().ToIntDecrementArray(); int t1 = t[0], t2 = t[1]; bool temp;
            if ((a[t1] && Array.BinarySearch(h, t1) >= 0) || (a[t2] && Array.BinarySearch(h, t2) >= 0)) {
                break;
            } else if ((a[t1] && Array.BinarySearch(h, t2) >= 0) || (a[t2] && Array.BinarySearch(h, t1) >= 0)) {
                temp = a[t1]; a[t1] = a[t2]; a[t2] = temp;
                break;
            }
            temp = a[t1]; a[t1] = a[t2]; a[t2] = temp;
        }
        for (i = 0; i < n; ++i) {
            if (a[i]) { Console.WriteLine(i + 1); return; }
        }
    }
}


using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Codeforces
{
	internal class Template
	{
		private void Solve()
		{
			var n = cin.NextInt();
			var m = cin.NextInt();
			var k = cin.NextInt();
			var holes = new bool[n + 1];
			for (var i = 0; i < m; i++)
			{
				holes[cin.NextInt()] = true;
			}
			var pos = 1;
			if (holes[pos])
			{
				Console.WriteLine(pos);
				return;
			}
			for (var i = 0; i < k; i++)
			{
				var u = cin.NextInt();
				var v = cin.NextInt();
				if (pos == u)
				{
					pos = v;
				}
				else if (pos == v)
				{
					pos = u;
				}
				if (holes[pos])
				{
					Console.WriteLine(pos);
					return;
				}
			}
			Console.WriteLine(pos);
		}

		private static readonly Scanner cin = new Scanner();

		private static void Main()
		{
#if DEBUG
			var inputText = File.ReadAllText(@"..\..\input.txt");
			var testCases = inputText.Split(new[] { "input" }, StringSplitOptions.RemoveEmptyEntries);
			var consoleOut = Console.Out;
			for (var i = 0; i < testCases.Length; i++)
			{
				var parts = testCases[i].Split(new[] { "output" }, StringSplitOptions.RemoveEmptyEntries);
				Console.SetIn(new StringReader(parts[0].Trim()));
				var stringWriter = new StringWriter();
				Console.SetOut(stringWriter);
				var sw = Stopwatch.StartNew();
				new Template().Solve();
				sw.Stop();
				var output = stringWriter.ToString();

				Console.SetOut(consoleOut);
				var color = ConsoleColor.Green;
				var status = "Passed";
				if (parts[1].Trim() != output.Trim())
				{
					color = ConsoleColor.Red;
					status = "Failed";
				}
				Console.ForegroundColor = color;
				Console.WriteLine("Test {0} {1} in {2}ms", i + 1, status, sw.ElapsedMilliseconds);
			}
			Console.ReadLine();
			Console.ReadKey();
#else
			new Template().Solve();
			Console.ReadLine();
#endif
		}
	}

	internal class Scanner
	{
		private string[] s = new string[0];
		private int i;
		private readonly char[] cs = { ' ' };

		public string NextString()
		{
			if (i < s.Length) return s[i++];
			var line = Console.ReadLine() ?? string.Empty;
			s = line.Split(cs, StringSplitOptions.RemoveEmptyEntries);
			i = 1;
			return s.First();
		}

		public double NextDouble()
		{
			return double.Parse(NextString());
		}

		public int NextInt()
		{
			return int.Parse(NextString());
		}

		public long NextLong()
		{
			return long.Parse(NextString());
		}
	}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cf2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            int n = temp[0], m = temp[1], k = temp[2];
            bool[] holes = new bool[n+1];
            int ans = 1;
            int[] temp2 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            for (int i = 0; i < m; i++)
            {
                holes[temp2[i]] = true;
            }
            if (holes[1] == true)
            {
                Console.WriteLine(ans);
            }
            else
            {
                for (int i = 0; i < k; i++)
                {
                    int[] tt = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                    if (tt[0] != ans) continue;
                    if (holes[tt[1]] == true)
                    {
                        ans = tt[1];
                        break;
                    }
                    else
                    {
                        ans = tt[1];
                    }
                }
                Console.WriteLine(ans);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cf2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            int n = temp[0], m = temp[1], k = temp[2];
            bool[] holes = new bool[n+1];
            int ans = 1;
            int[] temp2 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            for (int i = 0; i < m; i++)
            {
                holes[temp2[i]] = true;
            }
            for (int i = 0; i < k; i++)
            {
                int[] tt= Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                if (holes[tt[1]] == true)
                {
                    ans = tt[1];
                    break;
                }else
                {
                    ans = tt[1];
                }
            }
            Console.WriteLine(ans);

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cf2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            int n = temp[0], m = temp[1], k = temp[2];
            bool[] holes = new bool[n+1];
            int ans = 1;
            int[] temp2 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            for (int i = 0; i < m; i++)
            {
                holes[temp2[i]] = true;
            }
            if (holes[1] == true)
            {
                Console.WriteLine(ans);
            }
            else
            {
                for (int i = 0; i < k; i++)
                {
                    int[] tt = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                    if (holes[tt[1]] == true)
                    {
                        ans = tt[1];
                        break;
                    }
                    else
                    {
                        ans = tt[1];
                    }
                }
                Console.WriteLine(ans);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cf2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            int n = temp[0], m = temp[1], k = temp[2];
            bool[] holes = new bool[n+1];
            int ans = 1;
            int[] temp2 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            for (int i = 0; i < m; i++)
            {
                holes[temp2[i]] = true;
            }
            if (holes[1] == true)
            {
                Console.WriteLine(ans);
            }
            else
            {
                for (int i = 0; i < k; i++)
                {
                    int[] tt = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                    if (tt[0] != ans&&tt[1]!=ans) continue;
                    if (holes[tt[1]] == true)
                    {
                        ans = tt[1];
                        break;
                    }
                    else
                    {
                        ans = tt[1];
                    }
                }
                Console.WriteLine(ans);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cf2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            int n = temp[0], m = temp[1], k = temp[2];
            bool[] holes = new bool[n+1];
            int ans = 1;
            int[] temp2 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            for (int i = 0; i < m; i++)
            {
                holes[temp2[i]] = true;
            }
            if (holes[1] == true)
            {
                Console.WriteLine(ans);
            }
            else
            {
                for (int i = 0; i < k; i++)
                {
                    int[] tt = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                    if (tt[0] != ans&&tt[1]!=ans) continue;
                    if (tt[0] == ans)
                    {
                        if (holes[tt[1]] == true)
                        {
                            ans = tt[1];
                            break;
                        }
                        else
                        {
                            ans = tt[1];
                        }
                    }
                    else
                    {
                        if (holes[tt[0]] == true)
                        {
                            ans = tt[0];
                            break;
                        }
                        else
                        {
                            ans = tt[0];
                        }
                    }

                }
                Console.WriteLine(ans);
            }

        }
    }
}


//796B Find The Bone

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
public class _796B
{
	public static void Main()
	{
		string[] firstLine = Console.ReadLine().Split(' ');
		string[] listHole = Console.ReadLine().Split(' ');

		bool isNeedToTest = false;

		if(firstLine[2]=="300000") isNeedToTest=true;

		bool startCheck = false;
		string currentBonePosition = "1";

		if(listHole.Contains("1"))
		{
			Console.Write("1");
			return;
		}

		//List<string> listSwap = new List<string>();
		for(int i=0;i<int.Parse(firstLine[2]);i++)
		{
			//listSwap.Add(Console.ReadLine());
			string swapSet = Console.ReadLine();
			string firstSwapPosition = swapSet.Split(' ')[0];
			string secondSwapPosition = swapSet.Split(' ')[1];

			if(isNeedToTest) Console.WriteLine(swapSet);

			if(!startCheck)
			{
				if(firstSwapPosition=="1" || secondSwapPosition=="1")
				{
					startCheck = true;
				}
			}

			if(startCheck)
			{
				if(firstSwapPosition==currentBonePosition)
				{
					currentBonePosition = secondSwapPosition;
				}
				else if(secondSwapPosition==currentBonePosition)
				{
					currentBonePosition = firstSwapPosition;
				}

				if(listHole.Contains(currentBonePosition))
				{
					Console.Write(currentBonePosition);
					return;
				}
			}
		}

		//bool startCheck = false;
		//string currentBonePosition = "1";

		//for(int i=0;i<listSwap.Count;i++)
		//{
		//	string firstSwapPosition = listSwap[i].Split(' ')[0];
		//	string secondSwapPosition = listSwap[i].Split(' ')[1];

		//	if(!startCheck)
		//	{
		//		if(firstSwapPosition=="1" || secondSwapPosition=="1")
		//		{
		//			startCheck = true;
		//		}
		//	}

		//	if(startCheck)
		//	{
		//		if(firstSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = secondSwapPosition;
		//		}
		//		else if(secondSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = firstSwapPosition;
		//		}

		//		if(listHole.Contains(currentBonePosition))
		//		{
		//			break;
		//		}
		//	}
		//}

		Console.Write(currentBonePosition);
	}
}


//796B Find The Bone

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
public class _796B
{
	public static void Main()
	{
		string[] firstLine = Console.ReadLine().Split(' ');
		string[] listHole = Console.ReadLine().Split(' ');

		bool startCheck = false;
		string currentBonePosition = "1";

		//if(listHole.Contains("1"))
		//{
		//	Console.Write("1");
		//	return;
		//}

		//List<string> listSwap = new List<string>();
		for(int i=0;i<int.Parse(firstLine[2]);i++)
		{
			//listSwap.Add(Console.ReadLine());
			string swapSet = Console.ReadLine();
			string firstSwapPosition = swapSet.Split(' ')[0];
			string secondSwapPosition = swapSet.Split(' ')[1];

			if(!startCheck)
			{
				if(firstSwapPosition=="1" || secondSwapPosition=="1")
				{
					startCheck = true;
				}
			}

			if(startCheck)
			{
				if(firstSwapPosition==currentBonePosition)
				{
					currentBonePosition = secondSwapPosition;
					if(listHole.Contains(currentBonePosition))
					{
						Console.Write(currentBonePosition);
						return;
					}
				}
				else if(secondSwapPosition==currentBonePosition)
				{
					currentBonePosition = firstSwapPosition;
					if(listHole.Contains(currentBonePosition))
					{
						Console.Write(currentBonePosition);
						return;
					}
				}

				//if(listHole.Contains(currentBonePosition))
				//{
				//	Console.Write(currentBonePosition);
				//	return;
				//}
			}
		}

		//bool startCheck = false;
		//string currentBonePosition = "1";

		//for(int i=0;i<listSwap.Count;i++)
		//{
		//	string firstSwapPosition = listSwap[i].Split(' ')[0];
		//	string secondSwapPosition = listSwap[i].Split(' ')[1];

		//	if(!startCheck)
		//	{
		//		if(firstSwapPosition=="1" || secondSwapPosition=="1")
		//		{
		//			startCheck = true;
		//		}
		//	}

		//	if(startCheck)
		//	{
		//		if(firstSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = secondSwapPosition;
		//		}
		//		else if(secondSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = firstSwapPosition;
		//		}

		//		if(listHole.Contains(currentBonePosition))
		//		{
		//			break;
		//		}
		//	}
		//}

		Console.Write(currentBonePosition);
	}
}


//796B Find The Bone

using System;
using System.Collections.Generic;
using System.Linq;
public class _796B
{
	public static void Main()
	{
		string[] firstLine = Console.ReadLine().Split(' ');
		string[] listHole = Console.ReadLine().Split(' ');

		bool startCheck = false;
		string currentBonePosition = "1";

		//List<string> listSwap = new List<string>();
		for(long i=0;i<int.Parse(firstLine[2]);i++)
		{
			//listSwap.Add(Console.ReadLine());
			string swapSet = Console.ReadLine();
			string firstSwapPosition = swapSet.Split(' ')[0];
			string secondSwapPosition = swapSet.Split(' ')[1];

			if(!startCheck)
			{
				if(firstSwapPosition=="1" || secondSwapPosition=="1")
				{
					startCheck = true;
				}
			}

			if(startCheck)
			{
				if(firstSwapPosition==currentBonePosition)
				{
					currentBonePosition = secondSwapPosition;
				}
				else if(secondSwapPosition==currentBonePosition)
				{
					currentBonePosition = firstSwapPosition;
				}

				if(listHole.Contains(currentBonePosition))
				{
					break;
				}
			}
		}

		//bool startCheck = false;
		//string currentBonePosition = "1";

		//for(int i=0;i<listSwap.Count;i++)
		//{
		//	string firstSwapPosition = listSwap[i].Split(' ')[0];
		//	string secondSwapPosition = listSwap[i].Split(' ')[1];

		//	if(!startCheck)
		//	{
		//		if(firstSwapPosition=="1" || secondSwapPosition=="1")
		//		{
		//			startCheck = true;
		//		}
		//	}

		//	if(startCheck)
		//	{
		//		if(firstSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = secondSwapPosition;
		//		}
		//		else if(secondSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = firstSwapPosition;
		//		}

		//		if(listHole.Contains(currentBonePosition))
		//		{
		//			break;
		//		}
		//	}
		//}

		Console.Write(currentBonePosition);
	}
}


//796B Find The Bone

using System;
using System.Collections.Generic;
using System.Linq;
public class _796B
{
	public static void Main()
	{
		string[] firstLine = Console.ReadLine().Split(' ');
		string[] listHole = Console.ReadLine().Split(' ');

		bool startCheck = false;
		string currentBonePosition = "1";

		//List<string> listSwap = new List<string>();
		for(int i=0;i<int.Parse(firstLine[2]);i++)
		{
			//listSwap.Add(Console.ReadLine());
			string swapSet = Console.ReadLine();
			string firstSwapPosition = swapSet.Split(' ')[0];
			string secondSwapPosition = swapSet.Split(' ')[1];

			if(!startCheck)
			{
				if(firstSwapPosition=="1" || secondSwapPosition=="1")
				{
					startCheck = true;
				}
			}

			if(startCheck)
			{
				if(firstSwapPosition==currentBonePosition)
				{
					currentBonePosition = secondSwapPosition;
				}
				else if(secondSwapPosition==currentBonePosition)
				{
					currentBonePosition = firstSwapPosition;
				}

				if(listHole.Contains(currentBonePosition))
				{
					Console.Write(currentBonePosition);
					return;
				}
			}
		}

		//bool startCheck = false;
		//string currentBonePosition = "1";

		//for(int i=0;i<listSwap.Count;i++)
		//{
		//	string firstSwapPosition = listSwap[i].Split(' ')[0];
		//	string secondSwapPosition = listSwap[i].Split(' ')[1];

		//	if(!startCheck)
		//	{
		//		if(firstSwapPosition=="1" || secondSwapPosition=="1")
		//		{
		//			startCheck = true;
		//		}
		//	}

		//	if(startCheck)
		//	{
		//		if(firstSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = secondSwapPosition;
		//		}
		//		else if(secondSwapPosition==currentBonePosition)
		//		{
		//			currentBonePosition = firstSwapPosition;
		//		}

		//		if(listHole.Contains(currentBonePosition))
		//		{
		//			break;
		//		}
		//	}
		//}

		Console.Write(currentBonePosition);
	}
}