import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var h: number;
    var w: number;
    var ch: number;
    var cw: number;
    var dh: number;
    var dw: number;
    var shw: string[][];
    var ans;
    // init
    [h, w] = input.shift().split(" ").map(x => Number(x));
    [ch, cw] = input.shift().split(" ").map(x => Number(x) - 1);
    [dh, dw] = input.shift().split(" ").map(x => Number(x) - 1);
    shw = [];
    for (var hx = 0; hx < h; hx++) {
        shw[hx] = ("##" + input[hx] + "##").split("");
    }
    h += 4;
    w += 4;
    ch += 2;
    cw += 2;
    dh += 2;
    dw += 2;
    shw.unshift(new Array(w).fill("#"));
    shw.unshift(new Array(w).fill("#"));
    shw.push(new Array(w).fill("#"));
    shw.push(new Array(w).fill("#"));
    // console.debug(h, w, ch, cw, dh, dw);
    // console.debug(shw.map(x => x.join("")).reduce(((x, y) => x + "\n" + y)));
    // solve
    var patn = [
        [-1, +0],
        [+0, +1],
        [+1, +0],
        [+0, -1]
    ];
    var patw = [
        [-2, -2],
        [-2, -1],
        [-2, +0],
        [-2, +1],
        [-2, +2],
        [-1, -2],
        [-1, -1],
        [-1, +1],
        [-1, +2],
        [+0, -2],
        [+0, +2],
        [+1, -2],
        [+1, -1],
        [+1, +1],
        [+1, +2],
        [+2, -2],
        [+2, -1],
        [+2, +0],
        [+2, +1],
        [+2, +2]
    ];
    var que = [[ch, cw]];
    var warp = 0;
    while (true) {
        var que0 = [];
        while (0 < que.length) {
            var cur = que.pop();
            que0.push(cur)
            shw[cur[0]][cur[1]] = warp.toString();
            for (var patnx = 0; patnx < patn.length; patnx++) {
                var s = [cur[0] + patn[patnx][0], cur[1] + patn[patnx][1]];
                var c = shw[s[0]][s[1]];
                if (c == "." || c == "_") que.push(s);
            }
        }
        // console.debug(que, que0);
        while (0 < que0.length) {
            var cur = que0.pop();
            // console.debug("----");
            shw[cur[0]][cur[1]] = "_";
            for (var patwx = 0; patwx < patw.length; patwx++) {
                var s = [cur[0] + patw[patwx][0], cur[1] + patw[patwx][1]];
                var c = shw[s[0]][s[1]];
                // console.debug(s[0], s[1], c);
                if (c == ".") que.push(s);
            }
        }
        if (que.length == 0) break;
        warp++;
    }
    // console.debug(h, w, ch, cw, dh, dw);
    // console.debug(shw.map(x => x.join("")).reduce(((x, y) => x + "\n" + y)));
    var s = [dh, dw];
    var c = shw[s[0]][s[1]];
    ans = (c == ".") ? -1 : warp;
    // answer
    console.log(ans);
}

// math library
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    return ans;
}

// union-find library
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}

// entrypoint
function entrypoint() {
    try {
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        console.log("file='%s'", __filename.split("\\").slice(-1)[0]);
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            console.log("input=%o", input);
            console.time();
            main(input);
            console.timeEnd();
        });
    }
}
entrypoint();


ans = 0
s = input()
for s_ in list(s):
    if s_ == '+':
        ans += 1

    else:
        ans -= 1

print(ans)


a = input()
print(a.count("+") - a.count("-"))


S=input()
for i in range(len(S)):
  S=S[:2*i+1]+"1"+S[2*i+1:]
print(eval("0"+S))


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

ans = pow(10, 9)
for i in range(n - k + 1):
    tmp = min(abs(x[i]), abs(x[i + k - 1]))
    ans = min(ans, tmp + x[i + k - 1] - x[i])
print(ans)


s = list(map(str, input()))
a = s.count(+)
b = s.count(-)
print(a - b)


s = map(int, input().split(1))
a = s.count(+)
b = s.count(-)
print(a - b)


import java.io.*;
import java.util.*;
import java.math.*;
class Main
{
	public static int M = 1000000007;
    public static void main(String[] args)throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        String s = br.readLine();
        int n=0;
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)=='+')
                n++;
            else
                n--;
        }
        out.println(n);
        out.flush();
    }
    /** Loops
    *	i: for(int i=0;i<n;i++)
    *	j: for(int j=0;j<n;j++)
    *	k: for(int k=0;k<n;k++)

    *	ArrayList<Integer> arr1 = new ArrayList<>();

    * 	HashMap
    *	HashMap<Integer, Integer> hm = new HashMap<>();
    * 	for (Map.Entry<String,String> entry : hm.entrySet())
    		out.println(entry.getValue());

    *	Count frequencies
    	for(int i=0;i<n;i++)
        {
            Integer c = hm.get(Integer.parseInt(s[i]));
            if(c==null)
                hm.put(Integer.parseInt(s[i]),1);
            else
                hm.put(Integer.parseInt(s[i]),++c);
        }
	**/
    public static long modularExpo(long x,long n,int M)
	{
		long result=1;
		while(n>0)
		{
		    if(n%2==1)
		        result=(result*x)%M;
		    x=(x*x)%M;
		    n=n/2;
		}
		return result;
	}
	//FLT, only when a and M are co-prime
	public static long modInverse(int a,int M)
	{
		long g = gcd(a,M);
		if(g!=1)
			return -1;
	    return modularExpo(a,M-2,M);
	}
	public static long gcd(int a, int b)
	{
	    if(b==0)
	        return a;
	    else
	        return gcd(b, a % b);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws Exception {
	    String line = Io.read();

	    int answer = 0;
	    for (int i = 0; i < line.length(); i++) {
	        if (line.charAt(i) == '+') answer++;
	        else answer--;
        }

        Io.write(answer);
    }
}

class Io {

    public static String read() throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        br.close();
        return line;
    }

    public static void write(int answer)
    {
        System.out.println(answer);
    }
}


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

class Main {
  public static void main(String[] args)throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      char[] a=br.readLine().toCharArray();
      long count=0;
      for(int i=0;i<a.length;i++){
        if(a[i]=='+')
         count++;
        else
        count--;
      }
      System.out.println(count);
    }
  }


package abc101.a;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        String chara = scan.nextLine();
        int count = 0;
        for (char c :chara.toCharArray()) {
            if (c == '+') {
                count++;
            } else {
                count--;
            }
        }
        System.out.println(count);
    }
}


import java.util.*;

public class Main {

  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    int x = 0;
    String str = scan.next();

    for (int i = 0; i <= 4; i++) {
      char ch = str.charAt(i);

      if (ch == '+') {
        x = x + 1;
      }

      if (ch == '-') {
        x = x - 1;
      }
    }

    System.out.println(x);
  }
}


import java.util.*;

public class Main {

  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    int x = 0;
    String str = scan.next();
    String plus = "+";
    String minus = "-";

    for (int i = 0; i <= 4; i++) {
      char ch = str.charAt(i);

      if (ch.equals(plus)) {
        x = x + 1;
      }

      if (ch.equals(minus)) {
        x = x - 1;
      }
    }

    System.out.println(0);
  }
}


#include <stdio.h>

int main(void){
  char input;
  int count = 0;
  for(int i = 0; i < 4; i++){
    input = getchar();
    if(input == '+')
      count++;
    else
      count--;
  }
  printf("%d\n", count);
}


#include <cstdio>
char s[7];
int Ans;
int main(){
	scanf("%s",s);
	for (char *i=s;*i;++i) if (*i=='+') ++Ans; else --Ans;
	printf("%d",Ans);
	return 0;
}


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <string>
#define SIZE 200005
#define INF 1000000005LL

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

int n;
ll K;

