"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function () { return this.index < this.max },
        "next": function () { if (!this.hasNext()) { throw "ArrayIndexOutOfBoundsException"; } else { return this.list[this.index++]; } }
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let map = {}
    while (hasNext()) {
        let first = next()[0]
        if (!map[first]) map[first] = 1
        else map[first]++
    }
    let ans = 0n
    let march = ['M', 'A', 'R', 'C', 'H']
    for (let i = 0; i < march.length - 2; i++) {
        for (let j = i + 1; j < march.length - 1; j++) {
            for (let k = j + 1; k < march.length; k++) {
                if(!map[march[i]] || !map[march[j]] || !map[march[k]]) continue
                ans += BigInt(map[march[i]]) * BigInt(map[march[j]]) * BigInt(map[march[k]])
            }
        }
    }
    console.log(Number(ans))
}
Main()


'use strict'
function main(inp) {
  inp = inp.trim().split('\n')
  inp.shift()
  const P = [0,0,0,0,0,0,1,1,1,2];
  const Q = [1,1,1,2,2,3,2,2,3,3];
  const R = [2,3,4,3,4,4,3,4,4,4];
  let S = new Array(5).fill(0)

  inp.forEach(str => {
    const index = 'MARCH'.indexOf(str[0])
    if (~index) S[index]++
  })
  let ans = 0
  for (let i = 0; i < 10; i++) {
    ans += S[P[i]] * S[Q[i]] * S[R[i]]
  }
  console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


var obj = init();
Main();
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
function next(){return obj.next();}
function hasNext(){return obj.hasNext();}
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");}
function init(){
  var inputFile = myin();
  var returnObj = {
    "list" : inputFile, "index" : 0, "max" : inputFile.length,
    "hasNext" : function(){return (this.index < this.max);},
    "next" : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(t){console.log(t);}//標準出力
function myerr(t){console.error(t);}//標準エラー出力
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var N = nextInt();
  var list = {
    "M" : 0,
    "A" : 0,
    "R" : 0,
    "C" : 0,
    "H" : 0
  };
  while(hasNext()){
    var first = nextCharArray()[0];
    list[first]++;
  }
  var keys = Object.keys(list);
  var output = 0;
  for(var i = 0; i < keys.length - 2; i++){
    for(var j = i + 1; j < keys.length - 1; j++){
      for(var k = j + 1; k < keys.length; k++){
        output += list[keys[i]] * list[keys[j]] * list[keys[k]];
      }
    }
  }
  myout(output);
}


var input=`
5
MASHIKE
RUMOI
OBIRA
HABORO
HOROKANAI
`;
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n").map(v=> v.trim()).reverse();
var n=arr.pop()-0;
var obj={M:0,A:0,R:0,C:0,H:0}
arr.forEach(v=>{
   if(obj.hasOwnProperty(v[0]))obj[v[0]]++;
});
var ary=Object.values(obj);
var sum=0;
for(var i=0;i<5;i++){
    for(var j=i+1;j<5;j++){
       for(var k=j+1;k<5;k++){
          sum+=ary[i]*ary[j]*ary[k];
       }
    }
 }
 console.log(sum);


'use strict'

function main(input){
  const lines = input.split('\n');
  const N = parseInt(lines.shift());
  const S = [];
  for(let i=0;i<N;i++){
    S.push(lines[i].split(''))
  }
  const march=Array(5).fill(0);

  for(let i=0;i<N;i++){
    if( lines[i][0]=='M' ){ march[0]++; }
    if( lines[i][0]=='A' ){ march[1]++; }
    if( lines[i][0]=='R' ){ march[2]++; }
    if( lines[i][0]=='C' ){ march[3]++; }
    if( lines[i][0]=='H' ){ march[4]++; }
  }

//  console.log(march)

  let result = march.reduce( (a,b)=>a*b,1 );

  for(let i = 0;i<3;i++){
    for(let j = i+1;j<4;j++){
      for(let k = j+1;k<5;k++){
//        console.log([i,j,k])
//        console.log(march[i]*march[j]*march[k]);
//console.log(result);
//console.log('---');
        result += march[i]*march[j]*march[k];
      }
    }
  }

  console.log(result);

}

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


package main

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

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

	sc := bufio.NewScanner(os.Stdin)
	cnt := make([]int, 5)
	for i := 0; i < n; i++ {
		sc.Scan()
		s := sc.Text()
		switch s[0] {
		case 'M':
			cnt[0]++
		case 'A':
			cnt[1]++
		case 'R':
			cnt[2]++
		case 'C':
			cnt[3]++
		case 'H':
			cnt[4]++
		}
	}
	p := []int{0, 0, 0, 0, 0, 0, 1, 1, 1, 2}
	q := []int{1, 1, 1, 2, 2, 3, 2, 2, 3, 3}
	r := []int{2, 3, 4, 3, 4, 4, 3, 4, 4, 4}
	ans := 0
	for i := 0; i < 10; i++ {
		ans += cnt[p[i]] * cnt[q[i]] * cnt[r[i]]
	}
	fmt.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}
	di8     = []int64{-1, -1, 0, 1, 1, 1, 0, -1}
	dj8     = []int64{0, -1, -1, -1, 0, 1, 1, 1}
	P       = []int64{0, 0, 0, 0, 0, 0, 1, 1, 1, 2}
	Q       = []int64{1, 1, 1, 2, 2, 3, 2, 2, 3, 3}
	R       = []int64{2, 3, 4, 3, 4, 4, 3, 4, 4, 4}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	N := readInt()
	var m, a, r, c, h int64
	for i := int64(0); i < N; i++ {
		s := readString()
		switch s[0] {
		case 'M':
			m++
		case 'A':
			a++
		case 'R':
			r++
		case 'C':
			c++
		case 'H':
			h++
		}
	}
	var D = []int64{m, a, r, c, h}
	res := int64(0)
	for d := 0; d < 10; d++ {
		res += D[P[d]] * D[Q[d]] * D[R[d]]
	}
	fmt.Println(res)

}

