jiahuimbzuai/CoQuIR huggingface dataset:
//  [javascript]
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);
}
//  [javascript]
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);
//  [javascript]
'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') );
//  [go]
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)
}
//  [go]
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)
}
//  [go]
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
}
//  [go]
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)
}
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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)
//  [ruby]
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)
//  [ruby]
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
//  [rust]
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();
}
//  [rust]
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);
}
//  [rust]
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);
}
//  [rust]
                eprintln!("{:?}", (i, j, k));
//  [rust]
#![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()
    }
}
//  [rust]
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);
}
//  [swift]
// 🐋💭
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()
//  [typescript]
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"));
//  [typescript]
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"));
//  [typescript]
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);
//  [python]
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)
//  [python]
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)
//  [python]
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)
//  [python]
A,B,C,K=map(int,input().split())

if A+B>=K:
    print(A)
else:
    m=K-(A+B)
    print(A-m)
//  [python]
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)
//  [python]
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)
//  [java]
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);
  }
}
//  [java]

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);
	}
}
//  [java]
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;
	}
}
//  [java]
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);
    }
}
//  [java]
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);
  }
}
//  [java]
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);
		}
	}
}
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [cpp]
// 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 ファイルを選択します
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]

#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;

}
//  [c]
#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;
}
//  [c]
#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)
    }
}
//  [javascript]
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"));
//  [javascript]
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)
        }
    }
}
//  [javascript]
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"));
//  [javascript]
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'))
//  [javascript]
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"))
//  [javascript]
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"))
//  [go]
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)

}
//  [go]
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
}
//  [go]
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]
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
}
//  [go]
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)
}
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
a,b,c,k=gets.split.map(&:to_i)
l=[[1]*a,[0]*b,[-1]*c].flatten
p l[0,k].sum
//  [ruby]
a, b, c, k = gets.split(" ").map &:to_i
if a+b >= k
  puts k - b
else
  puts a - (k - (a+b))
end
//  [ruby]
a, b, c, k = gets.split(" ").map &:to_i
if a+b >= k
  puts k
else
  puts a - (k - (a+b))
end
//  [rust]
// -*- 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);
    }
}
//  [rust]
#![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);
}
//  [rust]
use std::io::*;

fn main() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.trim().split_whitespace();
    let 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);
}
//  [rust]
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};
}
//  [rust]
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};
}
//  [swift]
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))
}
//  [swift]
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))
//  [swift]
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)
//  [swift]
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()
//  [swift]
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()
//  [swift]
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()
//  [typescript]
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"));
//  [typescript]
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"));
//  [typescript]
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);
//  [typescript]
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()));
//  [typescript]
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'));
//  [typescript]
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'));
//  [python]
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)))
//  [python]
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)))