int main()
{
	char a;
	int ans=0;
	for(int i=0;i<4;i++){
		scanf("%c",&a);
		if(a == '+')ans ++;
		else ans--;
	}
	printf("%d\n",ans);
	return 0;
}


#include <bits/stdc++.h>
//#include <atcoder/all>
#define rep(i, n) for (int i=0; i < (n); i++)
using namespace std;
//using namespace atcoder;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int, int> P;
const int INF = 1 << 30;
const ll LINF = 1LL << 61;
const int NIL = -1;
const int MAX = 10000;
const int MOD = 1000000007;
const double pi = 3.141592653589;

int main() {
    string s;
    int ans = 0;
    cin >> s;
    rep(i,4){
        if(s[i] == '+')ans += 1;
        else ans -= 1;
    }
    return 0;
}


#include <bits/stdc++.h>
//#include <atcoder/all>
#define rep(i, n) for (int i=0; i < (n); i++)
using namespace std;
//using namespace atcoder;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int, int> P;
const int INF = 1 << 30;
const ll LINF = 1LL << 61;
const int NIL = -1;
const int MAX = 10000;
const int MOD = 1000000007;
const double pi = 3.141592653589;

int main() {
    string s;
    int ans = 0;
    cin >> s;
    rep(i,4){
        if(s[i] = '+')ans += 1;
        else ans -= 1;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main() {
  string a;
  ll b=0;
  ll c=0;
  for(ll i=0;i<4;i++){
    if(a.at(i)=='+'){
      b+=1;
    }
    else{
      c+=1;
    }
  }
  cout<<b-c<<endl;

  return 0;
}


#include <stdio.h>
int main(void)
{
	char s[4];
	int t;
	int takahasi = 0;

	scanf("%s", s);

	for (t = 0; t < 4; t++){
		 if (s[t] == '+'){
		 	takahasi++;
		 }

		 else if (s[t] == '-'){
		 	takahasi--;
		 }

	}

	printf("%d", takahasi);

	return 0;
}


#include<stdio.h>
int main()
{
    char s[5];
    scanf("%s", s);
    int i;
    int ans = 0;
    for (i = 0; i < 4; i++)
    {
        if (s[i] == '+')
            ans++;
        else
            ans--;
    }
    printf("%d\n", ans);
    return 0;
}


#include <stdio.h>

int main(void)
{
    int n;
    char str[5];
    int i;

    scanf("%s", str);

    n = 0;
    for(i = 0; str[i] != '\0'; i++){
        if(str[i] == '+'){
            n++;
        }
        else{
            n--;
        }
    }

    printf("%d\n", n);

    return(0);
}


#include<iostream>

using namespace std;

int main(){
    char S[5];
    scanf("%s", S);
    int sum=0;
    for(int i=0; i<4; i++){
        if(S[i]=='-')sum--;
        else sum++;
    }
    printf("%d\n", sum);
    return 0;
}


#include<stdio.h>

int main(void){
  char s[3];
  scanf("%s",s);
  int c=0;
  for(int i=0;i<4;i++){
    if(s[i]=='+'){
      c++;
    }else{
      c--;
    }
  }
    printf("%d",c);
   return 0;
}


#include<stdio.h>

int main(void){
  char s[20];
  scanf("%s",s);
  int c=0;
  for(int i=0;i<5;i++){
    if(s[i]=='+'){
      c++;
    }else{
      c--;
    }
  }
    printf("%d",c);
   return 0;
}


var input = require("fs").readFileSync("/dev/stdin","utf-8").trim();
var num=0;
for(var i=0;i<input.length;i++){
	if(input[i]==="+") num++;
  	if(input[i]==="-") num--;
}
console.log(num);


function main(input) {

    input = input.split('\n')[0].split('');
    var plus = 0;
    var minus = 0;
    for (var i = 0; i < input.length; i++) {
        if (input[i] == '+') plus++;
        else minus++;
    }

    console.log(plus - minus)

}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  var s = 0;
  var result = input.split('');

  for (var i = 0; i < 4; i++) {
    if(result[i] === '+') {
      s++;
    } else if(result[i] === '-') {
      s--;
    }
  }
  console.log(s);
}

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


const main = (arg) => {
  const lines = arg.trim().split('\n');
  const S = lines[0];
  let ans = 0;
  S.forEach((c) => {
    ans += c === '+' ? 1 : -1;
  });
  console.log(ans);
};
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  const N = parseInt(input, 10);
  (N % 2 === 0) ? console.log(N) : console.log(N * 2);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  const S = input.split('');
  let ans = 0;

  for (let i = 0; i < S.length; i++) {
    S[i] === '+' ? ans++ : ans--;
  }

  console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


package main

import (
	"fmt"
)

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

	ans := 0
	for _, v := range s {
		if string(v) == "+" {
			ans++
		} else {
			ans--
		}
	}
	fmt.Println(ans)

}


package main

import (
    . "fmt"
    "strings"
)

func main() {
    var s string
    Scanf("%s", &s)

    ans := 0
    ss := strings.Split(s, "")
    for _, v := range ss {
        if v == "+" {
            ans++
        } else if v == "-" {
            ans--
        }
    }
    Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	// "regexp"
)

/* sort */
type pair struct {
	index  int64
	p1, p2 interface{}
}
type pairs []pair

func (slice pairs) Len() int {
	return len(slice)
}

func (slice pairs) Less(i, j int) bool {
	return slice[i].index < slice[j].index
}

func (slice pairs) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

/* sort */
type Int64Slice []int64

func (slice Int64Slice) Len() int {
	return len(slice)
}

func (slice Int64Slice) Less(i, j int) bool {
	return slice[i] < slice[j]
}

func (slice Int64Slice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}
func Int64s(a []int64)                    { sort.Sort(Int64Slice(a)) }
func Int64sSliceAreSorted(a []int64) bool { return sort.IsSorted(Int64Slice(a)) }

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
	INF            = 1e8
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	di      = []int64{-1, 0, 1, 0}
	dj      = []int64{0, -1, 0, 1}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	S := readString()
	ans := 0
	for i := 0; i < len(S); i++ {
		if S[i] == '+' {
			ans++
		} else {
			ans--
		}
	}
	fmt.Println(ans)
}

/*==========================================
 *             Library
 *==========================================*/
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}
func doubleAry(h int64, w int64, init int64) (res [][]int64) {
	res = make([][]int64, h)
	for i := int64(0); i < h; i++ {
		res[i] = make([]int64, w)
		for j := int64(0); j < w; j++ {
			res[i][j] = init
		}
	}
	return
}

func aryEq(a []int64, b []int64) bool {
	return reflect.DeepEqual(a, b)
}

func clone(n []int64) (r []int64) {
	r = make([]int64, len(n))
	for i := 0; i < len(n); i++ {
		r[i] = n[i]
	}
	return
}
func write(s string) {
	writer.WriteString(s)
}

func print() {
	writer.Flush()
}

// scanner.Split(bufio.ScanWords) をコメントアウトしないと使用不可
func readLine() (s string) {
	if scanner.Scan() {
		s = scanner.Text()
	}
	return s
}

func readInt() (read int64) {
	scanner.Scan()
	read, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func readFloat() (read float64) {
	scanner.Scan()
	read, err := strconv.ParseFloat(scanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return
}

func readRunes() (read []rune) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, v)
	}
	return
}

func readString() (read string) {
	scanner.Scan()
	read = scanner.Text()
	return
}

func readStrings() (read []string) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, string(v))
	}
	return
}

func s2i(s string) int64 {
	var intVal, e = strconv.ParseInt(s, 10, 64)
	if e != nil {
		panic(e)
	}
	return intVal
}

func i2s(i int64) string {
	var strVal = strconv.FormatInt(i, 10)
	return strVal
}

func s2f(s string) float64 {
	var floatVal, e = strconv.ParseFloat(s, 64)
	if e != nil {
		panic(e)
	}
	return floatVal
}

func abs(i int64) int64 {
	return int64(math.Abs(float64(i)))
}