/*==========================================
 *             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
// }


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

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

//Combination generator for int slice
func combinations(list []int, choose int) (c chan []int) {
	c = make(chan []int, 1)
	go func() {
		defer close(c)
		switch {
		case choose == 0:
			c <- []int{}
		case choose == len(list):
			c <- list
		case len(list) < choose:
			return
		default:
			for i := 0; i < len(list); i++ {
				for subComb := range combinations(list[i+1:], choose-1) {
					c <- append([]int{list[i]}, subComb...)
				}
			}
		}
	}()
	return
}

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

	N := getInt()
	n := make([]int, 5)
	for i := 0; i < N; i++ {
		s := getString()
		switch s[0] {
		case 'M':
			n[0]++
		case 'A':
			n[1]++
		case 'R':
			n[2]++
		case 'C':
			n[3]++
		case 'H':
			n[4]++
		}
	}

	a := []int{0, 1, 2, 3, 4}

	ans := 0
	for comb := range combinations(a, 3) {
		x := 1
		for _, v := range comb {
			x *= n[v]
		}
		ans += x
	}
	out(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}

var M map[string]bool

func main() {
	N := nextInt()
	var S []string
	M = map[string]bool{"M": true, "A": true, "R": true, "C": true, "H": true}
	for i := 0; i < N; i++ {
		s := next()
		if IsMarch(s[0:1]) {
			S = append(S, s)
		}
	}
	if len(S) < 3 {
		fmt.Println(0)
		return
	}
	var ANS int
	for i := 0; i < len(S)-2; i++ {
		for j := i + 1; j < len(S)-1; j++ {
			for k := j + 1; k < len(S); k++ {
				if solve(S[i], S[j], S[k]) {
					ANS++
				}
			}
		}
	}
	fmt.Println(ANS)
}

func IsMarch(s string) bool {
	return M[s]
}

func solve(a, b, c string) bool {
	m := make(map[string]int, 3)
	m[a[0:1]]++
	m[b[0:1]]++
	m[c[0:1]]++
	for _, v := range m {
		if v > 1 {
			return false
		}
	}
	return true
}


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}
	di8     = []int64{-1, -1, 0, 1, 1, 1, 0, -1}
	dj8     = []int64{0, -1, -1, -1, 0, 1, 1, 1}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	N := readInt()
	m := make(map[string]int64, N)
	for i := int64(0); i < N; i++ {
		s := readString()
		switch s[0] {
		case 'M':
			fallthrough
		case 'A':
			fallthrough
		case 'R':
			fallthrough
		case 'C':
			fallthrough
		case 'H':
			m[string(s[0])]++
		}
	}
	all := len(m)
	// MARCH が3人以上いない場合
	if all < 3 {
		fmt.Println(0)
		return
	}
	// M:1,A:3,R:1->3 1*3*1
	// M:1,A:2,R:1->2 1*2*1
	// M:1,A:1,R:1->1 1*1*1
	// M:2,A:2,R:1->4 2*2*1
	// M:1,A:1,R:1,C:1 -> 4C3 -> 4
	// M:1,A:2,R:1,C:1 -> 4c3*2-1 -> 7
	// M:2,A:2,R:1,C:1 -> 4C3*2-1 + 4c3*2-1
	ans := int64(0)
	if all == 3 {
		p := int64(1)
		for _, v := range m {
			p = p * v
		}
		ans = p
	} else if all == 4 {
		for _, v := range m {
			if v > 1 {
				ans += 4*v - (v - 1)
			}
		}
		if ans == 0 {
			ans += 4 * 1
		}
	} else {
		for _, v := range m {
			if v > 1 {
				ans += (5*4)/(2*1)*v - 3*(v-1)
			}
		}
		if ans == 0 {
			ans += (5 * 4) / (2 * 1)
		}
	}
	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
// }


package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	n, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return n
}

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

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()

	c := map[byte]int{
		'M': 0,
		'A': 0,
		'R': 0,
		'C': 0,
		'H': 0,
	}

	for i := 0; i < n; i++ {
		s := nextString()
		if strings.IndexAny(s, "MARCH") != 0 {
			continue
		}
		c[s[0]]++
	}

	answer := 0

	answer += c['M'] * c['A'] * c['R']
	answer += c['M'] * c['A'] * c['C']
	answer += c['M'] * c['A'] * c['H']
	answer += c['M'] * c['R'] * c['C']
	answer += c['M'] * c['R'] * c['H']
	answer += c['M'] * c['C'] * c['H']
	answer += c['A'] * c['R'] * c['C']
	answer += c['A'] * c['C'] * c['H']
	answer += c['R'] * c['C'] * c['H']

	fmt.Println(answer)
}


n = gets.to_i
ary = Array.new(26, 0)
n.times do
  name = gets
  ary[name.ord-'A'.ord] += 1
end
str = 'MARCH'
cnt = Array.new
str.each_char do |c|
  cnt.push(ary[c.ord-'A'.ord])
end
sum = 0
cnt.combination(3) do |a|
  sum += a[0]*a[1]*a[2]
end
puts sum.to_s


gets
h = Hash.new 0
$<.each{|s|h[s[0]]+=1}
march = %w[M A R C H].map{|c|h[c]}
ans = 0
march.combination(3){|a|
  ans += a.inject :*
}
p ans


gets
c = Hash.new(0)
$<.each_with_index do |line, i|
  c[line[0]] += 1
end

sum = 0

["M","A","R","C","H"].combination(3) do |x,y,z|
  sum += c[x] * c[y] * c[z]
end

p sum


class Integer
    def !
        return 1 if self == 0
        (1..self).inject(:*)
    end

    def c(i)
        return 1 if i == 0
        (self-i+1..self).inject(:*) / i.!
    end
end

N = gets.to_i
name_march = Hash.new(0)

N.times{|i|
    s = gets.chomp

    case s[0]
    when "M", "A", "R", "C", "H" then
        name_march[s[0]] += 1
    end
}

only_name = name_march.values.select{|i| i == 1}.size
repetition = name_march.empty? ? 1 : name_march.values.inject(:*)

puts name_march.size.c(3) * repetition - only_name.c(3)


N = gets.to_i
name_march = Hash.new(0)

N.times{|i|
    s = gets.chomp

    case s[0]
    when "M", "A", "R", "C", "H" then
        name_march[s[0]] += 1
    end
}

only_name = name_march.values.select{|i| i == 1}.size
repetition = name_march.empty? ? 1 : name_march.values.inject(:*)

puts name_march.size.c(3) * repetition - only_name.c(3)


n = gets.chomp.split.to_i
cnt_hash = {M: 0, A: 0, R: 0, C: 0, H: 0}
persons = n.times map
  gets.chomp
end

grouped_p = persons.group_by{|p| p[0]}
  .map{|k,v| [k.to_sym, v.size]}.to_h

cnt_hash.merge! grouped_p

ans = "MARCH".chars.combination(3).inject(0) do |sum, attr|
  sum + cnt_hash[attr[0].to_sym] * cnt_hash[attr[1].to_sym] * cnt_hash[attr[2].to_sym]
end


use std::io::Read;
use std::collections::HashMap;

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

    let answer = solve(&buf);

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

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let march: Vec<char> = "MARCH".chars().collect();

    let n: usize = iterator.next().unwrap().parse().unwrap();
    let mut counts: HashMap<char, usize> = HashMap::new();
    for _ in 0..n {
        let first_char = iterator.next().unwrap().chars().next().unwrap();
        if march.contains(&first_char) {
            *counts.entry(first_char).or_insert(0) += 1;
        }
    }

    let zero = 0;
    let mut ans = 0;
    for i in 0..3 {
        for j in (i + 1)..4 {
            for k in (j + 1)..5 {
                let ci = counts.get(&march[i]).unwrap_or(&zero);
                let cj = counts.get(&march[j]).unwrap_or(&zero);
                let ck = counts.get(&march[k]).unwrap_or(&zero);
                ans += *ci * *cj * *ck;
            }
        }
    }
    return ans.to_string();
}


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

fn main() {
    let mut first_line = String::new();
    io::stdin().read_line(&mut first_line).unwrap();

    let n = i32::from_str(&first_line.trim()).unwrap();
    let mut counts: [u64; 5] = [0, 0, 0, 0, 0];

    for _ in 0..n {
        let mut line = String::new();
        io::stdin().read_line(&mut line).unwrap();
        match line.chars().next() {
            Some('M') => counts[0] += 1,
            Some('A') => counts[1] += 1,
            Some('R') => counts[2] += 1,
            Some('C') => counts[3] += 1,
            Some('H') => counts[4] += 1,
            _ => ()
        }
    }
    let mut answer: u64 = 0;
    for i in 0..5 {
        for j in 0..i {
            for k in 0..j {
                answer += counts[i] * counts[j] * counts[k];
            }
        }
    }
    println!("{}", answer);
}


use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let n = buf.trim().parse::<i32>().unwrap();

    let mut inum = [0i64; 5];
    for _ in 0..n {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();

        let fch = buf.chars().next().unwrap();
        match fch {
            'M' => inum[0] += 1,
            'A' => inum[1] += 1,
            'R' => inum[2] += 1,
            'C' => inum[3] += 1,
            'H' => inum[4] += 1,
            _ => (),
        }
    }

    if inum.iter().all(|&x| x == 0) {
        println!("0");
        return;
    }

    let n0 = inum.into_iter().filter(|&&x| x != 0)
                 .map(|&x| x).collect::<Vec<i64>>();

    let mut r = 0;

    let len = n0.len();
    if len == 3 {
        r = n0.iter().fold(1, |acc, &x| acc * x)
    } else if len == 4 {
        r = 0;
        for i in 0..4 {
            let mut r2 = 1;
            for j in 0..4 {
                if i != j {
                    r2 *= n0[j];
                }
            }
            r += r2;
        }
    } else if len == 5 {
        r = 0;
        for i in 0..5 {
            for j in (i + 1)..5 {
                let mut r2 = 1;
                for k in 0..5 {
                    if i != k && j != k {
                        r2 *= n0[k];
                    }
                }
                r += r2;
            }
        }
    }

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


eprintln!("{:?}", (i, j, k));


#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_imports)]

use itertools::Itertools;

const U_INF: usize = 1 << 60;
const I_INF: isize = 1 << 60;

fn main() {
    let mut sc = Scanner::new();
    let n = sc.next_usize();
    let mut m = 0;
    let mut a = 0;
    let mut r = 0;
    let mut c = 0;
    let mut h = 0;

    for _ in 0..n {
        let s = sc.next_chars();
        match s[0] {
            'M' => m += 1,
            'A' => a += 1,
            'R' => r += 1,
            'C' => c += 1,
            'H' => h += 1,
            _ => (),
        }
    }

    let v = [m, a, r, c, h];
    let mut ans = 0;
    for i in 0..5 {
        for j in i + 1..5 {
            for k in j + 1..5 {
                ans += v[i] * v[j] * v[k];
            }
        }
    }

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

pub struct Scanner {
    buf: std::collections::VecDeque<String>,
}

impl Scanner {
    pub fn new() -> Self {
        Self {
            buf: std::collections::VecDeque::new(),
        }
    }

    fn scan_line(&mut self) {
        let mut flag = 0;
        while self.buf.is_empty() {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            let mut iter = s.split_whitespace().peekable();
            if iter.peek().is_none() {
                if flag >= 5 {
                    panic!("There is no input!");
                }
                flag += 1;
                continue;
            }

            for si in iter {
                self.buf.push_back(si.to_string());
            }
        }
    }

    pub fn next<T: std::str::FromStr>(&mut self) -> T {
        self.scan_line();
        self.buf
            .pop_front()
            .unwrap()
            .parse()
            .unwrap_or_else(|_| panic!("Couldn't parse!"))
    }

    pub fn next_usize(&mut self) -> usize {
        self.next()
    }

    pub fn next_isize(&mut self) -> isize {
        self.next()
    }

    pub fn next_chars(&mut self) -> Vec<char> {
        self.next::<String>().chars().collect()
    }

    pub fn next_string(&mut self) -> String {
        self.next()
    }

    pub fn next_char(&mut self) -> char {
        self.next()
    }

    pub fn next_float(&mut self) -> f64 {
        self.next()
    }
}


use proconio::input;
use proconio::marker::Chars;

fn main() {
    input! {
        n: usize,
        s: [Chars; n],
    }

    let mut counter = vec![0; 5];
    for ns in &s {
        match ns[0] {
            'M' => counter[0] += 1,
            'A' => counter[1] += 1,
            'R' => counter[2] += 1,
            'C' => counter[3] += 1,
            'H' => counter[4] += 1,
            _ => {}
        }
    }

    let mut ans = 0;
    for bit in 0u64..1 << 5 {
        if bit.count_ones() == 3 {
            let mut sub_ans = 1;
            for i in 0..5 {
                if (bit >> i & 1) != 0 {
                    sub_ans *= counter[i];
                }
            }
            ans += sub_ans;
        }
    }

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


// 🐋💭
import Foundation

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

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}

func readLines() -> [String] {
    return readLine()!.map { String($0) }
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}

///最大公約数を返す
func gcd(_ array: [Int]) -> Int {
    var value = array[0]
    if array.count > 1 {
        for i in 1..<array.count {
            value = gcd(value, array[i])
        }
    }
    return value
}

///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    let aryMarch = ["M", "A", "R", "C", "H"]
    var march = [Int](repeating: 0, count: 5)
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力

    for _ in 0..<n {
        let s = readLines()[0]
        for i in 0..<aryMarch.count {
            if  s == aryMarch[i] {
                march[i] += 1
                break
            }
        }
    }
    var ans = 0

    for i in 0...2 {
        for j in i + 1...3 {
            for k in j + 1..<march.count {
                ans += march[i] * march[j] * march[k]
            }
        }
    }
    print(ans)
}
main()


// 🐋💭
import Foundation

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

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}

func readLines() -> [String] {
    return readLine()!.map { String($0) }
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}

///最大公約数を返す
func gcd(_ array: [Int]) -> Int {
    var value = array[0]
    if array.count > 1 {
        for i in 1..<array.count {
            value = gcd(value, array[i])
        }
    }
    return value
}

///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var aryName = [String]()
    let march = ["M", "A", "R", "C", "H"]

    for i in 0..<n {
        let str = readLines()[0]
        var isMarch = false
        for i in 0..<march.count {
            if str == march[i] {
                isMarch = true
            }
        }
        if isMarch {
            aryName.append(str)
        }
    }
    if aryName.count < 3 {
        print(0)
        return
    }
    var ans = 0

    for i in 0..<aryName.count {
        for j in i..<aryName.count {
            if aryName[i] == aryName[j] { continue }
            for k in j..<aryName.count {
                if aryName[i] == aryName[k] || aryName[j] == aryName[k] {
                    continue
                }
                ans += 1
            }
        }
    }
    print(ans)
}
main()


function Main(input){
  input = input.split('\n');
  const n = parseInt(input[0], 10);

  const atama = ['M', 'A', 'R', 'C', 'H'];
  let count = [0,0,0,0,0];

  for(const str of input){
    const k = str.substr(0,1);
    for(let i=0; i<5; i++){
      if(k == atama[i]){
        count[i]++;
      }
    }
  }

  let ans = 0;
  const p = [0,0,0,0,0,0,1,1,1,2];
  const q = [1,1,1,2,2,3,2,2,3,3];
  const r = [2,3,4,3,4,4,3,4,4,4];

  for(let i=0; i<10; i++){
    ans += count[p[i]] * count[r[i]] * count[q[i]];
  }
  console.log(ans);
}

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


function main (input) {
  input = input.trim().split("\n");
  const n = Number(input[0]);
  const map = {
    M: 0,
    A: 0,
    R: 0,
    C: 0,
    H: 0
  };
  for (let i = 1; i <= n; i++) {
    const str = input[i];
    let target;
    if (str[0] === "M") {
      target = "M";
    } else if (str[0] === "A") {
      target = "A";
    } else if (str[0] === "R") {
      target = "R";
    } else if (str[0] === "C") {
      target = "C";
    } else if (str[0] === "H") {
      target = "H";
    }
    if (!map[target] {
      map[target] = 1;
    } else {
      map[target] = map[target] + 1;
    }
  }
  	const combinations = [
        ["M", "A", "R"],
        ["M", "A", "C"],
        ["M", "A", "H"],
        ["M", "R", "C"],
        ["M", "R", "H"],
        ["M", "C", "H"],
        ["A", "R", "C"],
        ["A", "R", "H"],
        ["A", "C", "H"],
        ["R", "C", "H"]
  	];
	let result = 0;
	for(const combination of combinations) {
		result += combination.map(c => map[c]).reduce((a, b) => a*b);
    }
    console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


var input = require('fs').readFileSync('/dev/stdin', 'utf8');

var inputList = input.split('\n');

var n = Number(inputList[0]);

var capitalWordsList = inputList[1].split(' ').map(i => i.split('')[0]);

var mNum = capitalWordsList.filter(s => s === 'M').length;
var aNum = capitalWordsList.filter(s => s === 'A').length;
var rNum = capitalWordsList.filter(s => s === 'R').length;
var cNum = capitalWordsList.filter(s => s === 'C').length;
var hNum = capitalWordsList.filter(s => s === 'H').length;

var lengthList = [mNum, aNum, rNum, cNum, hNum];

var threeList = [];

var chooseThreeFromArr = (arr) => {
  for (var i=0;i<3;i++) {
    var list1 = [];
    list1.push(arr[i]);
    for (var j=i+1;j<5;j++) {
      var list2 = list1.slice();
      list2.push(arr[j]);
      for (var k=j+1;k<5;k++) {
        var list3 = list2.slice();
        list3.push(arr[k]);
        threeList.push(list3);
      }
    }
  }
}

chooseThreeFromArr(lengthList);

const result = threeList.map((i) => i.reduce((a,b)=>a*b)).reduce((a,b)=>a+b);

console.log(result);


import math

a, b, c, k = map(int, input().split(" "))

_sum = 0
if a >= k:
    print(k)
    exit()
else:
    _sum += a
    k -= a

if b >= k:
    print(_sum)
    exit()
else:
    k -= b

print(_sum - k)


A, B, C, K = list(map(int, input().split()))

if(A-K < 0):
    if((A-K)-B < 0):
        print(A - (K-A-B))
    else:
        print(K-A)
else:
    print(K)


A, B, C, K = map(int, input().split())
if K <= A:
  print(K)
elif A < K < A + B:
  print(A)
else:
  x = K - (A + B)
  print(A - x)


A,B,C,K=map(int,input().split())

if A+B>=K:
    print(A)
else:
    m=K-(A+B)
    print(A-m)


a, b, c, k = map(int, input().split())
ans = 0
if a >= k:
    print(a)
    exit()
elif a < k:
    ans += a
    k -= a
if b >= k:
    print(ans)
    exit()
elif a < k:
    k -= a
ans -= (k-a)
print(ans)


a, b, c, k = [int(num) for num in input().split(" ")]
sum = 0

if a > k:
    sum = k
    k = 0
else:
    sum = a
    k -= a

if b > k and k != 0:
    k = 0
elif b < k:
    k -= b

if c > k and k != 0:
    sum -= k
    k -= 0
elif b < k:
    sum -= c
print(sum)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
  private static class FastScanner {
    private BufferedReader reader = null;
    private StringTokenizer tokenizer = null;

    public FastScanner(InputStream in) {
      reader = new BufferedReader(new InputStreamReader(in));
      tokenizer = null;
    }

    public String next() {
      if (tokenizer == null || !tokenizer.hasMoreTokens()) {
        try {
          tokenizer = new StringTokenizer(reader.readLine());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
      return tokenizer.nextToken();
    }

    public String nextLine() {
      if (tokenizer == null || !tokenizer.hasMoreTokens()) {
        try {
          return reader.readLine();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }

      return tokenizer.nextToken("\n");
    }

    public long nextLong() {
      return Long.parseLong(next());
    }

    public int nextInt() {
      return Integer.parseInt(next());
    }

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

    public int[] nextIntArray(int n) {
      int[] a = new int[n];
      for (int i = 0; i < n; i++)
        a[i] = nextInt();
      return a;
    }

    public long[] nextLongArray(int n) {
      long[] a = new long[n];
      for (int i = 0; i < n; i++)
        a[i] = nextLong();
      return a;
    }
  }

  public static void main(String[] args) {
    FastScanner sc = new FastScanner(System.in);
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();
    int k = sc.nextInt();
    int result;
    if (a >= k) result = k;
    else if (a + b >= k) result = a;
    else result = a - (k - a - b);
    System.out.println(result);
  }
}


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

public class Main
{
	public static void main(String[] Arguments) throws IOException
	{
		BufferedReader BR = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer ST = new StringTokenizer(BR.readLine());
		int A = Integer.parseInt(ST.nextToken()), B = Integer.parseInt(ST.nextToken()), C = Integer.parseInt(ST.nextToken()), K = Integer.parseInt(ST.nextToken()), Sum = 0;
		Sum += Math.min(A, K);
		K -= Math.min(A, K);
		K -= Math.min(B, K);
		Sum -= Math.min(C, K);
		System.out.println(Sum);
	}
}


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

public class Main{
	static PrintWriter out=new PrintWriter(System.out);
	public static void main (String[] args) throws IOException{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

		String[] input=br.readLine().trim().split(" ");

		int a=Integer.parseInt(input[0]);
		int b=Integer.parseInt(input[1]);
		int c=Integer.parseInt(input[2]);
		int k=Integer.parseInt(input[3]);

		out.println(maxSum(a,b,c,k));

		out.flush();
		out.close();
	}
	public static int maxSum(int a,int b,int c,int k)
	{
	   int ans=0;
	   if(a>=k){
	       ans+=k;
	   }
	   else{
	       ans+=a;
	       k-=a;
	       if(b>=k){

	       }
	       else{
	           k-=b;
	           ans-=k;
	       }
	   }
	   return ans;
	}
}


import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
        int A = sc.nextInt();
        int B = sc.nextInt();
        int C = sc.nextInt();
        int K = sc.nextInt();
        int sum = 0;
        int max = 0;
        //int max = Math.pow(10,9);
        int a = 1;
        int b = 0;
        int c = -1;

        for(int i=0; i<K-2 ; i++) {
          for(int j=i+1; j<K-1 ; j++) {
            for(int k=j+1; k<K ; k++) {
              sum = a*i + b*j + c*k;
              if(sum>=max) {
                max = sum;
              }
            }
          }
        }
       System.out.println(max);
    }
}


import java.util.*;
import java.math.BigInteger;
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();
    int k = sc.nextInt();
    int ans = 0;
    for (int i = 1; i <= k; i++) {
      if (i <= a) ans++;
      if (i > a+b) ans--;
  }
  System.out.println(ans);
  }
}


import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long a = sc.nextLong(); // 1
		long b = sc.nextLong(); // 0
		long c = sc.nextLong(); // -1
		long k = sc.nextLong();

		if (a + b >= k) {
			System.out.println(a);
		} else {
			long ans = a + b - k + a;
			System.out.println(ans);
		}
	}
}


#include <stdio.h>
#include <string.h>
int main(){
	int a, b, c, d, s=0;
	scanf("%d%d%d%d", &a, &b, &c, &d);
	if(d >= a) s += a, d -= a;
	else s += d, d -= d;
	if(d >= b) s += 0, d -= b;
	else s += 0, d -= d;
	if(d >= c) s -= c, d -= c;
	else s -= d, d -= d;
	printf("%d\n", s);
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define LL long long
#define DB double
#define PI 3.14159265358979
#define MOD 1000000007
#define ERR 0.00000000000001
#define NUM 200010

int main(){
    int a, b, c, k;
    scanf("%d %d %d %d",&a,&b,&c,&k);
    if(k<=a){ printf("%d",k); }
    else if(k<=a+b){ printf("%d",a); }
    else if(k<=a+b+c){ printf("%d",a-(k-a-b)); }
    return 0;
}


#include <cstdio>

int main()
{
    int A,B,C,K;
    int out;

    // input
    scanf("%d %d %d %d", &A, &B, &C, &K);

    // process
    if ( A > K ) {
        out = K;
    } else if ( A + B > K ) {
        out = A;
    } else {
        out = A - ( K - ( A + B ) );
    }

    // output
    printf( "%d\n", out );

    return 0;
}


// MandaB.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。
//

#include <iostream>
using namespace std;

int main()
{
	int A, B, C, K;
	cin >> A >> B >> C >> K;
	int ans = 0;
	for (int i = 0; i < K; i++)
	{
		if (A!=0)
		{
			ans += 1;
			A--;
		}
		else if (B!=0)
		{
			B--;
		}
		else
		{
			ans -= 1;
			C--;
		}
	}
	cout << ans << endl;
}

// プログラムの実行: Ctrl + F5 または [デバッグ] > [デバッグなしで開始] メニュー
// プログラムのデバッグ: F5 または [デバッグ] > [デバッグの開始] メニュー

// 作業を開始するためのヒント:
//    1. ソリューション エクスプローラー ウィンドウを使用してファイルを追加/管理します
//   2. チーム エクスプローラー ウィンドウを使用してソース管理に接続します
//   3. 出力ウィンドウを使用して、ビルド出力とその他のメッセージを表示します
//   4. エラー一覧ウィンドウを使用してエラーを表示します
//   5. [プロジェクト] > [新しい項目の追加] と移動して新しいコード ファイルを作成するか、[プロジェクト] > [既存の項目の追加] と移動して既存のコード ファイルをプロジェクトに追加します
//   6. 後ほどこのプロジェクトを再び開く場合、[ファイル] > [開く] > [プロジェクト] と移動して .sln ファイルを選択します


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

int main()
{
    long long int p,q,r,k;
    cin>>p>>q>>r>>k;
    if(k<=p)
        cout<<p<<endl;
    else if(k<=(p+q))
        cout<<p<<endl;
    else
        cout<<p-(k-p-q)<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int mod = 200003;
typedef long long ll;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ll,int> pli;
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define sortall(x) sort(all(x))
#define fr(s,n) for (int i=(int)(s);i<(int)(n);i++)
#define lc cout<<"\n"
double pi=2*acos(0.0);
int main(){
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    ll a,b,c,k;
    cin>>a>>b>>c>>k;
    ll sum=0;
    if(k){
        if(k>=a){
            sum+=a;
            k-=a;
        }
        else{
            sum+=k;
            k-=k;
        }
    }
    if(k){
        if(k>=b){
            k-=b;
        }
        else{
            k-=k;
        }
    }
    if(k){
        if(k=c){
            sum-=c;
        }
        else{
            sum-=k;
        }
    }
    cout<<sum;
}


#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    intmax_t A, B, C, K;
    intmax_t ans = 0;

    scanf("%jd%jd%jd%jd", &A, &B, &C, &K);

    if (A < K) {
        ans = A;
    } else {
        ans = K;
    }
    K -= A;
    K -= B;
    if (K > 0) {
        ans -= K;
    }

    printf("%jd\n", ans);

    return 0;
}


#include<stdio.h>
int a,b,c,k,i,r;
int main(){
    scanf("%d%d%d%d",&a,&b,&c,&k);
    if(k<=a)printf("%d",k);
    else if(k<=a+b)printf("%d",a);
    else printf("%d",a-(k-a-b));
    return 0;
}


#include<stdio.h>
int main(){
  int a,b,c,k,count;
  scanf("%d%d%d%d",&a,&b,&c,&k);
  if(a>=k)
    count=k;
  else if(a+b>=k)
    count=a;
  else
    count=2*a+b-k;
  printf("%d\n",count);
  return 0;
}


#include <stdio.h>
#include <string.h>
#include <math.h>
#pragma warning(disable : 4996)

int main()
{
    long A, B, C, K;
    long a=0, b=0, c=0;
    int i, j;
    int r;

    scanf("%ld %ld %ld %ld", &A, &B, &C, &K);

    for (i = 0; i < K; i++) {
        if (A > 0) {
            A--;
            a++;
            continue;
        }

        if (B > 0) {
            B--;
            b++;
            continue;
        }

        if (C > 0) {
            C--;
            c++;
            continue;
        }

    }

    printf("%ld",a*1+b*0+c*(-1));

    return 0;

}


#include <stdio.h>

int main() {
	int A,B,C,K,i;
	scanf("%d %d %d %d", &A, &B, &C, &K);
		if (K <= A + B) {
			printf("%d", A);
		}
		else{
			printf("%d", A - (K - A - B));
		}
	return 0;
}


#include <stdio.h>
int main(void)
{
    int A,B,C,K;
    scanf("%d %d %d %d",&A,&B,&C,&K);
    if(A >= K){
        printf("%d",K);
    }else if(A+B >= K){
        printf("%d",A);
    }else{
        printf("%d",2*A+B-K)
    }
}


function main(input) {
  let [A, B, C, K] = input.split(' ').map(Number)
  let v = 0
  K = K - A
  if (K <= 0) {
    v += (K + A)
    console.log(v)
    return
  } else {
    v += A
  }
  // console.log(v, K)
  K = K - B
  if (K <= 0) {
    console.log(v)
    return
  }
  // console.log(v, K)
  K = K - C
  if (K <= 0) {
    v -= (K + C)
    console.log(v)
  } else {
    v -= C
    console.log(v)
  }
}

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


inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')
l = inp.shift().split(" ")
A = l.shift() * 1
B = l.shift() * 1
C = l.shift() * 1
K = l.shift() * 1

if (K - A < 0) {
    console.log(K)
} else {
    k = K - A;
    if (k - B < 0) {
        console.log(A)
    } else {
        k = k - B
        if (k - C < 0) {
            console.log(A - k)
        } else {
            console.log(A - C)
        }
    }
}


function Main(input) {
	var str = input;
	var ans = 0;
	str = str.split("\n")[0];
	str = str.split(" ");
	var a = Number(str[0]);
	var b = Number(str[1]);
	var c = Number(str[2]);
	var k = Number(str[3]);
	ans = Number(ans);
	if (a <= k){
	ans = a;
	k = k - a;
	k = k - b;
		if(k > 0){
			ans = ans - k;
		}
   	}else{
   		ans = k;
   	}
	   console.log(ans);
}
 //*おまじない
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const main = (input) => {
  let [a, b, c, k] = input.trim().split(' ').map(Number)

  let ans = a
  k -= a
  k -= b

  if (k > 0) ans -= k

  return console.log(ans)

}

process.env.MYTEST
  ? (process.env.MYTEST === 'test' ? test() : main(require('fs').readFileSync('dev/stdin', 'utf8')))
  : main(require('fs').readFileSync('/dev/stdin', 'utf8'))


const main = stdin => {
  const [A, B, C, K] = stdin.trim().split(' ').reduce((acc, value) => {
    acc.push(parseInt(value))
    return acc
  }, [])

  if (A >= K) {
    console.log(A)
  } else if (B >= K - A) {
    console.log(A)
  } else {
    console.log(A - (K - A - B))
  }
}

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


const main = stdin => {
  const [A, B, C, K] = stdin.trim().split(' ').reduce((acc, value) => {
    acc.push(parseInt(value))
    return acc
  }, [])

  if (A >= K) {
    console.log(1 * A)
  } else if (B >= K - A) {
    console.log(1 * A)
  } else {
    console.log(1 * A - 1 * (K - A - B))
  }
}

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


package main

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

const (
	maxBufsize = 1000000
)

func inputs(lines int, rdr *bufio.Reader) []string {
	var strSlice []string

	//rdr := bufio.NewReaderSize(os.Stdin, maxBufsize)

	for i := 0; i < lines; i++ {

		line := ReadLine(rdr)
		strSlice = append(strSlice, line)

	}

	return strSlice
}

// ReadLine is to read long line
func ReadLine(rdr *bufio.Reader) string {
	buf := make([]byte, 0, maxBufsize)
	for {
		l, p, e := rdr.ReadLine()

		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}

	return string(buf)
}

//DivideConvertInt is to divide and convert
func DivideConvertInt(line string, num int) []int {
	tmp := strings.Split(line, " ")

	intSlice := make([]int, num)

	for i := 0; i < num; i++ {
		intTmp, _ := strconv.Atoi(tmp[i])
		intSlice[i] = intTmp
	}

	return intSlice
}

func main() {
	rdr := bufio.NewReaderSize(os.Stdin, maxBufsize)
	lines := inputs(1, rdr)

	lineInt := DivideConvertInt(lines[0], 4)

	A := lineInt[0]
	B := lineInt[1]
	//C := lineInt[2]
	K := lineInt[3]

	if K <= A {
		fmt.Println(K)
		return
	}

	remaining := K - A

	if remaining <= B {
		fmt.Println(A)
		return
	}

	remaining = remaining - B

	fmt.Println(A - remaining)

}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	list := getStdinIntArr()
	A := list[0]
	B := list[1]
	C := list[2]
	K := list[3]

	A_N := A - K
	if A_N < 0 {
		K = K - A
		A_N = A
	} else {
		K = 0
		A_N = A - A_N
	}

	B_N := B - K
	if B_N < 0 {
		K = K - B
		B_N = B
	} else {
		K = 0
		B_N = B - B_N
	}

	C_N := C - K
	if C_N < 0 {
		K = K - C
		C_N = C
	} else {
		K = 0
		C_N = C - C_N
	}

	fmt.Printf("%d\n", A_N+(-1)*C_N)
}

func getStdin() string {
	sc.Scan()
	return sc.Text()
}
func getStdinInt() int {
	str := getStdin()
	rtn, _ := strconv.Atoi(str)
	return rtn
}
func getStdinIntArr() []int {
	str := getStdin()
	list := strings.Split(str, " ")
	rtn := make([]int, len(list))
	for idx, val := range list {
		rtn[idx], _ = strconv.Atoi(val)
	}
	return rtn
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	list := getStdinIntArr()
	A := list[0]
	B := list[1]
	C := list[2]
	K := list[3]

	if A >= K {
		fmt.Printf("%d", K)
		return
	}
	K = K - A

	if B >= K {
		fmt.Printf("%d", A)
		return
	}
	K = K - B

	if C >= K {
		fmt.Printf("%d", A-K)
		return
	}
	fmt.Printf("%d\n", A-C)
}

func getStdin() string {
	sc.Scan()
	return sc.Text()
}
func getStdinInt() int {
	sc.Scan()
	rtn, _ := strconv.Atoi(sc.Text())
	return rtn
}
func getStdinInt64() int64 {
	sc.Scan()
	rtn, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return rtn
}
func getStdinIntArr() []int {
	sc.Scan()
	str := sc.Text()
	list := strings.Split(str, " ")
	rtn := make([]int, len(list))
	for idx, val := range list {
		rtn[idx], _ = strconv.Atoi(val)
	}
	return rtn
}
func getStdinIntArr64() []int64 {
	sc.Scan()
	str := sc.Text()
	list := strings.Split(str, " ")
	rtn := make([]int64, len(list))
	for idx, val := range list {
		rtn[idx], _ = strconv.ParseInt(val, 10, 64)
	}
	return rtn
}


//go:generate echo "https://atcoder.jp/contests/abc167/tasks/abc167_b"
package main

import (
	"bufio"
	"fmt"
	"io"
	"math/big"
	"os"
	"strconv"
)

var scan = newScanner(os.Stdin)

func Solve(A, B, C, K int) int {
	sum := 0
	for i, n := range []int{A, B, C} {
		for j := 0; j < n; j++ {
			switch i {
			case 0:
				sum++
			case 1:
			case 2:
				sum--
			}
			K--
			if K == 0 {
				return sum
			}
		}
	}
	return sum
}

func main() {
	A, B, C, K := scan.Int(), scan.Int(), scan.Int(), scan.Int()
	fmt.Println(Solve(A, B, C, K))
}

type scanner struct {
	*bufio.Scanner
}

func newScanner(r io.Reader) *scanner {
	s := bufio.NewScanner(r)
	s.Split(bufio.ScanWords)
	s.Buffer(nil, 100000000)
	return &scanner{s}
}

func (s *scanner) String() string {
	s.Scan()
	return s.Text()
}

func (s *scanner) Strings(l int) []string {
	if l == 0 {
		return []string{}
	}
	sl := make([]string, l, l)
	for i := range sl {
		sl[i] = s.String()
	}
	return sl
}

func (s *scanner) Int() int {
	n, _ := strconv.Atoi(s.String())
	return n
}

func (s *scanner) Ints(l int) []int {
	if l == 0 {
		return []int{}
	}
	sl := make([]int, l, l)
	for i := range sl {
		sl[i] = s.Int()
	}
	return sl
}

func (s *scanner) Float64() float64 {
	f, _ := strconv.ParseFloat(s.String(), 64)
	return f
}

func (s *scanner) Floats64(l int) []float64 {
	if l == 0 {
		return []float64{}
	}
	sl := make([]float64, l, l)
	for i := range sl {
		sl[i] = s.Float64()
	}
	return sl
}

func (s *scanner) BigInt() *big.Int {
	n, _ := strconv.ParseInt(s.String(), 10, 64)
	return big.NewInt(n)
}

func (s *scanner) BigInts(l int) []*big.Int {
	if l == 0 {
		return []*big.Int{}
	}
	sl := make([]*big.Int, l, l)
	for i := range sl {
		sl[i] = s.BigInt()
	}
	return sl
}

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

func imax(x, y int) int {
	if x > y {
		return x
	}
	return y
}

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

func ipow(x, n int) int {
	if n == 0 {
		return 1
	}
	a := ipow(x, n>>1)
	a *= a
	if n&1 != 0 {
		a *= x
	}
	return a
}

func chmax(x *int, v int) {
	if *x < v {
		*x = v
	}
}

func chmin(x *int, v int) {
	if *x > v {
		*x = v
	}
}

func factor(n int) map[int]int {
	m := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			n /= i
			m[i]++
		}
	}
	if n != 1 {
		m[n]++
	}
	return m
}

var mod = 1000000007

func setMintMod(x int) {
	mod = x
}

type mint int

func newMint(v int) mint {
	return mint((v%mod + mod) % mod)
}

func (x mint) Add(y mint) mint {
	v := x + y
	if v >= mint(mod) {
		return v - mint(mod)
	}
	return v
}

func (x mint) Sub(y mint) mint {
	v := x + mint(mod) - y
	if v >= mint(mod) {
		return v - mint(mod)
	}
	return v
}

func (x mint) Mul(y mint) mint {
	return (x * y) % mint(mod)
}

func (x mint) pow(n int) mint {
	if n == 0 {
		return mint(1)
	}
	a := x.pow(n >> 1)
	a = a.Mul(a)
	if n&1 != 0 {
		a = a.Mul(x)
	}
	return a
}

func (x mint) Inverse() mint {
	return x.pow(mod - 2)
}

func (x mint) Div(y mint) mint {
	return x * y.Inverse()
}

func (x mint) Neg() mint {
	return newMint(int(-x))
}

type factorial struct {
	fact        []mint
	factInverse []mint
}

func newFactorial(n int) *factorial {
	f := new(factorial)
	f.init(n)
	return f
}

func (f *factorial) init(n int) {
	fact := make([]mint, n+1, n+1)
	fact[0] = newMint(1)
	for i := 1; i <= n; i++ {
		fact[i] = fact[i-1].Mul(newMint(i))
	}

	inv := make([]mint, n+1, n+1)
	inv[n] = fact[n].Inverse()
	for i := n; i >= 1; i-- {
		inv[i-1] = inv[i].Mul(newMint(i))
	}

	f.fact = fact
	f.factInverse = inv
}

func (f *factorial) Get(n int) mint {
	return f.fact[n]
}

func (f *factorial) GetInverse(n int) mint {
	return f.factInverse[n]
}

func (f *factorial) Permutation(n, k int) mint {
	if k < 0 || n < k {
		return 0
	}
	return f.fact[n].Mul(f.factInverse[n-k])
}

func (f *factorial) Combination(n, k int) mint {
	if k < 0 || n < k {
		return 0
	}
	return f.fact[n].Mul(f.factInverse[k]).Mul(f.factInverse[n-k])
}

type sieve struct {
	n          int
	primes     []int
	maxFactors []int
}

func newSieve(n int) *sieve {
	s := &sieve{
		n:          n,
		primes:     []int{},
		maxFactors: make([]int, n+1, n+1),
	}
	s.init()
	return s
}

func (s *sieve) init() {
	s.maxFactors[0] = -1
	s.maxFactors[1] = -1
	for i := 2; i <= s.n; i++ {
		if s.maxFactors[i] != 0 {
			continue
		}
		s.primes = append(s.primes, i)
		s.maxFactors[i] = i
		for j := i * i; j <= s.n; j += i {
			if s.maxFactors[j] == 0 {
				s.maxFactors[j] = i
			}
		}
	}
}

func (s *sieve) IsPrime(x int) bool {
	return s.maxFactors[x] == x
}

func (s *sieve) Factor(x int) map[int]int {
	m := map[int]int{}
	for x != 1 {
		m[s.maxFactors[x]]++
		x /= s.maxFactors[x]
	}
	return m
}


package main

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

func main() {
	sc := newScanner()
	sc.Scan()
	a, _ := strconv.Atoi(sc.Text())
	sc.Scan()
	b, _ := strconv.Atoi(sc.Text())
	sc.Scan()
	c, _ := strconv.Atoi(sc.Text())
	sc.Scan()
	k, _ := strconv.Atoi(sc.Text())

	ans := solve(a, b, c, k)
	fmt.Println(ans)
}

func solve(a, b, c, k int) (ans int) {
	for i := 0; i < k; i++ {
		if i < a {
			ans++
		} else if b <= i && i < c {
			ans--
		}
	}
	return ans
}

func newScanner() *bufio.Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer([]byte{}, math.MaxInt64)
	sc.Split(bufio.ScanWords)
	return sc
}


package main

import "fmt"

func main() {
	var a, b, c, k int
	fmt.Scan(&a, &b, &c, &k)
	ans := 0
	if a > 0 {
		if a >= k {
			ans += k
		} else {
			ans += a
		}
		k -= a
	}
	if b > 0 && k > 0 {
		k -= b
	} else if k > 0 {
		ans -= k
	}

	fmt.Println(ans)
}


ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
# mod = 998244353
# mod = 10 ** 9 + 9
mod = 10 ** 9 + 7
PI = Math::PI
dx = [ 1,  0, -1,  0,  1,  1, -1, -1]
dy = [ 0,  1,  0, -1,  1, -1,  1, -1]
eight = [0, 1, 1, 0, -1, -1, 1, -1, 0]
def max(a,b);       a > b ? a : b                              end
def min(a,b);       a < b ?  a : b                             end
def swap(a,b);      a, b = b, a                                end
def gi;             gets.to_s.to_i                             end
def gf;             gets.to_s.to_f                             end
def gs;             gets.to_s.chomp                            end
def gmi(n=nil); n.nil? ? gets.to_s.split.map{|t|t.to_i} : n.times.map{ gets.to_s.to_i } end
def gmf(n=nil); n.nil? ? gets.to_s.split.map{|t|t.to_f} : n.times.map{ gets.to_s.to_f } end
def gms(n=nil); n.nil? ? gets.to_s.split : n.times.map{ gets.to_s.chomp } end
def ga2i(h);        h.times.map{ gets.to_s.split.map{|t|t.to_i} }      end
def gm(h);        Array.new(h){ gets.to_s.split.map{|t|t.to_i} }      end
def yn(f); puts f ? "Yes" : "No" end
#def YN(f); puts f ? "YES" : "NO" end
def yes(f=nil); f.nil? ? (puts "Yes"; exit) : (puts f ? "Yes" : "No") end
def no(f=nil); f.nil? ? (puts "No"; exit) : (puts f ? "Yes" : "No") end
def yay(f=nil); f.nil? ? (puts "Yay!"; exit) : (puts f ? "Yay!" : ":(") end

#n = gets.to_s.to_i
a, b, c, k = gets.to_s.split.map{|e|e.to_i}
#m = Array.new(n){ gets.to_s.split.map{|e|e.to_i} }
# s = gets.to_s.chomp
# t = gets.to_s.chomp

if k <= a
  puts k
elsif k <= a + b
  puts a
elsif k <= a + b + c
  puts a - ( k - a -b )
end


imput = gets.chomp.split(" ")
#puts imput
a = imput[0].to_i
b = imput[1].to_i
c = imput[2].to_i
k = imput[3].to_i
#puts a,b,c,k
if (a >= k) then
    puts k
else
    if (a + b >= k) then
        puts a
    else
        puts (a - (k-a-b))
        #puts k
    end
end


a, b, c, k = gets.chomp.split.map(&:to_i)
res = 0

res += [k, a].min
k -= a

if k > 0
  k -= b
end

if k > 0
  res -= k
end

puts res


a,b,c,k=gets.split.map(&:to_i)
l=[[1]*a,[0]*b,[-1]*c].flatten
p l[0,k].sum


a, b, c, k = gets.split(" ").map &:to_i
if a+b >= k
  puts k - b
else
  puts a - (k - (a+b))
end


a, b, c, k = gets.split(" ").map &:to_i
if a+b >= k
  puts k
else
  puts a - (k - (a+b))
end


// -*- coding:utf-8-unix -*-

use proconio::input;

fn main() {
    input! {
        t: (i64, i64, i64, i64),
    }
    let a = t.0;
    let b = t.1;
    let c = t.2;
    let k = t.3;

    if k <= a {
        println!("{}", k);
    } else if k <= a + b {
        println!("{}", a);
    } else if k <= a + b + c {
        let p = k - a - b;
        println!("{}", a - p);
    }
}


#![allow(unused_imports)]

//input
use proconio::input;
use proconio::marker::{Bytes, Chars};
//use std::io::Read;

//collections
//use std::collections::BTreeMap;
//use std::collections::BTreeSet;
//use std::collections::HashMap;
//use std::collections::HashSet;
//use std::collections::VecDeque;
//use std::collections::BinaryHeap;

//use std::cmp::*;

fn main() {
    input! {
        a: i64,
        b: i64,
        c: i64,
        mut k: i64,
    }
    let mut ans = 0i64;

    if k >= a {
        ans += a;
        k -= a;
    } else {
        ans += k;
        k = 0;
    }

    if k >= b {
        k -= b;
    } else {
        k = 0;
    }
    if k >= c {
        ans -= c;
        k -= c;
    } else {
        ans -= k;
        k = 0;
    }

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


use std::io::*;

fn main() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.trim().split_whitespace();
    let a: i64 = itr.next().unwrap().parse().unwrap();
    let b: i64 = itr.next().unwrap().parse().unwrap();
    let _: i64 = itr.next().unwrap().parse().unwrap();
    let mut k: i64 = itr.next().unwrap().parse().unwrap();

    let mut ans = 0;
    if k <= a {
        println!("{}", k);
        return;
    }
    k -= a;
    ans += a;
    if k <= b {
        println!("{}", ans);
        return;
    }
    k -= b;
    println!("{}", ans - k);
}


use proconio::*;
#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars};
use std::*;

#[allow(dead_code)]
const MOD: i128 = 100_000_007;

#[fastout]
fn main() {
    input!{
        a :usize,
        b : usize,
        c : usize,
        k : usize
    }
    let ans = if a >= k {
        k
    } else if a + b >= k {
        a
    } else {
        a - (k - a - b)
    };
    println!{"{}",ans};
}


use proconio::*;
#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars};
use std::*;

#[allow(dead_code)]
const MOD: i128 = 100_000_007;

#[fastout]
fn main() {
    input!{
        a :usize,
        b : usize,
        c : usize,
        k : usize
    }
    let ans = if a > k {
        k
    } else if a + b > k {
        a
    } else {
        a - (k - a - b)
    };
    println!{"{}",ans};
}


use std::*;
use std::io::*;
use std::iter::Iterator;
use std::str::FromStr;
#[allow(unused_imports)]
use std::fmt::{Display, Formatter};

#[allow(dead_code)]
fn main() {
  let stdin = stdin();
  let r = &mut BufReader::new(stdin.lock());
  let stdout = stdout();
  let w = &mut BufWriter::new(stdout.lock());
  let stderr = stderr();
  let err = &mut BufWriter::new(stderr.lock());
  run(r, w, err);
  w.flush().unwrap();
  err.flush().unwrap();
}

macro_rules! _ft { () => (impl FnOnce(&mut Cursor<Vec<u8>>, &mut Vec<u8>, &mut Vec<u8>)); }

#[allow(dead_code)]
fn test(input: &str, output: &str, f: _ft!()) {
  let r = &mut Cursor::new(input.as_bytes().to_vec());
  let w: &mut Vec<u8> = &mut Vec::new();
  let err: &mut Vec<u8> = &mut Vec::new();
  f(r, w, err);
  let mut stderr = stderr();
  writeln!(stderr, "{}", String::from_utf8(err.to_vec()).unwrap()).unwrap();
  stderr.flush().ok();
  assert_eq!(String::from_utf8(w.to_vec()).unwrap().trim(), output.trim())
}

#[allow(unused_macros)]
macro_rules! t {
  ($f: ident => $input: expr, $output: expr) => (
    #[test]
    fn $f() { test($input, $output, run); }
  );
}

macro_rules! _display_st {
    ($f: expr; $name: expr, ) => (write!($f, "{}", $name)?);
    ($f: expr; $name: expr) => (_display_st!($f; $name, ));
    ($f: expr; $name: expr, $($rest: expr),+, ) => (
      _display_st!($f; $name);
      write!($f, " ")?;
      _display_st!($f; $($rest, )+);
    );
    ($f: expr; $name: expr, $($rest: expr),+) => (_display_st!($f; $name, $($rest, )+));
}

macro_rules! _st_iter_parse {
  ($iter: expr; $($p: ident : $t: ty),+; ) => (Self {
    $($p: $iter.next().unwrap().parse::<$t>().unwrap(), )+
  });
  ($iter: expr; $($p: ident : $t: ty),+; 1~) => (Self {
    $($p: $iter.next().unwrap().parse::<$t>().unwrap() - 1, )+
  });
}

/// 構造体を作成する
#[allow(unused_macros)]
macro_rules! st {
  ($name: ident => $($p: ident : $t: ty),+; $($rest: tt)*) => (
    struct $name { $($p : $t),+ }
    impl FromStr for $name {
      type Err = ();
      fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let mut iter = s.split_whitespace();
        Ok(_st_iter_parse!(iter; $($p : $t),+; $($rest)*))
      }
    }
    impl Display for $name {
      fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        _display_st!(f; $(&self.$p, )+);
        Ok(())
      }
    }
  );
  ($name: ident => $($p: ident : $t: ty),+) => (st!($name => $($p : $t),+; ););

  ($name: ident => $($($p: ident),+: $t: ty);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($($p: ident),+: $($t: ty),+);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($p: ident),+: $t: ty) => (st!($name => $($p : $t),+););
  ($name: ident => $($p: ident),+: $($t: ty),+) => (st!($name => $($p : $t),+););

  ($name: ident => $($($p: ident),+: $t: ty);+; $($rest: tt)*) => (
    st!($name => $($($p : $t),+),+; $($rest)*);
  );
  ($name: ident => $($($p: ident),+: $($t: ty),+);+; $($rest: tt)*) => (
    st!($name => $($($p : $t),+),+; $($rest)*);
  );
  ($name: ident => $($p: ident),+: $t: ty; $($rest: tt)*) => (
    st!($name => $($p : $t),+; $($rest)*);
  );
  ($name: ident => $($p: ident),+: $($t: ty),+; $($rest: tt)*) => (
    st!($name => $($p : $t),+; $($rest)*);
  );
}

fn _read_iter<R: Read>(reader: &mut R) -> impl Iterator<Item=char> + '_ {
  reader.by_ref()
    .bytes()
    .map(|c| c.unwrap() as char)
    .skip_while(|c| c.is_whitespace())
}

#[allow(dead_code)]
fn read<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| !c.is_whitespace()).collect::<String>();
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read_line<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| c != &'\n').collect::<String>();
  let str = if str.ends_with('\r') { &str[0..str.len() - 1] } else { &str };
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read1<R: Read, T>(reader: &mut R, mut f: impl FnMut(char) -> T) -> T {
  f(_read_iter(reader).next().unwrap())
}

#[allow(dead_code)]
fn read1_line<R: Read, T>(reader: &mut R, f: impl FnMut(char) -> T) -> Vec<T> {
  _read_iter(reader).take_while(|c| c != &'\n').map(f).collect::<Vec<_>>()
}

/// 1要素読む
#[allow(unused_macros)]
macro_rules! r {
  ($stream: expr) => (read::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));

  ($stream: expr; $t: ty) => (read::<$t, _>($stream));
  ($stream: expr; $t: ty; 1~) => (r!($stream; $t) - 1);

  ($stream: expr; $($t: ty),+) => (($(r!($stream; $t)),*));
  ($stream: expr; $($t: ty),+; 1~) => (($(r!($stream; $t) - 1),*));

  ($stream: expr; $t: ty; $n: expr) => (
    (0..$n).map(|_| r!($stream; $t)).collect::<Vec<_>>()
  );
  ($stream: expr; $t: ty; $n: expr; 1~) => (
    (0..$n).map(|_| r!($stream; $t) - 1).collect::<Vec<_>>()
  );

  ($stream: expr; $t: ty; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r!($stream; $t)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
  ($stream: expr; $t: ty; $h: expr, $w: expr; 1~) => (
    (0..$h).map(|_| (0..$w).map(|_| r!($stream; $t) - 1).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
}

/// 1文字読む
#[allow(unused_macros)]
macro_rules! r1 {
  ($stream: expr) => (read1($stream, |c| c));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $f: expr) => (read1($stream, $f));
  ($stream: expr; $f: expr; ) => (r1!($stream, $f));
  ($stream: expr; $f: expr; $n: expr) => ((0..$n).map(|_| r1!($stream; $f)).collect::<Vec<_>>());
  ($stream: expr; $f: expr; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r1!($stream; $f)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );

  ($stream: expr; @$c: tt; $($tt: tt)*) => (
   r1!($stream; |c| c == stringify!($c).chars().next().unwrap(); $($tt)*)
  );
  ($stream: expr; @$c: tt/$_c: tt; $($tt: tt)*) => (r1!($stream; @$c; $($tt)*));
}

/// 1行読む
#[allow(unused_macros)]
macro_rules! rl {
  ($stream: expr) => (read_line::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $t: ty) => (read_line::<$t,  _>($stream));
  ($stream: expr; $t: ty; $n: expr) => ((0..$n).map(|_| rl!($stream; $t)).collect::<Vec<_>>());
}

macro_rules! _writes {
  ($stream: expr; $arg0: expr, $($arg: expr),*) => ({
    write!($stream, "{}", $arg0).ok();
    $(write!($stream, " {}", $arg).ok();)*
  });
}

/// 変数を出力
#[allow(unused_macros)]
macro_rules! w {
  ($stream: expr) => (write!($stream, " ").ok());
  ($stream: expr; ) => (w!($stream));
  ($stream: expr, ) => (w!($stream));

  ($stream: expr; $arg: expr) => (write!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (w!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => (_writes!($stream; $arg0, $($arg),+));
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (w!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (write!($stream, $($arg)*).ok());
}

/// 変数を改行付きで出力
#[allow(unused_macros)]
macro_rules! wl {
  ($stream: expr) => (writeln!($stream).ok());
  ($stream: expr, ) => (wl!($stream));
  ($stream: expr; ) => (wl!($stream));

  ($stream: expr; $arg: expr) => (writeln!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (wl!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => ({
    _writes!($stream; $arg0, $($arg),+);
    wl!($stream)
  });
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (wl!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (writeln!($stream, $($arg)*).ok());
}

/// ベクタを出力
#[allow(unused_macros)]
macro_rules! w_vec {
  ($stream: expr; $vec: expr) => (w_vec!($stream; $vec; $vec.len()));
  ($stream: expr; $vec: expr; $($tt: tt)*) => (w_vec!($stream; $vec => |e| e, " "; $($tt)*));

  ($stream: expr; $vec: expr => $f: expr) => (w_vec!($stream; $vec => $f; $vec.len()));
  ($stream: expr; $vec: expr => $f: expr; $($tt: tt)*) => (
    w_vec!($stream; $vec => $f, ""; $($tt)*)
  );

  ($stream: expr; $vec: expr => $f: expr, $del: expr; $n: expr) => (
    w!($stream; $f($vec[0]));
    for i in 1..$n { w!($stream, "{}{}", $del, $f($vec[i as usize])); }
    wl!($stream);
  );
  ($stream: expr; $vec: expr => $f: expr, $del: expr; $h: expr, $w: expr) => (
    for i in 0..$h { w_vec!($stream; $vec[i as usize] => $f, $del; $w); }
  );

  ($stream: expr; $vec: expr => String) => (w_vec!($stream; $vec => |c| c as char; $vec.len()));
  ($stream: expr; $vec: expr => String; $($tt: tt)*) => (
    w_vec!($stream; $vec => |c| c as char; $($tt)*)
  );

  ($stream: expr; $vec: expr => @$c_t: tt/$c_f: tt) => (
    w_vec!($stream; $vec => @$c_t/$c_f; $vec.len())
  );
  ($stream: expr; $vec: expr => @$c_t: tt/$c_f: tt; $($tt: tt)*) => (
    w_vec!($stream; $vec => |e| if e {stringify!($c_t)} else {stringify!($c_f)}; $($tt)*)
  );
}

/// ベクタを改行付きで出力
#[allow(unused_macros)]
macro_rules! wl_vec {
  ($stream: expr; $vec: expr) => (w_vec!($stream; $vec => |e| e, "\n"; $vec.len()));
  ($stream: expr; $vec: expr; $($tt: tt)*) => (w_vec!($stream; $vec => |e| e, "\n"; $($tt)*));
  ($stream: expr; $vec: expr => $f: expr) => (w_vec!($stream; $vec => $f, "\n"; $vec.len()));
  ($stream: expr; $vec: expr => $f: expr; $($tt: tt)*) => (
    w_vec!($stream; $vec => $f, "\n"; $($tt)*)
  );

  ($stream: expr; $vec: expr => 1~) => (wl_vec!($stream; $vec => |e| e + 1; $vec.len()));
  ($stream: expr; $vec: expr => 1~; $($tt: tt)*) => (
    w_vec!($stream; $vec => |e| e + 1, "\n"; $($tt)*)
  );

  ($stream: expr; $vec: expr => String) => (
    wl_vec!($stream; $vec => |c| c as char, "\n"; $vec.len())
  );
  ($stream: expr; $vec: expr => String; $($tt: tt)*) => (
    w_vec!($stream; $vec => |c| c as char, "\n"; $($tt)*)
  );

  ($stream: expr; $vec: expr => @$c_t: tt/$c_f: tt) => (
    wl_vec!($stream; $vec => @$c_t/$c_f; $vec.len())
  );
  ($stream: expr; $vec: expr => @$c_t: tt/$c_f: tt; $($tt: tt)*) => (
    w_vec!($stream; $vec => |e| if e {stringify!($c_t)} else {stringify!($c_f)}, "\n"; $($tt)*)
  );
}

/// 早期リターン
#[allow(unused_macros)]
macro_rules! early { ($($t: tt)*) => ({ w!($($t)*); return; }); }

/// 配列の初期化
#[allow(unused_macros)]
macro_rules! v {
  ($elem: expr; $n: expr) => (vec![$elem; $n as usize]);
  ($elem: expr; $h: expr, $w: expr) => (vec![vec![$elem; $w as usize]; $h as usize]);
}

// start: Copied Libraries

// end: Copied Libraries

#[allow(unused_variables)]
fn run<R: Read, W: Write, E: Write>(r_: &mut R, w_: &mut W, err: &mut E) {
  let (a, b, c, k) = r!(r_; usize, usize, usize, usize);
  if k <= a { early!(w_; k); }
  if k <= a + b { early!(w_; a); }
  w!(w_; a + a + b - k);
}

t!(tb1 => r"2 1 1 3", r"2");
t!(tb2 => r"1 2 3 4", r"0");
t!(tb3 => r"2000000000 0 0 2000000000", r"2000000000");


func readArrayInt() -> [Int] {
    readLine()!.split(separator: " ").map({Int($0)!})
}

let line = readArrayInt()
let (A, B, C, K) = (line[0], line[1], line[2], line[3])

if K <= A {
    print(K)
} else if K <= A + B {
    print(A)
} else {
    print(A - (K - A - B))
}


func solve(_ A: Int, _ B: Int, _ C: Int, _ K: Int) -> Int {

  var K = K
  if K <= A {
    return K
  }
  K -= A

  if K <= B {
    return A
  }

  K -= B

  return A - K

}

let line = readLine()!
let inputs = line.split(separator: " ")
var A = Int(inputs[0])!
var B = Int(inputs[1])!
var C = Int(inputs[2])!
var K = Int(inputs[3])!

print(solve(A, B, C, K))


import Foundation

var num = readLine()!.split(separator: " ").map{Int($0)!}
var p = 0
if(num[0] >= num[3]){
  p += num[3]
  num[3] = 0
}else{
  p += num[0]
  num[3] -= num[0] + num[1]
}
if(num[3] > 0){
  p -= num[3]
}
print(p)


import Foundation

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

func main(){
    let abck = readInts()
    let (a,b,_,k) = (abck[0],abck[1],abck[2],abck[3])

    var ans = 0

    if k <= a{
        print(k)
        return
    }

    if k - a - b > 0 {
        ans += a
        ans -= (k - a - b)*1
    }
    print(ans)
}

main()


import Foundation

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

func main(){
    let abck = readInts()
    let (a,b,_,k) = (abck[0],abck[1],abck[2],abck[3])

    var ans = 0

    if k <= a{
        print(k)
        return
    }

    if k - a - b > 0{
        ans -= (k - a - b)*1
    }
    print(ans)
}

main()


import Foundation

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

func main(){
    let abck = readInts()
    let (a,b,_,k) = (abck[0],abck[1],abck[2],abck[3])
    var ans = 0

    ans = a*1

    if k - a - b > 0{
     ans -= (k - a - b)*1
    }
    print(ans)
}

main()


function Main(input) {
    let rows = input.split("\n");
    let row  = rows[0].split(" ");
    let a = parseInt(row[0], 10);
    let b = parseInt(row[1], 10);
    let c = parseInt(row[2], 10);
    let k = parseInt(row[3], 10);
    if (a >= k) {
      console.log(k)
    } else {
      k -= a+b;
      console.log(a-k)
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


import * as fs from 'fs';

export function Main(input: string) {
    const [a, b, c, k] = input.split(' ')
        .map(x => parseInt(x));    // ?

    let result: number;

    if (k >= a) {
        result = a;
        if (k >= a + b) {
            result -= k - a - b;
        }
    } else {
        result = k;
    }

    //output
    console.log(result);
}

// Don't edit this line!
Main(fs.readFileSync("/dev/stdin", "utf8"));


import * as fs from 'fs';

const [a, b, c, k]: number[] = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n')[0].split(' ').map(Number);
let ans: number;
ans = (a >= k) ? k : a;
const kk = (a + b >= k) ? 0 : k - (a + b);
ans -= (c >= kk) ? kk : c;
console.log(ans);


import { readFileSync } from "fs";

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

const main = (input: string[][]) => {
  const [A, B, , K] = input[0].map(Number);

  return Math.min(A, K) - (K - (A + B));
};

console.log(main(read()));


import * as fs from 'fs';

export function main(input: string) {
  let [A, B, C, K] = input.split(" ").map(x => parseInt(x))

  let result = 0
  if(K <= A) {
    console.log(K);
  } else if(K <= A + B) {
    console.log(A);
  } else {
    console.log(a - (k - a - b));
  }
}

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


import * as fs from 'fs';

export function main(input: string) {
  let [A, B, C, K] = input.split(" ")
  A = parseInt(A)
  B = parseInt(B)
  C = parseInt(C)
  K = parseInt(K)

  let result = 0
  for(let i=0; i<A && K!==0; i++, K--) {
    result += 1;
  }

  for(let i=0; i<B && K!==0; i++, K--) {
    result += 0;
  }

  for(let i=0; i<C && K!==0; i++, K--) {
    result -= 1;
  }

  console.log(result)
}

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


import sys
from collections import Counter
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
l = read().decode().split()
c = Counter(l)
max = c.most_common()[0][1]
ans = [i[0] for i in c.items() if i[1] >= max]
print('\n'.join(sorted(ans)))


import sys
from collections import Counter

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
l = read().decode().split()
c = Counter(l)

max = c.most_common()[0][1]
ans = [i[0] for i in c.items() if i[1] >= max]

print('\n'.join(sorted(ans)))


n = int(input())
d = {}
for _ in range(n):
    s = input()
    if s in d:
        d[s] += 1
    else:
        d[s] = 1
m = d[max(d)]
l=[]
for i in d:
    if d[i] == m:
        l.append(i)
for i in sorted(l):
    print(i)


n = int(input())
d = {}
for _ in range(N):
    S = input()
    if S in d:
        d[S] += 1
    else:
        d[S] = 1
m = d[max(d)]
l=[]
for i in d:
    if d[i] == m:
        l.append(i)
for i in sorted(l):
    print(i)


n = int(input())
s = list(input() for _ in range(n))
d = {}
for i in range(n):
    if s[i] in d:
        d[s[i]] += 1
    else:
        d[s[i]] = 1
m = d[max(d)]
for s in sorted(k for k in d if d[k] == m):
    print(s)


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;

public class Main {
	public static void main(String[] args) throws Exception {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
			int n = Integer.parseInt(br.readLine());
			Map<String, Integer> map = new TreeMap<>();
			int max = 0;
			for (int i = 0; i < n; i++) {
				String s = br.readLine();
				int val = map.containsKey(s) ? map.get(s) + 1 : 1;
				map.put(s, val);
				max = Math.max(max, val);
			}
			PrintWriter out = new PrintWriter(System.out);
			for (String key : map.keySet()) {
				if (map.get(key) == max) {
					out.println(key);
				}
			}
			out.flush();
		}
	}
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.TreeMap;

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

		int n = stdIn.nextInt();
		Map<String,Integer> map = new TreeMap<>();
		int max = 0;
		for(int i = 0; i < n; i++) {
			String s = stdIn.next();
			int val = map.containsKey(s)?map.get(s)+1:1;
			map.put(s,val);
			max = Math.max(max, val);

		}
		for(String s:map.keySet()) {
			if(map.get(s)==max) {
				out.println(s);
			}
		}
		out.flush();

	}

}
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.*;
import java.util.*;

public class Main {
	public static void main(String[] args) throws Exception {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
			int n = Integer.parseInt(br.readLine());
			Map<String, Integer> map = new TreeMap<>();
			int max = 0;
			for (int i = 0; i < n; i++) {
				String s = br.readLine();
				int val = map.containsKey(s) ? map.get(s) + 1 : 1;
				map.put(s, val);
				max = Math.max(max, val);
			}
			PrintWriter out = new PrintWriter(System.out);
			for (String key : map.keySet()) if (map.get(key) == max) out.println(key);
			out.flush();
		}
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> si = new HashMap<String, Integer>();

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        sc.nextLine();

        for (int i = 0; i < N; i++) {
            String s;
            s = sc.next();
            si.put(s,si.getOrDefault(s,0)+1);
        }

        Iterator it = si.entrySet().iterator();
        ArrayList arr = new ArrayList();
        int currentMax = 0;

        while(it.hasNext()) {
            Map.Entry<String,Integer> set = (Map.Entry<String, Integer>) it.next();

            if (set.getValue()>currentMax) {
                arr.clear();
                arr.add(set.getKey());
                currentMax = set.getValue();
            }

            else if (set.getValue()==currentMax) {
                arr.add(set.getKey());
            }

            else {

            }
        }

        for (int i = 0; i < arr.size(); i++) {
            System.out.println(arr.get(i));
        }
    }
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> si = new HashMap<String, Integer>();

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        sc.nextLine();

        for (int i = 0; i < N; i++) {
            String s;
            s = sc.next();

            si.put(s,si.getOrDefault(s,0)+1);
        }

        Iterator it = si.entrySet().iterator();
        ArrayList arr = new ArrayList();
        int currentMax = 0;

        while(it.hasNext()) {
            Map.Entry<String,Integer> set = (Map.Entry<String, Integer>) it.next();

            if (set.getValue()>currentMax) {
                arr.clear();
                arr.add(set.getKey());
                currentMax = set.getValue();
            }

            else if (set.getValue()==currentMax) {
                System.out.println(set.getKey() + " added");
                arr.add(set.getKey());
            }

            else {

            }
        }

        System.out.println(arr.size());

        for (int i = 0; i < arr.size(); i++) {
            System.out.println(arr.get(i));
        }
    }
}


import java.util.*;

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

        int n = sc.nextInt();
        String[] str = new String[n];
        int[] count = new int[n];
        String[] ans = new String[n];
        int max = 0;

        for(int i=0; i<n; i++){
            str[i] = sc.next();
        }

        Arrays.sort(str);

         for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                if(str[i].equals(str[j])){
                    count[i]++;
                }
            }
            if(max<count[i]){
                max = count[i];
            }
        }

        if(max==n){
            System.out.println(str[0]);
            return;
        }

        int a=0;
        for(int i=0; i<n; i++){
            if(max==count[i]){
                ans[i] = str[i];
                //System.out.println(ans[i]);
                a++;
            }
        }

        for(int i=1; i<a; i=i+max){
            System.out.println(ans[i+max]);
        }
   }
}


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline ll getint() {
	ll A = 0;
	int k = 10;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= 'a') A = (A << 5) + ct - '`', k--;
	else while ((ct = *ci++) >= 'a') A = (A << 5) + ct - '`', k--;
	A <<= k * 5;
	return A;
}

char D[2200010];
char *di = D;
void pakuri_sort(int N, ll A[]) {
	const int b = 9;
	ll tmp[200001];
	rep(k, 6) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	fread_unlocked(cn, 1, cm, stdin);
	int N = 0;
	while ((ct = *ci++) >= '0') N = N * 10 + ct - '0';

	ll S[200000];
	rep(i, N) S[i] = getint();
	pakuri_sort(N, S);
	int kazu = 0;
	int saidai = 1;
	ll mae = 0;
	rep(i, N) {
		if (S[i] != mae) {
			if (saidai < kazu) {
				saidai = kazu;
				di = D;
			}
			if (saidai == kazu) {
				ll s = S[i - 1];
				for (ll m = 45; s; s &= ~(31ll << m), m -= 5) {
					*di++ = (s >> m) + '`';
				}
				*di++ = '\n';
			}
			kazu = 1;
			mae = S[i];
		}
		else kazu++;
	}
	if (saidai < kazu) {
		saidai = kazu;
		di = D;
	}
	if (saidai == kazu) {
		ll s = S[N - 1];
		for (ll m = 45; s; s &= ~(31ll << m), m -= 5) {
			*di++ = (s >> m) + '`';
		}
		*di++ = '\n';
	}
	fwrite(D, 1, di - D, stdout);

	Would you please return 0;
}


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

char C[2200010];
char *ci = C, ct;
char D[2200010];
char *di = D;
void pakuri_sort(int N, ll A[], int ichi[]) {
	const int b = 8;
	ll tmp[200001];
	int tmp2[200001];
	rep(k, 6) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) {
			tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
			tmp2[kazu[A[i] >> k * b & ((1 << b) - 1)]] = ichi[i];
		}
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) {
			A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
			ichi[kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp2[i];
		}
	}
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	fread(C, 1, 2200010, stdin);
	int N = 0;
	while ((ct = *ci++) >= '0') N = N * 10 + ct - '0';

	ll S[200000];
	int ichi[200001];
	rep(i, N) {
		ll s = 0;
		ichi[i] = ci - C;
		int k = 10;
		while ((ct = *ci++) >= 'a') {
			s = s * 27 + ct - '`';
			k--;
		}
		rep(i, k) s *= 27;
		S[i] = s;
	}
	pakuri_sort(N, S, ichi);
	int kazu = 0;
	int saidai = 0;
	ll mae = 0;
	rep(i, N) {
		if (S[i] != mae) {
			if (saidai < kazu) {
				saidai = kazu;
				di = D;
			}
			if (saidai == kazu) {
				char* tmp = C + ichi[i - 1];
				while (*tmp >= 'a')* di++ = *tmp++;
				*di++ = '\n';
			}
			kazu = 1;
			mae = S[i];
		}
		else kazu++;
	}
	if (saidai < kazu) {
		saidai = kazu;
		di = D;
	}
	if (saidai == kazu) {
		char* tmp = C + ichi[N - 1];
		while (*tmp >= 'a')* di++ = *tmp++;
		*di++ = '\n';
	}
	fwrite(D, 1, di - D, stdout);

	Would you please return 0;
}


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

char C[2200010];
char *ci = C, ct;
char D[2200010];
char *di = D;
void pakuri_sort(int N, ll A[], int ichi[]) {
	const int b = 8;
	ll tmp[200001];
	int tmp2[200001];
	rep(k, 6) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) {
			tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
			tmp2[kazu[A[i] >> k * b & ((1 << b) - 1)]] = ichi[i];
		}
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) {
			A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
			ichi[kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp2[i];
		}
	}
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	fread(C, 1, 2200010, stdin);
	int N = 0;
	while ((ct = *ci++) >= '0') N = N * 10 + ct - '0';

	ll S[200000];
	int ichi[200001];
	rep(i, N) {
		ll s = 0;
		ichi[i] = ci - C;
		int k = 10;
		while ((ct = *ci++) >= 'a') {
			s = s * 27 + ct - '`';
			k--;
		}
		rep(i, k) s *= 27;
		S[i] = s;
	}
	pakuri_sort(N, S, ichi);
	int kazu = 0;
	int saidai = 0;
	ll mae = 0;
	rep(i, N) {
		if (S[i] != mae) {
			chmax(saidai, kazu);
			kazu = 1;
			mae = S[i];
		}
		else kazu++;
	}
	chmax(saidai, kazu);
	kazu = 0;
	mae = 0;

	rep(i, N) {
		if (S[i] != mae) {
			if (saidai == kazu) {
				char *tmp = C + ichi[i - 1];
				while (*tmp >= 'a') *di++ = *tmp++;
				*di++ = '\n';
			}
			kazu = 1;
			mae = S[i];
		}
		else kazu++;
	}
	if (saidai == kazu) {
		char* tmp = C + ichi[N - 1];
		while (*tmp >= 'a') *di++ = *tmp++;
		*di++ = '\n';
	}
	fwrite(D, 1, di - D, stdout);

	Would you please return 0;
}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using pint = pair<int, int>;

int main() {
	int N;
	cin >> N;

	vector<int> cnt;
	vector<string> ans;
	for (int i = 0; i < N; ++i) {
		string S;
		cin >> S;
		auto itr = find(ans.begin(), ans.end(), S);
		if (itr == ans.end()) {
			ans.push_back(S);
			cnt.push_back(1);
		}
		else {
			int index = distance(ans.begin(), itr);
			cnt[index]++;
		}
	}

	int maxCnt = 0;
	for (int i = 0; i < cnt.size(); ++i) {
		maxCnt = max(maxCnt, cnt[i]);
	}
	vector<string> finalans;
	for (int i = 0; i < cnt.size(); ++i) {
		if (cnt[i] == maxCnt) {
			finalans.push_back(ans[i]);
		}
	}

	sort(finalans.begin(), finalans.end());

	for (int i = 0; i < finalans.size(); ++i) {
		cout << finalans[i] << endl;
	}

	return 0;
}


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

int main() {
  int64_t n,a,m;
  cin>>n;
  a=0;
  m=0;
  vector<string> vec(n);
  for(int64_t i=0;i<n;i++){
  cin>>vec.at(i);
  }
  sort(vec.begin(), vec.end());
  for(int64_t i=0;i<n-1;i++){
  if(vec.at(i)==vec.at(i+1)){a++;
                            m=max(m,a);}
    else{a=0;}
  }
  a=0;
  for(int64_t i=0;i<n-1;i++){
  if(vec.at(i)==vec.at(i+1)){a++;
                            if(m==a){cout<<vec.at(i)<<endl;};}
    else{a=0;}
  }
 }


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

int main() {
  int64_t n,a,m;
  cin>>n;
  a=0;
  m=0;
  vector<string> vec(n);
  for(int64_t i=0;i<n;i++){
  cin>>vec.at(i);
  }
  sort(vec.begin(), vec.end());
  for(int64_t i=0;i<n-1;i++){
  if(vec.at(i)==vec.at(i+1)){a++;
                            m=max(m,a);}
    else{a=0;}
  }
  for(int64_t i=0;i<n-1;i++){
  if(vec.at(i)==vec.at(i+1)){a++;
                            if(m==a){cout<<vec.at(i)<<endl;};}
    else{a=0;}
  }
 }


// ABC 155-C
// 2020.2.16 bal4u

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

typedef long long ll;

#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)

int in() {   // 非負整数の入力
	int n = 0;
	int c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

ll ins() { // 文字列の入力　スペース以下の文字で入力終了
    ll n = 0;
	int c = gc();
    int w = 10;
	do n = (n << 5) + (c - 'a'+1), --w;
    while ((c = gc()) > ' ');
    return n << 5*w;
}

void outs(ll s) {
    int c, i = 5*9;
    while (c = (s >> i) & 31) pc(c+'a'-1), i -= 5;
    pc('\n');
}

void Usort(ll *a, int n) {
	int i, k;
#define B 8
#define BMSK 255 // (1<<8)-1
	int t1[1 << B], t2[1 << B];

	ll *tmp = malloc(n * sizeof(ll));
	for (k = 0; k < 8; ++k) {  // for 64ビット
		memset(t1, 0, sizeof(t1)), memset(t2, 0, sizeof(t2));
		for (i = 0; i < n; ++i)	t1[(a[i] >> k*B) & BMSK]++;
		for (i = 0; i < BMSK; ++i) t1[i+1] += t1[i];
		i = n; while (i--) tmp[--t1[(a[i] >> k*B) & BMSK]] = a[i];
		k++;
		for (i = 0; i < n; ++i) t2[(tmp[i] >> k*B) & BMSK]++;
		for (i = 0; i < BMSK; ++i) t2[i+1] += t2[i];
		i = n; while (i--) a[--t2[(tmp[i] >> k*B) & BMSK]] = tmp[i];
	}
	free(tmp);
#undef B
}

#define MAX 200005
ll s[MAX]; int n[MAX];

int main()
{
	int i, j, k, N, ma;

    N = in();
	for (i = 0; i < N; ++i) s[i] = ins();
	Usort(s, N);

	j = 0, k = 1, ma = 1;
	for (i = 1; i <= N; ++i) {
		if (s[i] == s[j]) ++k;
		else {
			n[j] = k;
			if (k > ma) ma = k;
			j = i, k = 1;
		}
	}

	for (i = 0; i < N; ++i) {
		if (n[i] == ma) outs(s[i]);
	}
	return 0;
}