func max(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans < v {
			ans = v
		}
	}
	return ans
}
func min(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans > v {
			ans = v
		}
	}
	return ans
}

func sum(i []int64) int64 {
	sum := int64(0)
	for _, val := range i {
		sum += val
	}
	return sum
}

func split(s string) []string {
	return strings.Fields(s)
}

func strAry2intAry(strs []string) []int64 {
	var ret = make([]int64, 0, len(strs))
	for _, str := range strs {
		var intVal = s2i(str)
		ret = append(ret, intVal)
	}
	return ret
}

func intAry2strAry(nums []int64) []string {
	var ret = make([]string, 0, len(nums))
	for _, num := range nums {
		var strVal = i2s(num)
		ret = append(ret, strVal)
	}
	return ret
}

func ary2str(strs []string) string {
	return strings.Join(strs, " ")
}

func reverse(res []int64) []int64 {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
func reverseStr(res []string) []string {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}

func ini(res []int, init int) {
	if len(res) == 0 {
		return
	}
	res[0] = init
	for i := 0; i < len(res); i++ {
		copy(res[i:], res[:i])
	}
}

//
// func regexpExample() {
//     // Your code here!
//     var str = "13:20"
//     r := regexp.MustCompile(`(\d+):(\d+)`)
//     fmt.Println(r.FindStringSubmatch(str))
// }

// type Country struct {
//     gold int
//     silver int
//     blonze int
// }

// // 複数ソートのサンプル
// func stableSortExample() []Country{
//     var country = []Country {
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:3, blonze:2},
//         {gold:1, silver:3, blonze:3},
//     }
//     sort.SliceStable(country, func(i, j int) bool { return country[i].blonze > country[j].blonze })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].silver > country[j].silver })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].gold > country[j].gold })
//     return country
// }


// https://atcoder.jp/contests/abc101/tasks/abc101_a

package main

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

func main() {
  scanner := bufio.NewScanner(os.Stdin)
  scanner.Scan()
  S := scanner.Text()

  n := 4
  res := 0
  for i := 0; i < n; i++ {
    if string(S[0]) == "+" {
      res++
    } else {
      res--
    }
  }

  fmt.Println(res)
}

type Io struct {
  reader *bufio.Reader
  writer *bufio.Writer
  tokens []string
  nextToken int
}

func NewIo() *Io {
  return &Io{
    reader: bufio.NewReader(os.Stdin),
    writer: bufio.NewWriter(os.Stdout),
  }
}

func (io *Io) Next() string {
  if io.nextToken >= len(io.tokens) {
    line := io.NextLine()
    io.tokens = strings.Fields(line)
    io.nextToken = 0
  }

  res := io.tokens[io.nextToken]
  io.nextToken++
  return res
}

func (io *Io) NextInt() int {
  res, err := strconv.Atoi(io.Next())
  if err != nil {
    panic(err)
  }
  return res
}

func (io *Io) NextStrings(n int) []string {
  res := make([]string, n)
  for i := 0; i < n; i++ {
    res[i] = io.Next()
  }
  return res
}

func (io *Io) Println(a ...interface{}) {
  var values []string
  for i := 0; i < len(a); i++ {
    values = append(values, "%v")
  }
  io.Printfln(strings.Join(values, " "), a...)
}

func (io *Io) Printfln(format string, a ...interface{}) {
  fmt.Fprintf(io.writer, format+"\n", a...)
}

func (io *Io) NextLine() string {
  if io.nextToken < len(io.tokens) {
    panic("io.nextToken < len(io.tokens)")
  }

  var buffer bytes.Buffer

  for {
    line, isPrefix, err := io.reader.ReadLine()
    if err != nil {
      panic(err)
    }
    buffer.Write(line)
    if !isPrefix {
      break
    }
  }

  return buffer.String()
}


package main

import "fmt"

func main(){
  var s string
  fmt.Scan(&s)
  cnt := 0
  for _, x := range s {
    switch x {
    case "+": cnt++
    case "-": cnt--
    }
  }
  fmt.Println(cnt)
}


package main

import (
    "fmt"
    "os"
    "strings"
)

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

    fmt.Fprint(os.Stdin, strings.Count(s, "+") - strings.Count(s, "-"))
}


s = gets.chomp

print("#{2 * s.count('+') - 4}")


s = gets.chomp.chars
ans = 0
s.each do |ss|
  if ss == "+"
    ans += 1
  else
    ans -= 1
  end
end

puts ans


a=gets.chomp.count("+");p (0 + a) - (4 - a)


s = gets.chomp
p s.size - s.count("-")


r = 0
gets.chomp.chars.do |c|
  r += (c == "+") ? 1 : -1
end
p r


int = 0
S = ["+", "-", "+", "+"]

if S[0] == "+" then
  int+=1
else
  int-=1
end
if S[1] == "+" then
  int+=1
else
  int-=1
end
if S[2] == "+" then
  int+=1
else
  int-=1
end
if S[3] == "+" then
  int+=1
else
  int-=1
end

print int


#[allow(unused_macros, dead_code)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros, dead_code)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros, dead_code)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(dead_code)]
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
    size: Vec<usize>,
}

#[allow(dead_code)]
impl UnionFind {
    fn new(n: usize) -> UnionFind {
        let mut p = vec![0; n];
        for i in 0..n {
            p[i] = i;
        }
        return UnionFind {
            parent: p,
            rank: vec![0; n],
            size: vec![1; n],
        };
    }

    fn find(&mut self, x: usize) -> usize {
        if x == self.parent[x] {
            x
        } else {
            let p = self.parent[x];
            let pr = self.find(p);
            self.parent[x] = pr;
            pr
        }
    }

    fn same(&mut self, a: usize, b: usize) -> bool {
        self.find(a) == self.find(b)
    }

    fn unite(&mut self, a: usize, b: usize) {
        let a_root = self.find(a);
        let b_root = self.find(b);
        if a_root == b_root {
            return;
        }
        if self.rank[a_root] > self.rank[b_root] {
            self.parent[b_root] = a_root;
            self.size[a_root] += self.size[b_root];
        } else {
            self.parent[a_root] = b_root;
            self.size[b_root] += self.size[a_root];
            if self.rank[a_root] == self.rank[b_root] {
                self.rank[b_root] += 1;
            }
        }
    }

    fn get_size(&mut self, x: usize) -> usize {
        let root = self.find(x);
        self.size[root]
    }
}

const MOD_P: usize = 1000000007;

#[allow(dead_code)]
// fact(n) = n! mod p
fn fact(n: usize) -> usize {
    let mut acc = 1;
    for i in 1..n + 1 {
        acc = acc * i % MOD_P;
    }
    acc
}

#[allow(dead_code)]
fn mod_pow(b: usize, mut e: usize) -> usize {
    let mut base = b;
    let mut acc = 1;

    while e > 1 {
        if e % 2 == 1 {
            acc = acc * base % MOD_P;
        }
        e /= 2;
        base = base * base % MOD_P;
    }

    if e == 1 {
        acc = acc * base % MOD_P;
    }

    acc
}

#[allow(dead_code)]
fn comb(n: usize, r: usize) -> usize {
    // nCr = n! / (r! (n-r)!) = n! (r!)^(p-2) ((n-r)!)^(p-2)
    let x = ((n - r + 1)..(n + 1)).fold(1, |p, x| p * x % MOD_P);
    let y = mod_pow(fact(r), MOD_P - 2);
    x * y % MOD_P
}

#[allow(dead_code)]
fn gcd(a: usize, b: usize) -> usize {
    if b > a {
        gcd(b, a)
    } else if a % b == 0 {
        b
    } else {
        gcd(b, a % b)
    }
}

#[allow(dead_code)]
fn getline() -> String {
    let mut __ret = String::new();
    std::io::stdin().read_line(&mut __ret).ok();
    return __ret;
}

use std::cmp::{max, min};

fn main() {
    input! {
        s: chars,
    }
    let ans = s
        .iter()
        .fold(0, |acc, &c| acc + if c == '+' { 1 } else { -1 });
    println!("{}", ans);
}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s = buf.trim().chars().collect::<Vec<char>>();
	let mut ret:i32 = 0;
	for i in s {
		if i == '+' {
			ret += 1;
		}else{
			ret -= 1;
		}
	}
	println!("{}", ret);
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main(){

    input!{
        s:chars,
    }

    let mut ans = 0;

    for i in s{
        if i=='+' {
            ans += 1;
        } else {
            ans -= 1;
        }
    }

    println!("{}", ans);

}


//入力マクロここから
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
macro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
//入力マクロここまで

fn main() {
    input! {
        n: usize,
        k: usize,
        _a: [u64;n],
    }

    let ans = if n % (k - 1) == 0 {
        n / (k - 1)
    } else {
        n / (k - 1) + 1
    };

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


use std::str::FromStr;
use std::fmt::Debug;
use std::cmp;
#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()

}

#[allow(dead_code)]
fn read_as_string() -> String{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

fn main(){
    let s = read_as_string().chars().collect::<Vec<char>>();

    println!("{}", s.iter().filter(|x| **x == '+').count()*2 - s.len());
}


// Template from https://techracho.bpsinc.jp/jhonda/2019_08_05/78537

// input macro for competive-programming from https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };

    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($next:expr, [ $t:tt ]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
        }
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, bytes) => {
        read_value!($iter, String).into_bytes()
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    use std::io::Read;
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).unwrap();

    println!("{}", solve(&s));
}

macro_rules! test {
    ($($input:expr => $output:expr),* $(,)*) => {
        #[test]
        fn solve_test() {
            $(
                assert_eq!(solve($input), $output);
            )*
        }
    };
}

test! {
// r#"2018 218"# => "Yes",
// r#"2763 0"# => "No",
r#"999"# => "ABC",

}

fn solve(src: &str) -> String {
    input! {
        source = src,
        s: chars,
    }

    let mut ans:i64 = 0;

    for i in 0..s.len() {
        if s[i] == '+' {
            ans += 1;
        } else {
            ans += 0;
        }
    }

    ans.to_string()
}


var i=0;readLine()!.characters.forEach{String($0)=="+" ?i++:i--};print(i)


let s = Array(readLine()!.characters)
var ans = 0
for i in 0...3 {
  ans += s[i] == Character("+") ? 1 : -1
}
print(ans)


var i=0;readLine()!.characters.forEach(String($0)=="+" ?i++:i--);print(i)


import * as fs from 'fs';

namespace AtCoder.abc101 {
    class ProgramA {
        args: string[];

        // +-++
        // 2
        constructor(args: string[]) {
            this.args = args;
        }

        main(): void {
            const s: string = args[0];
            let ans: number = 0;

            s.split('').forEach(x => {
                if (x === '+') ans++;
                if (x === '-') ans--;
            });
            console.log(ans);
        }
    }

    const args: string[] = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
    const func: ProgramA = new ProgramA(args);
    func.main();
}


const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  let ans=0
  rep(4,()=>{
    if(ssin()=='+')ans++
    else ans--
  })
  out(ans)
}
main();


const Main = (ary: string): void => {
	const input = ary.split("")
	let ret = 0
	for (let i = 0; i < input.length; i++) {
		if (input[i] === "+") {
			ret++
		} else if (input[i] === "-") {
			ret--
		}
	}
	console.log(ret)
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"))


const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  let ans=0
  rep(4,()=>{
    if(sin()=='+')ans++
    else ans--
  })
  out(ans)
}
main();


const main = (input) => {
  input = input.trim();
  input = input.split('');
  const a = input[0];
  const b = input[1];
  const c = input[2];
  const d = input[3];
  const s = a+b+c+d;

  if(s=="+---"){
    console.log(-2);
  }else if(s=="+++-"){
    console.log(2);
  }else if(s=="++++"){
    console.log(4);
  }else if(s=="----"){
    console.log(-4);
  }else{
    console.log(0);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (input: void) => {
  const s: string = input;
  let cnt: number = 0;

  for (let i=0; i < s.length; i++) {
    if (s.split('')[i] === '+') {
      cnt++;
    } else {
      cnt--;
    }
  }
  console.log(cnt);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


S=input()
T=input()
s=[str(a) for a in S]
t=[str(b) for b in T]
s.sort()
t.sort(reverse=True)
s=''.join(s)
t=''.join(t)
if s<t:
  print ("Yes")
else:
  print("No")


s = "".join(sorted(input()))
t = "".join(sorted((input()))[::-1])
if s < t:
    print("Yes")
else:
    print("No")


val = sorted(input())
val2 = sorted(input(),reverse=True)
print("Yes" if val2 > val else "No")


s = list(input())
t = list(input())

s.sort()
s = "".join(s)

t.sort()
t = "".join(t)

print("Yes" if s<t else "No")


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

s = ''.join(sorted(list(input().split())))
t = ''.join(sorted(list(input().split())))[::-1]

if s < t:
    print('Yes')
else:
    print('No')


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

s = ''.join(sorted(input().split()))
t = ''.join(sorted(input().split()))[::-1]

if s < t:
    print('Yes')
else:
    print('No')


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

public class Main {

	public static void main(String[] args) {

		FastScanner sc = new FastScanner();
		String s = sc.next();
		String t = sc.next();
		char[] a = s.toCharArray();
		char[] b = t.toCharArray();
		Arrays.sort(a);
		Arrays.sort(b);
		char[] c = new char[b.length];
		for (int i = 0; i < b.length; i++)
			c[i] = b[b.length - 1 - i];

		for (int i = 0; i < Math.min(a.length, c.length); i++) {
			if (a[i] < c[i]) {
				System.out.println("Yes");
				return;
			} else if (a[i] > c[i]) {
				System.out.println("No");
				return;
			}
		}
		if (a.length < c.length)
			System.out.println("Yes");
		else
			System.out.println("No");
	}
	//以下、自作ライブラリ

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

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

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

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

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

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

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

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

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

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

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

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

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


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        char[] s = input.readLine().toCharArray();
        char[] t = input.readLine().toCharArray();
        Arrays.sort(s);
        Arrays.sort(t);
        for (int i = 0, j = t.length - 1; i < s.length && j > -1; i++, j--) {
            if (s[i] < t[j]) {
                System.out.println("Yes");
                return;
            } else if (s[i] > t[j]) {
                System.out.println("No");
                return;
            }
        }
        if (s.length < t.length) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}


import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args) throws IOException{
        Reader r = new Reader();
        String s = r.s();
        String t = r.s();
        char[] sc = s.toCharArray();
        char[] tc = t.toCharArray();
        Arrays.sort(sc);
        Arrays.sort(tc);
        char[] temp = new char[tc.length];
        for(int i = 0; i < tc.length; i++)
            temp[i] = tc[tc.length-1-i];
        tc = temp;
        s = new String(sc);
        t = new String(tc);
        println(s.compareTo(t) < 0 ? "Yes" : "No");
    }
    static class EdgeList{
        int id;
        ArrayList<int[]> list = new ArrayList<>();
        int d;
        EdgeList(int n){
            id = n;
        }
        void add(int[] a){
            list.add(a);
        }
        int size(){
            return list.size();
        }
        void setD(int d){
            this.d = d;
        }
    }
    static void print(Object o){
        System.out.print(o.toString());
    }
    static void println(Object o){
        System.out.println(o.toString());
    }
    static int Int(String s){
        return Integer.parseInt(s);
    }
    static long Long(String s){
        return Long.parseLong(s);
    }
    static class Reader extends BufferedReader{
        Reader(){
            super(new InputStreamReader(System.in));
        }
        String s() throws IOException{
            return readLine();
        }
        String[] ss() throws IOException{
            return s().split(" ");
        }
        int i() throws IOException{
            return Int(s());
        }
        int[] ii() throws IOException{
            String[] ss = ss();
            int size = ss.length;
            int[] ii = new int[size];
            for(int j = 0; j < size; j++) ii[j] = Int(ss[j]);
            return ii;
        }
        long l() throws IOException{
            return Long(s());
        }
        long[] ll() throws IOException{
            String[] ss = ss();
            int size = ss.length;
            long[] ll = new long[size];
            for(int j = 0; j < size; j++) ll[j] = Long(ss[j]);
            return ll;
        }
    }
}


import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

public class Main {
	public static void main(String[]args) {
		try(Scanner scan = new Scanner(System.in)){

			String s = scan.next();
			Character[]S = new Character[s.length()];
			for(int i = 0;i<s.length();i++) {
				S[i] = s.charAt(i);
			}

			Arrays.sort(S);

			String t = scan.next();
			Character[]T = new Character[t.length()];
			for(int i = 0;i<t.length();i++) {
				T[i] = t.charAt(i);
			}

			Arrays.sort(T,Collections.reverseOrder());

			/*
			for(int i = 0;i<S.length;i++)System.out.print(S[i]);
			System.out.println();
			for(int i = 0;i<T.length;i++)System.out.print(T[i]);
			*/

			int ok = 1;
			int i = 0;
			while(true) {
				if(S[i]==T[i]) {
					i++;
					if(i==S.length)break;
				}else if(S[i]<T[i]) {
					break;
				}else {
					ok=0;
					break;

				}
			}

			if(ok==0) {
				System.out.println("No");
			}else {
				if(i==S.length) {
					if(S.length<T.length) {
						System.out.println("Yes");
					}else {
						System.out.println("No");
					}

				}else {
					System.out.println("Yes");
				}

			}

		}

	}

}


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

	//Method addition frame end
}


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

    String s = sc.next();
    String t = sc.next();
    String ss[] = s.split("");
    String tt[] = t.split("");
    Arrays.sort(ss);
    Arrays.sort(tt);
    s = String.join("",ss);
    t = String.join("",tt);
    int n = Math.min(s.length(),t.length());
    String ans = "No";
    int c = 0;
    for(int i = 1 ; i <= n ; ++i){
      if((int)s.charAt(0)<(int)t.charAt(t.length()-i)){
        ans = "Yes";
        break;
      }else if((int)s.charAt(0)==(int)t.charAt(t.length()-i)){
        c++;
      }
    }

    if(c==n && s.length()<t.length()) ans ="Yes";

    System.out.println(ans);

  }
}


#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
    char a[100],b[100];
    int f=0,i,j;
    scanf("%s",a);
    scanf("%s",b);
    sort(a,a+strlen(a));
    sort(b,b+strlen(b));
    i=0;
    j=strlen(b)-1;
    while(i<strlen(a)&&j>=0)
    {
        if(b[j]!=a[i])
        {
            if(b[j]<a[i])
                printf("No");
            else
                printf("Yes");
            f=1;
            break;
        }
        i++;
        j--;
    }
    if(!f)
    {
        if(j>=0)
            printf("Yes");
        else
            printf("No");
    }
    return 0;
}


#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
bool cmp(int a,int b){
	return a>b;
}
int main() {
	char a[100],b[100];
	scanf("%s%s",a,b);
	sort(a,a+strlen(a));
	sort(b,b+strlen(b),cmp);
	if(strcmp(a,b)<0){
		printf("Yes\n");
	}else{
		printf("No\n");
	}
	return 0;
}


#include <bits/stdc++.h>
#include<algorithm>
#include<math.h>
#include<string>
#include<iostream>
using namespace std;

template <class T> using V = vector<T>;

using ll = long long;
using db = double;
using st = string;
using ch = char;
using bl = bool;
using vll = V<ll>;
using vpll =V<pair<ll,ll>>;
using vst = V<st>;
using vdb = V<db>;
using vch = V<ch>;
using vbl = V<bl>;

#define FOR(i,a,b) for(ll i=(a);i<(ll)(b);i++)
#define rFOR(i,a,b) for(ll i=(a);i>(ll)(b);i--)
#define oFOR(i,a,b) for(ll i=(a);i<(ll)(b);i+=2)
#define bgn begin()
#define en end()
#define SORT(a) sort((a).bgn,(a).en)
#define REV(a) reverse((a).bgn,(a).en)
#define M(a,b) max(a,b)
#define rM(a,b) min(a,b)
#define fi first
#define se second
#define sz size()
#define gcd(a,b) __gcd(a,b)
#define co(a) cout<<a<<endl;
#define ci(a) cin>>a;

ll sum(ll n) {
  ll m=0;
  FOR(i,0,20){
    m+=n%10;
    n/=10;
    if(n==0){
      break;
    }
  }
  return m;
}

ll combi(ll n,ll m) {
  ll ans=1;
  rFOR(i,n,n-m){
    ans*=i;
  }
  FOR(i,1,m+1){
    ans/=i;
  }
  return ans;
}

ll lcm(ll a,ll b){
  ll n;
  n=a/gcd(a,b)*b;
  return n;
}

/****************************************\
| Thank you for viewing my code:)        |
| Written by RedSpica a.k.a. RanseMirage |
| Twitter:@asakaakasaka                  |
\****************************************/

signed main() {
  st s,t; ci(s>>t)
    SORT(s);
    SORT(t);
    REV(t);
  if(s<t) co("Yes")
    else co("No")
    }


#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int main (void) {
	char w1[101];
	char w2[101];

	char max2 = 0, min1 = 123;

	fill(w1, w1 + 101, 0);
	fill(w2, w2 + 101, 0);
	scanf("%s %s", w1, w2);

	for (int it = 0; it < 101; ++it) {
		if (w1[it] != 0 && w1[it] < min1) min1 = w1[it];
		if (w2[it] > max2) max2 = w2[it];
	}

	if (max2 > min1) cout << "Yes\n";
	else if (strcmp(w1, w2) && strlen(w2) > strlen(w1)) cout << "Yes\n";
	else cout << "No\n";

	return 0;
}


#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int main (void) {
	char w1[101];
	char w2[101];

	char max2 = 0, min1 = 123;

	fill(w1, w1 + 101, 0);
	fill(w2, w2 + 101, 0);
	scanf("%s %s", w1, w2);

	for (int it = 0; it < 101; ++it) {
		if (w1[it] != 0 && w1[it] < min1) min1 = w1[it];
		if (w2[it] > max2) max2 = w2[it];
	}

	if (max2 > min1) cout << "Yes\n";
	else if (strcmp(w1, w2) && strlen(w2) < strlen(w1)) cout << "Yes\n";
	else cout << "No\n";

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rrep(i, n) for (int i = 1; i < (int)(n+1); i++)
const int MAX = 510000;
const int MOD = 1000000007;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (long long i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
long long COM(ll n, ll k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
  	if(n==k){
      return 1;
    }
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}
// vector<vector<int>> A(3, vector<int>(4));
int main() {
    string S,T;
    cin>>S>>T;
    sort(S.begin(9,S.end());
    sort(T.rbegin(),T.rend());
    if(S<T){
        cout<<"Yes"<<endl;
    }
    else{
        cout<<"No"<<endl;
    }
}


#include <stdio.h>
#include <string.h>

int main() {
  char s[101] = {0}, t[101] = {0};
  int i, j;
  int sl, tl;
  scanf("%s %s", s, t);
  sl = strlen(s);
  tl = strlen(t);

  for (i = 0; i < sl-1; i++) {
    for (j = i+1; j < sl; j++) {
      if (s[i] > s[j]) {
        char tmp;
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
      }
    }
  }

  for (i = 0; i < tl-1; i++) {
    for (j = i+1; j < tl; j++) {
      if (t[i] < t[j]) {
        char tmp;
        tmp = t[i];
        t[i] = t[j];
        t[j] = tmp;
      }
    }
  }

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


#include<stdio.h>
#include<string.h>
//20000桁のマージソート(1単語10文字以下)
char c[101];
int sort(int a,int b,char s[101]){
  if(a==b)
    return 0;
  sort(a,(a+b)/2,s);
  sort((a+b)/2+1,b,s);
  int i=a,j=(a+b)/2+1,k=a;
  while(k<=b){
    if(i<(a+b)/2+1 && j<b+1){
      if(s[i]<s[j]){
        c[k]=s[i];
        i++;
      }
      else{
        c[k]=s[j];
        j++;
      }
    }
    else if(j>b){
      c[k]=s[i];
      i++;
    }
    else{
      c[k]=s[j];
      j++;
    }
    k++;
  }
  for(i=a;i<=b;i++)
    s[i]=c[i];
  return 0;
}

int main(){
  char s[101],t[101];
  scanf("%s%*c%s",s,t);
  int slen=strlen(s);
  int tlen=strlen(t);
  int i;
  sort(0,slen-1,s);
  sort(0,tlen-1,t);
  for(i=0;i<slen;i++){
    if(s[i]<t[tlen-1-i]){
      puts("Yes");
      return 0;
    }
    else if(s[i]>t[tlen-1-i]){
      puts("No");
      return 0;
    }
  }
  if(slen==tlen)
    puts("No");
  else
    puts("Yes");
  return 0;
}


// 161-C Replacing Integer

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>
#include <stdlib.h>

// qsortで用いる比較用関数．*a<*bならaが先になる．
int compare(const void* a, const void* b) {
    return *(char*)a - *(char*)b;
}

void kojun(char* word) {
    char min_alphabet[2],tmp[2];
    int i, min_i,j;

    for (j = strlen(word) - 1; j > 0; j--) {
        min_i = 0;
        min_alphabet[0] = word[min_i];
        for (i = 1; i < j+1; i++) {
            if (word[i] < min_alphabet[0]) {
                //printf("word[i]:%c min_alphabet:%c ", word[i], min_alphabet[0]);
                min_alphabet[0] = word[i];
                min_i = i;
            }
        }
        tmp[0] = word[j];
        word[j] = word[min_i];
        word[min_i] = tmp[0];

        //printf("j:%d min_alphabet:%c\n", j, min_alphabet[0]);
    }
    return;
}

void syojun (char* word) {
    char max_alphabet[2], tmp[2];
    int i, max_i, j;

    for (j = strlen(word) - 1; j > 0; j--) {
        max_i = 0;
        max_alphabet[0] = word[max_i];
        for (i = 1; i < j + 1; i++) {
            if (word[i] > max_alphabet[0]) {
                //printf("word[i]:%c max_alphabet:%c ", word[i], max_alphabet[0]);
                max_alphabet[0] = word[i];
                max_i = i;
            }
        }
        tmp[0] = word[j];
        word[j] = word[max_i];
        word[max_i] = tmp[0];

        //printf("j:%d max_alphabet:%c\n", j, max_alphabet[0]);
    }
    return;
}

int main() {

    char word_s[101], word_t[101];

    scanf("%s", word_s);
    scanf("%s", word_t);

    syojun(word_s);
    kojun(word_t);
    //printf("%s %s\n", word_s, word_t);
    if (strcmp(word_s, word_t) < 0) {
        printf("Yes\n");
    }
    else {
        printf("No\n");
    }

    return 0;
}


#include<stdio.h>
#include<string.h>
int main(void){
  int i,j;
  char s[101],t[101];
  char b;
  int ls,lt;
  int x=0;

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

  ls=strlen(s);
  lt=strlen(t);

  for(i=0;i<ls;i++){
    for(j=i;j<ls;j++){
      if(s[i]>s[j]){
        b=s[i];
        s[i]=s[j];
        s[j]=b;
      }
      else{}
    }
  }

  for(i=0;i<lt;i++){
    for(j=i;j<lt;j++){
      if(t[i]<t[j]){
        b=t[i];
        t[i]=t[j];
        t[j]=b;
      }
      else{}
    }
  }

  for(i=0;i<101;i++){
    if(s[i]==t[i]){}
    if(s[i]<t[i]){
      x=1;
      break;
    }
    if(s[i]>t[i]){
      x=0;
      break;
    }
  }

  printf("%s\n",s);
  printf("%s\n",t);
  if(x==0)printf("No\n");
  if(x==1)printf("Yes\n");

  return 0;
}


#include <stdio.h>
#include <string.h>

void sort(char *s,int n)
{
        int i,j,index;
        char max;
        for(i=0;i<n;i++){
                max=s[i];index=i;
                for(j=i+1;j<n;j++){
                        if(s[j]>max){
                                max=s[j];index=j;
                        }
                }
                s[index]=s[i];s[i]=max;
        }
        return ;
}
void reverse(char *s,int n)
{
        int i,j,index;
        char max;
        for(i=0;i<n;i++){
                max=s[i];index=i;
                for(j=i+1;j<n;j++){
                        if(s[j]<max){
                                max=s[j];index=j;
                        }
                }
                s[index]=s[i];s[i]=max;
        }
        return ;
}
int main(void)
{
        int a,n,m,i,c=0,fl=0;
        char s[101],t[101];
        scanf("%s%s",s,t);
        n=strlen(s); m=strlen(t);
        sort(t,m);
        reverse(s,n);
        if(m<n)a=m;
        else a=n;
        for(i=0;i<a;i++){
                if(s[i]<t[i]){ fl=1;break;}
                else {fl=2;break;}
                c++;
        }
        if(fl==0 && n<m)fl=1;
        if(fl==0 && n>=m)fl=2;
        if(fl==1)printf("Yes\n");
        if(fl==2)printf("No\n");
        return 0;
}


#include <stdio.h>
#include <string.h>

void sort(char *s,int n)
{
        int i,j,index;
        char max;
        for(i=0;i<n;i++){
                max=s[i];index=i;
                for(j=i+1;j<n;j++){
                        if(s[j]>max){
                                max=s[j];index=j;
                        }
                }
                s[index]=s[i];s[i]=max;
        }
        return ;
}
void reverse(char *s,int n)
{
        int i,j,index;
        char max;
        for(i=0;i<n;i++){
                max=s[i];index=i;
                for(j=i+1;j<n;j++){
                        if(s[j]<max){
                                max=s[j];index=j;
                        }
                }
                s[index]=s[i];s[i]=max;
        }
        return ;
}
int main(void)
{
        int a,n,m,i,c=0,fl=0;
        char s[101],t[101];
        scanf("%s%s",s,t);
        n=strlen(s); m=strlen(t);
        sort(t,m);
        reverse(s,n);
        if(m<n)a=m;
        else a=n;
        for(i=0;i<a;i++){
                if(s[i]<t[i]){ fl=1;break;}
                else {fl=2;break;}
                c++;
        }
        if(fl==1 || c==a-1 && n<m)printf("Yes\n");
        else printf("No\n");
        return 0;
}


function Main(input){
	input = input.split("\n");
	var n = input[0].split("").sort().join("");
	var m = input[1].split("").sort().reverse().join("");
	console.log(n<m?"Yes":"No")
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


function compareNumbers2(a, b) { //for sort
    return b.charCodeAt()-a.charCodeAt();
}

function Main(arg) {
  var s = arg.split("\n")[0].split("");
  var t = arg.split("\n")[1].split("");

  s.sort();
  t.sort(compareNumbers2);

  if (s < t) {
    console.log("Yes");
  }
  else {
    console.log("No");
  }

  return;
}

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


"use strict";

const main = arg => {
    const s = arg.split("\n")[0].split("").sort().join("");
    const t = arg.split("\n")[1].split("").sort().reverse().join("");

    if(s < t) {
        console.log("Yes");
    } else {
        console.log("No");
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const inputText = require("fs").readFileSync("/dev/stdin", "utf8").split(/\n/);
const a = inputText[0].split("").sort();
const b = inputText[1].split("").sort().reverse();

if (a < b) {
  console.log("YES");
} else {
  console.log("No");
}


( i => {
  i = i.split('\n').map((val, index) => index ? val.split('').sort().join('') : val.split('').sort().reverse().join(''));
  console.log(i[0] < i[1] ? 'Yes' : 'No')
})(require("fs").readFileSync("/dev/stdin", "utf8"))


( i => {
  i = i.split('\n').map((val, index) => index ? val.split('').sort().join('') : val.split('').sort().reverse().join(''));
  console.log(i[0] > i[1] ? 'Yes' : 'No')
})(require("fs").readFileSync("/dev/stdin", "utf8"))


package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	scanner.Split(bufio.ScanWords)

	S, T := next(), next()

	if len(S) < len(T) && S == T {
		fmt.Println("Yes")
		return
	}

	s := strings.Split(S, "")
	t := strings.Split(T, "")

	sort.Strings(s)
	sort.Strings(t)
	if len(s) < len(t) && strings.HasPrefix(strings.Join(t, ""), strings.Join(s, "")) {
		fmt.Println("Yes")
		return
	}

	sort.Sort(sort.Reverse(sort.StringSlice(t)))
	for i := 0; i < min(len(s), len(t)); i++ {
		if s[i] == t[i] {
			continue
		}
		if s[i] < t[i] {
			fmt.Println("Yes")
			return
		}
	}
	fmt.Println("No")
}

func next() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	i, err := strconv.Atoi(next())
	if err != nil {
		fmt.Println(err)
	}
	return i

}

func min(n, m int) int {
	if n <= m {
		return n
	}
	return m
}


package main

import (
  "fmt"
  "sort"
  "strings"
)
func main() {
  var s, t string
  fmt.Scan(&s)
  fmt.Scan(&t)

  s1 := strings.Split(s,"")
  t1 := strings.Split(t,"")

  sort.Strings(s1)
  sort.Sort(sort.Reverse(sort.StringSlice(t1)))

  s = strings.Join(s1, "")
  t = strings.Join(t1, "")

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


package main

import (
	"fmt"
)

func Sort(s string) string {
	runes := []rune(s)
	for i := 0; i < len(runes); i++ {
		min := runes[i]
		minIndex := i
		for j := i+1; j < len(runes); j++ {
			if min > runes[j] {
				min = runes[j]
				minIndex = j
			}
		}
		tmp := runes[i]
		runes[i] = min
		runes[minIndex] = tmp
	}
	return string(runes)
}

func Reverse(t string) string {
	runes := []rune(t)
	for i := 0; i < len(runes); i++ {
		max := runes[i]
		maxIndex := i
		for j := i+1; j < len(runes); j++ {
			if max < runes[j] {
				max = runes[j]
				maxIndex = j
			}

		}
		tmp := runes[i]
		runes[i] = max
		runes[maxIndex] = tmp
	}
	return string(runes)
}

func main() {
	var s,t string
	fmt.Scan(&s,&t)

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

}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	a, _ := strconv.Atoi(sc.Text())
	return a
}

func main() {
	r := bufio.NewReader(os.Stdin)
	// w := bufio.NewWriter(os.Stdout)
	// defer w.Flush()
	// sc.Split(bufio.ScanWords)
	var s, t string
	fmt.Fscan(r, &s)
	fmt.Fscan(r, &t)

	ls := make([]int, 27)
	lt := make([]int, 27)

	for _, l := range s {
		ls[l-[]rune("a")[0]]++
	}
	ns := ""
	for i, l := range ls {
		ns += strings.Repeat(string(rune(i)+[]rune("a")[0]), l)
	}

	for _, l := range t {
		lt[26-(l-[]rune("a")[0])]++
	}
	nt := ""
	for i, l := range lt {
		nt += strings.Repeat(string(rune(26-i)+[]rune("a")[0]), l)
	}
	// fmt.Println(ns, nt)

	ans := "Draw"
	for i := 0; i < len(ns); i++ {
		if ns[i] == nt[i] {
			continue
		} else if ns[i] < nt[i] {
			ans = "Yes"
			break
		} else {
			ans = "No"
			break
		}
	}
	if ans == "Draw" {
		if len(ns) < len(nt) {
			ans = "Yes"
		} else {
			ans = "No"
		}
	}
	fmt.Println(ans)
}


package main

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

func main() {
	s, t := []byte(ReadString()), []byte(ReadString())
	sort.Slice(s, func(i, j int) bool {
		return s[i] > s[j]
	})
	sort.Slice(t, func(i, j int) bool {
		return t[i] > t[j]
	})
	a, b := string(s), string(t)
	if a < b {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

var reader = bufio.NewReader(os.Stdin)

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


s = gets.chomp.chars.sort
t = gets.chomp.chars.sort{|a, b| b <=> a}
f = false
([s.size, t.size].max).times do |i|
  if s[i].nil?
    f = true
    break
  elsif t[i].nil?
    break
  elsif s[i] > t[i]
    break
  elsif s[i] < t[i]
    f = true
    break
  end
end
puts (f ? "Yes" : "No")


s = gets.chomp.split('')
t = gets.chomp.split('')

ss = s.sort.join('')
tt = t.sort.reverse.join('')

if ss < tt
  puts 'Yes'
else
  puts 'No'
end


# https://atcoder.jp/contests/abc082/tasks/abc082_b

s = gets.chomp
t = gets.chomp
cond = s.chars.sort.join < t.chars.sort.reverse.join
puts cond ? 'Yes' : 'No'


s = gets.chomp.chars
t = gets.chomp.chars

dictionary = ('a'..'z').each_with_object({}).with_index(1) { |(char, h), i| h[char] = i }

s_dash = s.map { |char| dictionary[char] }.sort.join
t_dash = t.map { |char| dictionary[char] }.sort.reverse.join

max = [s.size, t.size].max

s_dash << '0' * (max - s.size)
t_dash << '0' * (max - t.size)

puts s_dash < t_dash ? 'Yes' : 'No'


s=gets.chomp
t=gets.chomp
if s<t
  puts :Yes
  exit
end
s.each_char do |si|
  t.each_char do |ti|
    if si>ti
      puts :Yes
      exit
    end
  end
end
puts :No


s = gets.chomp
t = gets.chomp

s.chars.sort!.join
t2 = t.chars.sort!.reverse!.join

print (s < t2) ? "Yes" : "No"


#[allow(unused_imports)]
use std::io::Write;

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

#[allow(non_snake_case)]
fn main() {
    input![s: String, t: String];
    let mut s: Vec<_> = s.chars().collect();
    s.sort();
    let mut t: Vec<_> = t.chars().collect();
    t.sort();
    t.reverse();
    let ans = {
        if s < t {
            "Yes"
        } else {
            "No"
        }
    };
    println!("{}", ans);

}


use std::io::*;
use std::str::FromStr;

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

use std::cmp::min;

fn main() {
    let mut s: Vec<char> = read::<String>().chars().collect();
    let mut t: Vec<char> = read::<String>().chars().collect();
    let mut ans: &str = &String::new();

    s.sort();
    t.sort();
    t.reverse();

    for i in 0..min(s.len(), t.len()) {
        if s[i] < t[i] {
            ans = &"Yes";
            break;
        }
        if s[i] > t[i] {
            ans = &"No";
            break;
        }
    }

    if ans != "" {
        println!("{}", ans);
        return;
    }

    if s.len() < t.len() {
        println!("Yes");
    } else {
        println!("No");
    }
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
fn main() {
    input! {
        s: chars,
        t: chars,
    }
    let mut s = s;
    let mut t = t;
    s.sort();
    t.sort_by(|a, b| b.cmp(a));
    println!("{}", if s < t {"Yes"} else {"No"});
}


#![allow(unused_imports)]
use itertools::Itertools;
use proconio::{input, marker::*};

fn main() {
    input! {
        mut s: Chars,
        mut t: Chars
    };
    s.sort();
    t.sort();
    t.reverse();
    let tf = (0..s.len()).any(|index| s[index] < t[index])
        || ((s.len() < t.len()) && (0..s.len()).all(|index| s[index] == t[index]));
    println!("{}", ["No", "Yes"][tf as usize]);
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input!{
        ss: chars,
        tt: chars,
    };
    let mut s = ss.clone();
    let mut t = tt.clone();
    s.sort();
    t.sort_by(|a, b| b.cmp(a));
    for i in 0..s.len().min(t.len()){
        if s[i] > t[i] {
            println!("No");
            return;
        }
        if s[i] < t[i] {
            println!("Yes");
            return;
        }
    }
    if s.len() >= t.len(){
        println!("No");
    } else {
        println!("Yes");
    }

}


use std::io::*;
use std::str::FromStr;

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

fn main() {
    let s: Vec<char> = read::<String>().chars().collect();
    let t: Vec<char> = read::<String>().chars().collect();

    let mins = s.iter().min();
    let maxt = t.iter().max();

    if maxt == mins {
        if s.len() == 1 && t.len() != 1 {
            println!("Yes");
        } else {
            println!("No");
        }
        return;
    }

    if maxt < mins {
        println!("No");
    } else {
        println!("Yes")
    }
}


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

//var min, min2, count: Int!
//for i in 1...10 {
//    let x = Int(readLine()!)!
//    if i == 1 {
//        min = x
//        count = 1
//    } else if x < min {
//        min2 = min
//        min = x
//        count = 1
//    } else if x == min && count == 1 {
//        min2 = x
//        count = 2
//    }
//}
//print(min2)

/*************** メインプログラム ***************/

let s = readLine()!.toArray().sorted().joinWithSeparator("")
let t = readLine()!.toArray().sorted().reversed().joinWithSeparator("")
if s < t {
    print("Yes")
} else {
    print("No")
}


import Foundation

let s = readLine()!.sorted().map { String($0) }.joined()
let t = readLine()!.sorted { $0 > $1 }.map { String($0) }.joined()
print(s < t ? "Yes" : "No")


#if os(Linux)
    import Glibc
#else
    import Foundation
    import Darwin
#endif

#if swift(>=4.0)
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { return (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { return (a[0], a[1], a[2]) }
#else
func readInts() -> [Int] {
    return readLine()!.split(" ").map { Int($0)! }
}

prefix operator * {}
prefix func * <T> (a: [T]) -> (T, T) { return (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { return (a[0], a[1], a[2]) }

extension String: CollectionType {}
#endif

let s = readLine()!
let t = readLine()!

let cs = s.sorted(by: {$0 < $1}).map(String.init).joined()
let ct = t.sorted(by: {$0 > $1}).map(String.init).joined()

if cs < ct {
    print("Yes")
} else {
    print("No")
}


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

//var min, min2, count: Int!
//for i in 1...10 {
//    let x = Int(readLine()!)!
//    if i == 1 {
//        min = x
//        count = 1
//    } else if x < min {
//        min2 = min
//        min = x
//        count = 1
//    } else if x == min && count == 1 {
//        min2 = x
//        count = 2
//    }
//}
//print(min2)

/*************** メインプログラム ***************/

let s = readLine()!.toArray().sorted()
let t = readLine()!.toArray().sorted().reversed()
if s < t {
    print("Yes")
} else {
    print("No")
}


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

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

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

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

ans()


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


const log = console.log;

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

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

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

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

// ----

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

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

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

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


// const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

const stdin = `ratcode
atlas`

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

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

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

ans()


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

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

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

  console.log(sd, td)

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

ans()


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

print(t.count("AB") + a)


n,*t=open(0).read().split()
n=int(n)
a=0
b=0
c=0

ans=0
for i in t:
    if i[0]=="B"and i[-1]=="A":
        a+=1
    elif i[0]=="B":
        b+=1
    elif i[-1]=="A":
        c+=1
    ans+=i.count("AB")
if a>0 and b>0 and c>0:
    ans+=a+1
    a=0
    b-=1
    c-=1
if a>0 and b>0:
    ans+=a
    a=0
    b-=1
if a>0 and c>0:
    ans+=a
    a=0
    c-=1
if a>0:
    ans+=a-1
    a=0
if b>0 and c>0:
    ans+=min(b,c)
print(ans)


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

if __name__ == "__main__":
    main()


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

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

a -= b_a
b -= b_a
print(ab + min(a, b) + b_a)


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

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

a -= b_a
b -= b_a
print(ab + min(a, b) + b_a)


N = int(input())
S = [input().strip() for _ in range(N)]
C = {"A":0,"B":0,"BA":0}
cnt = 0
for i in range(N):
    s = S[i]
    for j in range(len(s)-2+1):
        if s[j:j+2]=="AB":
            cnt += 1
    if s[0]=="B" and s[-1]=="A":
        C["BA"] += 1
    elif s[0]=="B":
        C["B"] += 1
    elif s[-1]=="A":
        C["A"] += 1
if C["BA"]>0:
    cnt += C["BA"]-1
cnt += min(C["B"],C["A"])
if C["BA"]>0 and C["B"]!=C["A"]:
    cnt += 1
print(cnt)


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

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

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

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

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

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

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

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

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

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

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

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


import java.io.*;
import java.util.*;
import java.math.*;
// import java.awt.Point;

public class Main {
    InputStream is;
    PrintWriter out;
    String INPUT = "";

    // static int mod = 1_000_000_007;
    int mod = 998244353;
    // long inf = Long.MAX_VALUE/2;
    int inf = Integer.MAX_VALUE/2;

    ArrayList<Integer>[] e;

    void solve(){
        int n = ni();
        int[] res = new int[3];
        int ans = 0;
        for(int i = 0; i < n; i++){
            char[] c = ns().toCharArray();
            if(c[0]=='B'&&c[c.length-1]=='A') res[0]++;
            else if(c[0]=='B') res[1]++;
            else if(c[c.length-1]=='A') res[2]++;

            for(int j = 0; j < c.length-1; j++){
                if(c[j]=='A'&&c[j+1]=='B') ans++;
            }
        }
        if(res[2]>0){
            ans += res[0];
        }
        else{
            ans += Math.max(0,res[0]-1);
            if(res[0]>0){
                res[2]++;
            }
        }
        ans += Math.min(res[1],res[2]);
        out.println(ans);
    }

    void run() throws Exception
    {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        out = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        out.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }

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

    private byte[] inbuf = new byte[1024];
    private int lenbuf = 0, ptrbuf = 0;

    private int readByte()
    {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b) && b != ' ')){
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n)
    {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m)
    {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException
	{
		new Main().run();
	}

	public void run() throws NumberFormatException, IOException
	{
		BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(file.readLine());
		char[][] strs = new char[N][];
		int b = 0;
		int ba = 0;
		int a = 0;
		int cnt = 0;
		for(int i = 0;i<N;i++)
		{
			strs[i] = file.readLine().trim().toCharArray();
			if(strs[i][0] == 'B'){
				if(strs[i][strs[i].length-1]=='A')
					ba++;
				else
					b++;
			}
			else if(strs[i][strs[i].length-1]=='A')
				a++;
			for(int j = 0;j<strs[i].length-1;j++)
			{
				if(strs[i][j]=='A' &&strs[i][j+1] == 'B')
					cnt++;
			}
		}
		if(a!=0)
		{
			a--;
			cnt+=ba;//now ends with a
			if(b!=0)
			{
				b--;
				cnt++;
			}
			cnt+=Math.min(a,b);
		}else if(ba!=0){
			cnt+=ba-1;
			if(b!=0)
				cnt++;
		}
		System.out.println(cnt);
	}

}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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