jiahuimbzuai/CoQuIR huggingface dataset:
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
 
int compare_int(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}

int main()
{
//  int  a, b, c, d, X, Y;
//  double  c;
  long long  a, b, c, d, X, Y;
  int N, K;
  //char s[101][101]={};
  char sv[101]={};
  char ss[101]={};
  char t[12]={};
//  char s[10000000000000000001]={};
  char s[2][100001]={};
  int len=0;
  long long A[1000001]={};
//  long long  A[101]={};
  long long  B[101]={};
  long long  C[101]={};
  int i,j,k;
  int flag=0;
  long long tmp=0;
  long long min=10000000000;
  int cnt=0;
  double ans=1000;
  int max=-1;
  
  //  int ans=0;
  int str_len=0;
//  char alp[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
//  scanf("%lld %lld", &a, &b);
  scanf("%d %d", &N, &K);
  for(i=0;i<N;i++){
    scanf("%lld", &A[i]);
//    printf("%lld\n" ,A[i]);
  }
  qsort(A, N, sizeof(long long), compare_int);
  for(i=0;i<N;i++){
    scanf("%lld", &A[i]);
//    printf("%lld\n" ,A[i]);
  }
  for(i=0;i<(N-K+1);i++){
    tmp=A[i+K-1]-A[i];
//    printf("%lld\n" ,tmp);
    if(min>tmp) min=tmp;
//    printf("%lld\n" ,min);
    
  }
  
    printf("%lld\n" ,min);
return 0;
}
//  [javascript]
'use strict'

const main = INPUT => {
  let input = INPUT.split('\n')
  const N = Number(input[0].split(' ')[0])
  const K = Number(input[0].split(' ')[1])
  const h = input
    .slice(1, N + 1)
    .map(n => Number(n))
    .sort((a, b) => a - b)

  let ans = Number.MAX_SAFE_INTEGER
  for (let i = 0; i <= h.length - K; i++) {
    let tmp = h[i + K - 1] - h[i]
    if (tmp < ans) {
      ans = tmp
    }
  }
  console.log(ans)
}

main(require('fs').readFileSync('/dev/stdin', 'utf-8'))
//  [javascript]
'use strict'

const main = (input) => {
    input = input.split('\n')
    const N = parseInt(input[0].split(' ')[0])
    const K = parseInt(input[0].split(' ')[1])
    const h = input.slice(1, N + 1).map(v => parseInt(v)).sort((a, b) => a - b)
    
    let max = Number.MAX_SAFE_INTEGER
    for(let i = 0; i <= h.length - K; i++){
        let diff = h[i + K - 1] - h[i]
        if(diff < max){
            max = diff
        }
    }
    console.log(max)
}

main(require('fs').readFileSync('/dev/stdin', 'utf-8'))
//  [javascript]
'use strict'

function main(input) {
  input = input.split('\n')
  input[0] = input[0].split(' ')
  const n = ~~input[0][0]
  const k = ~~input[0][1]

  const tree = input
    .slice(1, -1)
    .map(v => ~~v)
    .sort((a, b) => a - b)

  // i-1+k本の差を収納
  const diff = Array.apply(null, { length: n - (k - 1) }).fill(-1)
  let min = Number.MAX_SAFE_INTEGER
  let tmp = 0
  for (let i = 0; i < diff.length; i++) {
    // diff.push()
    tmp = tree[i + k - 1] - tree[i]
    min = min > tmp ? tmp : min
  }
  console.log(min)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
// WA
"use strict";
function main(input) {
  const inputs = input.split("\n").filter(x => x !== "");
  let N = Number(inputs[0].split(" ")[0]);
  let K = Number(inputs[0].split(" ")[1]);
  let hs = inputs.slice(1).map(h => Number(h));

  let temp = hs.sort((a, b) => a - b);
  console.error(temp);

  temp = temp.map((h, index, hs) => {
    if (index + K - 1 < hs.length) {
      return hs[index + K - 1] - hs[index];
    }
    return null;
  });
  console.error(temp);

  temp = temp.filter(x => x !== null);

  console.error(temp);

  console.log(Math.min(...temp));
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(input) {
  var N = input[0].split(" ")[0]-0;
  var K = input[0].split(" ")[1]-0;

  var map = {};
  var maxsame = 0;
  var min = max = input[1];
  for(var i=1;i<=N;i++){
    var t = input[i]-0;
    if(!map[t])map[t] = 1;
    else map[t]++;
    maxsame = Math.max(maxsame, map[t]);
    min = Math.min(t, min);
    max = Math.max(t, max);
  }
  if(maxsame>=K) console.log(0);
  else{
    var ans = max-min;
    var keys = Object.keys(map).sort((a,b)=>a-b);
    var nummap = [];
    nummap[-1] = 0;
    nummap[0] = map[keys[0]];
    for(var i=1;i<keys.length;i++){
      nummap[i] = map[keys[i]] + nummap[i-1];
    }
    start:for(var i=0;i<keys.length;i++){
      var first = keys[i];
      var tmpnum = map[first];
      var lastIdx = bsearch(nummap, K+nummap[i-1], i);
      if(lastIdx>=keys.length) continue;
      var last = keys[lastIdx];
      ans = Math.min(last-first, ans);
    }
    console.log(ans);
  }
}

function bsearch(arr, targ, min, max){
  var min=min||0,max=max||arr.length;
  var mid = ~~((min+max)/2);
  while(min<max){
    mid = ~~((min+max)/2);
    if(arr[mid]<targ){
      min = mid+1;
    }else if(arr[mid]>targ){
      max = mid-1;
    }else{
      return mid;
    }
  }
  return max;
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"))
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func rcv() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

func main() {
	sc.Split(bufio.ScanWords)
	n, k := rcv(), rcv()
	h := make([]int, n)
	for i := 0; i < n; i++ {
		h[i] = rcv()
	}
	sort.Ints(h)

	a := int(^uint(0) >> 1)
	for i := k - 1; i < n; i++ {
		if x := h[i] - h[i-k+1]; x < a {
			a = x
		}
	}
	fmt.Println(a)
}
//  [go]
package main

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

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)

	sc := bufio.NewScanner(os.Stdin)
	hs := make([]int, n)
	for i := 0; i < n; i++ {
		sc.Scan()
		hs[i], _ = strconv.Atoi(sc.Text())
	}

	sort.Sort(sort.IntSlice(hs))

	min := math.MaxInt64

	for i := 0; i < n-k+1; i++ {
		h := hs[i+k-1] - hs[i]
		if min > h {
			min = h
		}
	}

	fmt.Println(min)
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	n := nextInt()
	k := nextInt()
	hl := make([]int, n)

	for i := 0; i < n; i++ {
		hl[i] = nextInt()
	}
	sort.Ints(hl)

	dh := make([]int, n-1)
	for i := 0; i < n-1; i++ {
		dh[i] = hl[i+1] - hl[i]
	}
	minrun := 1000000000

	for i := 0; i < n-k+1; i++ {
		runsum := 0
		for j := 0; j < k-1; j++ {
			runsum += dh[i+j]
			//fmt.Println("i,j=", i, j, "runsum += dh[i+j] (", dh[i+j], ")", " new runsum=", runsum)
		}
		//fmt.Println(i, runsum, minrun)
		minrun = min(minrun, runsum)
	}

	fmt.Println(minrun)
}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

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

import (
	"fmt"
	"sort"
)

func main() {
	// Code for C - Christmas Eve
	var N, K int
	fmt.Scanf("%d %d", &N, &K)
	h := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &h[i])
	}

	sort.Sort(sort.IntSlice(h))

	var min int = 10000000000
	var temp int
	for i := 0; i < N-K+1; i++ {
		temp = h[i+K-1] - h[i]
		if min > temp {
			min = temp
		}
	}

	fmt.Println(min)
}
//  [go]
package main

import (
   "fmt"
   "sort"
)

func solution(n, k int, h []int) int {
   sort.Ints(h)
   out := 1 << 31
   for i := 0; i < n-k+1; i++ {
        lo := h[i]
        hi := h[i+k-1]
        out = min(out, hi-lo)
   }
   return out
}

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

func main() {
   var n, k int
   fmt.Scan(&n, &k)
   h := make([]int, n)
   for i := range h {
        fmt.Scan(&h[i])
   }
   fmt.Println(solution(n, k, h))
}
//  [ruby]
N,K,*hs=$<.read.split.map(&:to_i)
hs.sort!

i = 0
j = K-1
min = 10**9
while j < N
  n = hs[j] - hs[i]
  min = n if n < min
  i += 1
  j += 1
end

puts min
//  [ruby]
N, K = STDIN.gets.chomp.split(' ').map(&:to_i)

h = []
STDIN.each_line do |l|
  hn = l.to_i
  h.push(hn)
end

h.sort!

# puts h.join(',')
array = []

d = 0
min = h[K-1] - h[0]
((K-1)..(h.length-1)).each do |i|
  # puts "#{h[i]}-#{h[d]}"
  diff = h[i] - h[d]
  min = diff if diff < min
  d += 1
end

puts min
//  [ruby]
n, k = STDIN.gets.split(/ +/).map(&:to_i)
p = []
n.times do
  p << STDIN.gets.to_i
end
p.sort!


min = p[k-1] - p[0]
i = 1
while i + k -1 < n do
  if min > p[k+i-1] - p[i]
    min = p[k+i-1] - p[i]
  end

  i += 1
end

puts min
//  [ruby]
ary = Array.new
while line = $stdin.gets
ary << line.chomp.split
end
N = ary[0][0].to_i
K = ary[0][1].to_i
ary.delete_at(0)
ary.map!{|item| item[0].to_i }
ary.sort!{|a,b| a <=> b}
kai = ary[K-1]-ary[0]
t = N-K+1
t.times{|num|
if ary[num+K-1]-ary[num] < kai then
kai = ary[num+K-1]-ary[num]
end
}
print kai
//  [ruby]
n, k = gets.strip.split.map(&:to_i)
hs = n.times.map { gets.strip.to_i }.sort { |a, b| b <=> a }

def ckmin(a, b) a < b ? a : b end

res = 10**9 + 1
n.times do |max_pos|
  min_pos = max_pos + k - 1
  break if min_pos >= n
  res = ckmin(res, hs[max_pos] - hs[min_pos])
end
puts res
//  [ruby]
MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; ha=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end
def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n, k = gsmi
h = desc n.times.map{gi}

min = 10**9
l = 0
r = k-1
while r<n do
  diff = h[l] - h[r]
  min = diff if min>diff
  l+=1
  r+=1
end

puts min
//  [rust]
use proconio::{input, fastout};
 
pub const arr: [i32; 29] = [
    0,
    343474715,
    0,
    0,
    0,
    0,
    499999999,
    0,
    0,
    0,
    495113154,
    675365680,
    0,
    0,
    0,
    0,
    0,
    0,
    2,
    19,
    173224800,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    833484826,
];

#[fastout]
fn main(){
    input!{
        ax: [usize; 3],
    }
    
    let m = (ax[0] + ax[1] + ax[2]) % 29;
    println!("{}", arr[m]);
    return;
}
//  [rust]
use proconio::{input};

fn main(){
    const arr: [i32; 29] = [
        0,
        343474715,
        0,
        0,
        0,
        0,
        499999999,
        0,
        0,
        0,
        495113154,
        675365680,
        0,
        0,
        0,
        0,
        0,
        0,
        2,
        19,
        173224800,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        833484826,
    ];
    input!{
        a: usize,
        b: usize,
        c: usize,
    }
    
    let m = (a + b + c) % 29;
    println!("{}", arr[m]);
}
//  [rust]
#[allow(dead_code)]
fn main() {
    let (n, k) = i::u2();
    let mut h = i::uv(n);
    h.sort();
    let mut ans = h[n - 1];
    for i in (k - 1)..n {
        ans = min(ans, h[i] - h[i + 1 - k]);
    }
    println!("{}", ans);
}

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::*;
#[allow(unused_imports)]
use std::num::*;
#[allow(unused_imports)]
use std::str::*;

#[allow(dead_code)]
mod i {
    use super::*;

    pub fn read<T: FromStr>() -> T {
        stdin()
            .bytes()
            .map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>()
            .parse::<T>()
            .ok()
            .unwrap()
    }

    pub fn str() -> String {
        read()
    }

    pub fn s() -> Vec<char> {
        str().chars().collect()
    }

    pub fn i() -> i64 {
        read()
    }

    pub fn u() -> usize {
        read()
    }

    pub fn u2() -> (usize, usize) {
        (read(), read())
    }

    pub fn u3() -> (usize, usize, usize) {
        (read(), read(), read())
    }

    pub fn f() -> f64 {
        read()
    }

    pub fn c() -> char {
        read::<String>().pop().unwrap()
    }

    pub fn iv(n: usize) -> Vec<i64> {
        (0..n).map(|_| i()).collect()
    }

    pub fn iv2(n: usize) -> Vec<(i64, i64)> {
        (0..n).map(|_| iv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn uv(n: usize) -> Vec<usize> {
        (0..n).map(|_| u()).collect()
    }

    pub fn uv2(n: usize) -> Vec<(usize, usize)> {
        (0..n).map(|_| uv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn uv3(n: usize) -> Vec<(usize, usize, usize)> {
        (0..n).map(|_| uv(3)).map(|a| (a[0], a[1], a[2])).collect()
    }

    pub fn fv(n: usize) -> Vec<f64> {
        (0..n).map(|_| f()).collect()
    }

    pub fn cmap(h: usize) -> Vec<Vec<char>> {
        (0..h).map(|_| s()).collect()
    }
}
//  [rust]
#![allow(unused_imports)]

use text_io::*;
use proconio::*;
use std::collections::*;
use std::process::exit;
use std::cmp::*;
use itertools::Itertools;

fn main() {
    let n:usize=read!();
    let k:usize=read!();
    let mut v=Vec::new();
    for _i in 0..n {
        let b:usize=read!();
        v.push(b);
    }
    v.sort();
    let mut ans:usize=100000000000;
    for i in 0..=n-k {
        if v[i+k-1]-v[i]<ans {ans=v[i+k-1]-v[i]}
    }
    println!("{}",ans)
}
//  [rust]
#[allow(dead_code)]
fn main() {
    let (n, k) = i::u2();
    let mut h = i::uv(n);
    h.sort();
    let mut ans = h[n - 1] - h[0];
    for i in 0..n - k + 1 {
        ans = min(ans, h[i + k - 1] - h[i]);
    }
    println!("{}", ans);
}

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::*;
#[allow(unused_imports)]
use std::num::*;
#[allow(unused_imports)]
use std::str::*;

#[allow(dead_code)]
mod i {
    use super::*;

    pub fn read<T: FromStr>() -> T {
        stdin()
            .bytes()
            .map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>()
            .parse::<T>()
            .ok()
            .unwrap()
    }

    pub fn str() -> String {
        read()
    }

    pub fn s() -> Vec<char> {
        str().chars().collect()
    }

    pub fn i() -> i64 {
        read()
    }

    pub fn u() -> usize {
        read()
    }

    pub fn u2() -> (usize, usize) {
        (read(), read())
    }

    pub fn u3() -> (usize, usize, usize) {
        (read(), read(), read())
    }

    pub fn f() -> f64 {
        read()
    }

    pub fn c() -> char {
        read::<String>().pop().unwrap()
    }

    pub fn iv(n: usize) -> Vec<i64> {
        (0..n).map(|_| i()).collect()
    }

    pub fn iv2(n: usize) -> Vec<(i64, i64)> {
        (0..n).map(|_| iv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn uv(n: usize) -> Vec<usize> {
        (0..n).map(|_| u()).collect()
    }

    pub fn uv2(n: usize) -> Vec<(usize, usize)> {
        (0..n).map(|_| uv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn uv3(n: usize) -> Vec<(usize, usize, usize)> {
        (0..n).map(|_| uv(3)).map(|a| (a[0], a[1], a[2])).collect()
    }

    pub fn fv(n: usize) -> Vec<f64> {
        (0..n).map(|_| f()).collect()
    }

    pub fn cmap(h: usize) -> Vec<Vec<char>> {
        (0..h).map(|_| s()).collect()
    }
}
//  [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 gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
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 nk = readInts()
    let (n, k) = (nk[0], nk[1])
    var aryH = [Int]()
    for _ in 0..<n {
        aryH.append(readInt())
    }
    
    aryH.sort(by: >)
    
    var mi = Int.max
    
    var left  = 0
    var right = k - 1
    
    while right < n && mi > 0{
        var m = 0
        m = aryH[left] - aryH[right]
        mi = min(mi, m)
        m -= aryH[left]
        left += 1
        right += 1
    }
    print(mi)
}
main()
//  [swift]
import Foundation

extension String {
    func wordsMap<T>(_ f: (Substring) -> T?) -> [T] {
        return self.split(separator: " ").compactMap(f)
    }
}

private func readWords<T>(_ f: (Substring) -> T?) -> [T] {
    return readLine()!.wordsMap(f)
}

prefix operator *
private prefix func *<T>(a: inout IndexingIterator<[T]>) -> T {
    return a.next()!
}

extension Optional {
    func pleaseAC(){
        print(self!)
    }
}

readLine().map { line -> Any in 
    let nk = line.wordsMap { Int($0) }
    let n = nk[0]
    let k = nk[1]

    let H = (1...n).map { _ in Int(readLine()!)! }.sorted()
    var mini = Int.max
    for i in 0...(n-k) {
        mini = min(mini, H[i+k-1] - H[i])
    }

    return mini
}
.pleaseAC()
//  [swift]
let input = readLine()!.characters.split(" ").map{Int(String($0))!}
let (N, K) = (input[0], input[1])
let h = (0..<N).map{_ in Int(readLine()!)!}.sort()
print((0...N-K).map{h[$0+K-1]-h[$0]}.minElement()!)
//  [swift]
import Foundation

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

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



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

let input = readIntSplit(by: " ")
let (N, K) = (input[0], input[1])
let h = (0..<N).map{_ in readInt()!}.sorted()
var ans = 1_000_000_000
for i in 0...N-K {
    ans = min(h[i+K-1] - h[i], ans)
}
print(ans)
//  [typescript]
function main(input:string) {
    const i = input.split("\n");
    const n =  parseInt(i[0].split(" ")[0]);
    const k = parseInt(i[0].split(" ")[1]);
    let answer = [];
    
    const h = i.slice(1,n+1).map(x => parseInt(x)).sort((a,b) => { return a-b });
        
    for (let j = 0; j < n - k + 1; j++) {
        answer.push(h[k - 1 + j] - h[j]);
    }
    console.log(answer.reduce((a,b)=>Math.min(a,b)));
    
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const [n, k] = stdin
  .split('\n')[0]
  .split(' ')
  .map(Number)

const [, ..._h] = stdin.trim().split('\n')
const h = _h.map(Number)

const s = h.sort((a, b) => a - b)

const getMin = _ => {
  let min = Infinity
  for (let i = 0; i <= s.length - k; i++) {
    const diff = s[i + k - 1] - s[i]
    min = min > diff ? diff : min
  }
  return min
}

console.log(getMin())
//  [typescript]
function main(input) {
  input = input.trim().split("\n");
  const [n, k] = input[0].split(" ").map(n => Number(n));
  const hs = input.slice(1).map(n => Number(n));
  hs.sort((a, b) => a - b);
  let result;
  for (let i = 0; i <= n - k; i++) {
    const dif = hs[i + k - 1] - hs[i];
    if (result === undefined || dif < result) {
      result = dif;
    }
  }
  console.log(result)
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
s=require("fs").readFileSync("/dev/stdin","utf8").split('\n');
[n,k]=s[0].split(' ').map(n=>n|0)
s.shift()
s=s.map(n=>n|0).sort((a,b)=>b-a);
console.log(Math.min(...Array(n-k+1).fill().map((_,i)=>s[i]-s[i+k-1])))
//  [typescript]
s=require("fs").readFileSync("/dev/stdin","utf8").split('\n');
[n,k]=[...s[0].split(' ')].map(n=>n|0)
s.shift()
s=s.map(n=>n|0).sort((a,b)=>b-a);
console.log(Math.min(...Array(n-k+1).fill().map((_,i)=>s[i]-s[i+k-1])))
//  [typescript]
s=require('fs').readFileSync('/dev/stdin','utf8').split('\n');
[n,k]=s[0].split(' ').map(n=>n|0)
s.shift()
s=s.map(n=>n|0).sort((a,b)=>b-a)
console.log(Math.min(...Array(n-k+1).fill().map((_,i)=>s[i]-s[i+k-1])))
//  [python]
# -*- coding: utf-8 -*-

import itertools

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

delete = []

for i in range(n):
    if s[i][0] == "M" or s[i][0] == "A" or s[i][0] == "R" or s[i][0] == "C" or s[i][0] == "H":
        pass
    else:
        delete.append(i)

diff = 0
for i in range(len(delete)):
    del s[delete[i] - diff]
    diff += 1

cand = [0,0,0,0,0]
for i in range(len(s)):
    if s[i][0] == "M":
        cand[0] += 1
    if s[i][0] == "A":
        cand[1] += 1
    if s[i][0] == "R":
        cand[2] += 1
    if s[i][0] == "C":
        cand[3] += 1
    if s[i][0] == "H":
        cand[4] += 1

ans = 0

for i in range(5):
    for j in range(5):
        if i == j:
            break
        for k in range(5):
            if i == k:
                break
            if j == k:
                break
            ans += int(cand[i] * cand[j] * cand[k])

print(ans)
//  [python]
import numpy as np
import scipy as sp
from collections import Counter

N = int(input())
S = []
for _ in range(N):
    a = input()[0]
    if a in {'M','A','R','C','H'}:
        S.append(a)

a = Counter(S)

num = list(a.values())

l = len(num)
s = 0
for i in range(l-2):
    for j in range(i+1,l-1):
        for k in range(j+1,l):
            s += num[i] * num[j] * num[k]
print(s)
//  [python]
# standard library# {{{
import sys
import os
import time
import re
from pydoc import help
import string
import math
import numpy as np
from operator import itemgetter
from collections import Counter
from collections import deque
from collections import defaultdict as dd
import fractions
from heapq import heappop, heappush, heapify
import array
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy as dcopy
import itertools
sys.setrecursionlimit(10**7)
inf = 10**20
gosa = 1.0 / 10**10
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def DP(N, M, first): return [[first] * M for n in range(N)]
def DP3(N, M, L, first): return [[[first] * L for n in range(M)] for _ in range(N)]
# }}}


def solve():
    N = int(input())

    S = [0]*5
    for s in range(N):
        s = input()
        if s[0] == 'M':
            S[0] += 1
        if s[0] == 'A':
            S[1] += 1
        if s[0] == 'R':
            S[2] += 1
        if s[0] == 'C':
            S[3] += 1
        if s[0] == 'H':
            S[4] += 1

    res = 0
    for c in itertools.combinations([0,1,2,3,4], 3):
        i,j,k = c
        res += S[i] * S[j] * S[k]

    print(res)

if __name__ == "__main__":
    solve()
//  [java]

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

public class Main {
    public static void main(final String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final Set<String> march = new HashSet<>(Arrays.asList("MARCH".split("")));
        final Map<String, AtomicLong> countMap = new HashMap<>();
        final int n = scanner.nextInt();
        scanner.nextLine();
        for (int i = 0; i < n; i++) {
            final String prefix = scanner.nextLine().split("")[0];
            if (march.contains(prefix)) {
                countMap.computeIfAbsent(prefix, count -> new AtomicLong())
                        .incrementAndGet();
            }
        }

        final List<AtomicLong> counts = new ArrayList<>(countMap.values());
        long answer = 0;

        for (int i = 0; i < counts.size() - 2; i++) {
            for (int j = i + 1; j < counts.size() - 1; j++) {
                for (int k = j + 1; k < counts.size(); k++) {
                    answer += counts.get(i).get() * counts.get(j).get() * counts.get(k).get();
                }
            }
        }

        System.out.println(answer);
    }
}
//  [java]
import java.util.Scanner;

public class Main{
	public static void main(String[] args){
		
		Scanner sc = new Scanner(System.in);
		final int n = Integer.parseInt(sc.nextLine());
		long cntM=0;
		long cntA=0;
		long cntR=0;
		long cntC=0;
		long cntH=0;
		for(int i=0;i<n;i++){
			String[] name = sc.nextLine().split("");
			if(name[0].equals("M")){
				cntM=cntM+1;
			}else if(name[0].equals("A")){
				cntA=cntA+1;
			}else if(name[0].equals("R")){
				cntR=cntR+1;
			}else if(name[0].equals("C")){
				cntC=cntC+1;
			}else if(name[0].equals("H")){
				cntH=cntH+1;
			}
		}
		long answer=cntM*cntA*cntR+cntM*cntA*cntC+cntM*cntA*cntH+
					cntM*cntR*cntC+cntM*cntR*cntH+
					cntM*cntC*cntH+
					cntA*cntR*cntC+cntA*cntR*cntH+
					cntA*cntC*cntH+
					cntR*cntC*cntH;
		System.out.println(answer);
	}
}
//  [java]
import java.util.*;

public  class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int count = sc.nextInt();
		HashMap<String, Long> map = new HashMap<String, Long>();
		map.put("M", (long) 0);
		map.put("A", (long) 0);
		map.put("R", (long) 0);
		map.put("C", (long) 0);
		map.put("H", (long) 0);
		for (int i = 0; i < count; i++) {
			String initial = sc.next().split("")[0];

			if (initial.equals("M") || initial.equals("A") || initial.equals("R") || initial.equals("C") || initial.equals("H")) {
				long value = map.get(initial);
				map.put(initial, value + 1);
			}
		}

		long result = 0;
		result += map.get("M") * map.get("A") * map.get("R");
		result += map.get("M") * map.get("A") * map.get("C");
		result += map.get("M") * map.get("A") * map.get("H");
		result += map.get("M") * map.get("R") * map.get("C");
		result += map.get("M") * map.get("R") * map.get("H");
		result += map.get("M") * map.get("C") * map.get("H");
		result += map.get("A") * map.get("R") * map.get("C");
		result += map.get("A") * map.get("R") * map.get("H");
		result += map.get("A") * map.get("C") * map.get("H");
		result += map.get("R") * map.get("C") * map.get("H");
		
		System.out.println(result);
	}
}
//  [cpp]
#define _USE_MATH_DEFINES
#include  <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include<math.h>
#include<iomanip>
#include<stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include <queue>
#include<map>
#include <sstream>
#include<set>
#include<stack>

//#include<bits/stdc++.h>


using namespace std;



int main() {
	
	
	int n;
	cin >> n;
	map<string, int>f;
	set<string>s;
	long long int t[8] = {};
	for (int i = 0; i < n; i++) {
		string a;
		cin >> a;
		if (f[a])continue;
		if (a[0] != 'M'&&a[0] != 'A'&&a[0] != 'R'&&a[0] != 'C'&&a[0] != 'H')continue;
		f[a]++;
		s.insert(a);
		if (a[0] == 'M')t[0]++;
		if (a[0] == 'A')t[1]++;
		if (a[0] == 'R')t[2]++;
		if (a[0] == 'C')t[3]++;
		if (a[0] == 'H')t[4]++;

	}
	long long int ans = 0;
	for (int i = 0; i < 5; i++) {
		for (int j = i + 1; j < 5; j++) {
			for (int k = j + 1; k < 5; k++) {
				ans += t[i] * t[j] * t[k];
			}
		}
	}
	cout << ans << endl;

	

	return 0;

}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  long long n;
  cin >>n;
  vector<string>a(n);
  for(long long i=0;i<n;i++)cin>>a[i];
  long long m_kazu=0;
  long long a_kazu=0;
  long long r_kazu=0;
  long long c_kazu=0;
  long long h_kazu=0;
  map<string,long long>mp;
  for(string x:a){
    if(mp.count(x)){
      mp.at(x)++;
    }else{
      mp[x]=1;
      if(x[0]=='M')m_kazu++;
      if(x[0]=='A')a_kazu++;
      if(x[0]=='R')r_kazu++;
      if(x[0]=='C')c_kazu++;
      if(x[0]=='H')h_kazu++;
    }
  }
  long long kazu[5]={m_kazu,a_kazu,r_kazu,c_kazu,h_kazu};
  long long kotae=0;
  for(int a=0;a<3;a++){
    for(int b=a+1;b<4;b++){
      for(int c=b+1;c<5;c++){
        kotae+=kazu[a]*kazu[b]*kazu[c];
      }
    }
  }
  cout<<kotae<<endl;
  return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>

void quick(char s[][13], int left, int right){
  int pl = left, pr = right;
  char x[13];  sprintf(x, "%s", s[(left+right)/2]);
  do{
    while(strcmp(s[pl], x) < 0)  pl++;
    while(strcmp(s[pr], x) > 0)  pr--;
    if(pl <= pr){
      char t[13];  sprintf(t, "%s", s[pl]);
      sprintf(s[pl], "%s", s[pr]);
      sprintf(s[pr], "%s", t);
      pl++, pr--;
    }
  }while(pl <= pr);
  if(pl < right)  quick(s, pl, right);
  if(pr > left)   quick(s, left, pr);
}

int main(){
  int n;  scanf("%d", &n);
  char s[100005][13], march[] = "MARCH";
  for(int i=1; i<=n; i++)  scanf("%s", s[i]);
  quick(s, 1, n);

  long idx = 1, num[5] = {0};
  while(idx <= n){
    int same = 1;
    for(int i=0; i<5; i++)
      if(s[idx][0] == march[i]){
	num[i]++;
	break;
      }
    while(strcmp(s[idx], s[idx+same])==0)  same++;
    idx = idx + same;
  }

  long ans = 0;
  for(int i=0; i<3; i++)
    for(int j=i+1; j<4; j++)
      for(int k=j+1; k<5; k++){
	ans += num[i] * num[j] * num[k];
      }

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

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

signed main(){
	int N, M = 0, A = 0, R = 0, C = 0, H = 0, i, ans = 0;
	scanf("%lld", &N);
	char **S = (char **)malloc(sizeof(char *) * N);
	for(i = 0; i < N; i++){
		S[i] = (char *)malloc(sizeof(char) * 11);
		scanf("%s", S[i]);
		if(S[i][0] == 'M'){
			M++;
		}
		if(S[i][0] == 'A'){
			A++;
		}
		if(S[i][0] == 'R'){
			R++;
		}
		if(S[i][0] == 'C'){
			C++;
		}
		if(S[i][0] == 'H'){
			H++;
		}
	}
	ans += M * A * R;
	ans += M * A * C;
	ans += M * A * H;
	ans += M * R * C;
	ans += M * R * H;
	ans += M * C * H;
	ans += A * R * C;
	ans += A * R * H;
	ans += A * C * H;
	ans += R * C * H;
	printf("%lld\n", ans);
	return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>

int main(){
  int i,j,n;

  scanf("%d",&n);
  char s[12];
  long long m=0,a=0,r=0,c=0,h=0;
  scanf("%c",&s[0]);

  for(i=0;i<n;i++){
    for(j=0;j<=10;j++){
      scanf("%c",&s[j]);
      if(s[j]=='\n') break;
    }
    if(s[0]=='M') m++;
    if(s[0]=='A') a++;
    if(s[0]=='R') r++;
    if(s[0]=='C') c++;
    if(s[0]=='H') h++;
  }
  long long x=0;
  x=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;
  printf("%lld",x);
  return 0;
}
//  [javascript]
function Main(input) {
	input = input.split("\n")
	var namesN = input[0]
	var names = input.slice(1)
	var nameInitialCounts = {}
	for(var name of names) {
		nameInitialCounts[name.charAt(0)]
			= ++nameInitialCounts[name.charAt(0)] || 1;
	}
	var cases = k_combinations(["M", "A", "R", "C", "H"], 3)
	var result = 0
	for(var c of cases) {
		result += (nameInitialCounts[c[0]] || 0) * (nameInitialCounts[c[1]] || 0) * (nameInitialCounts[c[2]] || 0)
	}
	console.log(result)
}


function k_combinations(set, k) {
	var i, j, combs, head, tailcombs;
	
	// There is no way to take e.g. sets of 5 elements from
	// a set of 4.
	if (k > set.length || k <= 0) {
		return [];
	}
	
	// K-sized set has only one K-sized subset.
	if (k == set.length) {
		return [set];
	}
	
	// There is N 1-sized subsets in a N-sized set.
	if (k == 1) {
		combs = [];
		for (i = 0; i < set.length; i++) {
			combs.push([set[i]]);
		}
		return combs;
	}
	
	// Assert {1 < k < set.length}
	
	// Algorithm description:
	// To get k-combinations of a set, we want to join each element
	// with all (k-1)-combinations of the other elements. The set of
	// these k-sized sets would be the desired result. However, as we
	// represent sets with lists, we need to take duplicates into
	// account. To avoid producing duplicates and also unnecessary
	// computing, we use the following approach: each element i
	// divides the list into three: the preceding elements, the
	// current element i, and the subsequent elements. For the first
	// element, the list of preceding elements is empty. For element i,
	// we compute the (k-1)-computations of the subsequent elements,
	// join each with the element i, and store the joined to the set of
	// computed k-combinations. We do not need to take the preceding
	// elements into account, because they have already been the i:th
	// element so they are already computed and stored. When the length
	// of the subsequent list drops below (k-1), we cannot find any
	// (k-1)-combs, hence the upper limit for the iteration:
	combs = [];
	for (i = 0; i < set.length - k + 1; i++) {
		// head is a list that includes only our current element.
		head = set.slice(i, i + 1);
		// We take smaller combinations from the subsequent elements
		tailcombs = k_combinations(set.slice(i + 1), k - 1);
		// For each (k-1)-combination we join it with the current
		// and store it to the set of k-combinations.
		for (j = 0; j < tailcombs.length; j++) {
			combs.push(head.concat(tailcombs[j]));
		}
	}
	return combs;
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
	input = input.split("\n");
	var N = parseInt(input[0]);
	var M = new Array(5).fill(0);
	for(var i = 0; i < N; i++){
		switch(input[i+1][0]){
			case "M":
				M[0]++;
				break;
			case "A":
				M[1]++;
				break;
			case "R":
				M[2]++;
				break;
			case "C":
				M[3]++;
				break;
			case "H":
				M[4]++;
				break;
		}
	}
	var ans = 0;
	for(i = 0; i < 3; i++){
		for(var j = i+1; j < 4; j++){
			for(var k = j+1; k < 5; k++){
				ans += M[i] * M[j] * M[k];
			}
		}
	}
	console.log(ans);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
run (function * (write, gets) {
	var counts = [0, 0, 0, 0, 0];

	var n = parseInt(yield, 10);
	for (var i=0; i<n; ++i) {
		var name = yield;
		switch (name[0]) {
			case 'M': ++counts[0]; break;
			case 'A': ++counts[1]; break;
			case 'R': ++counts[2]; break;
			case 'C': ++counts[3]; break;
			case 'H': ++counts[4]; break;
			default: break;
		}
	}

	var ans = 0;
	for (var i=0; i<5; ++i)
	for (var j=i+1; j<5; ++j)
	for (var k=j+1; k<5; ++k) {
		ans += counts[i] * counts[j] * counts[k];
	}

	write(ans);
});

/**
 * @param {(write: (line: string, end?: string) => void, gets: () => IterableIterator<string|null>) => IterableIterator<any>} main 
 */
function run (main) {
	var istream = process.stdin;
	var ostream = process.stdout;

	/**
	 * @type {[string|null]}
	 */
	var words = [];
	/**
	 * @type {[string]}
	 */
	var lines = [];
	var rest = "";
	var ended = false;
	var INPUT_MODE_LINE = 0;
	var INPUT_MODE_WORD = 1;
	var input_mode = INPUT_MODE_WORD;

	/**
	 * @param {string} line 
	 * @param {string} [end] 
	 */
	function write (line, end) {
		ostream.write(line + (undefined === end ? os.EOL : end));
	}
	function *gets () {
		if (0 < lines.length) {
			return lines.shift();
		} else {
			input_mode = INPUT_MODE_LINE;
			/**
			 * @type {string}
			 */
			var line = yield;
			input_mode = INPUT_MODE_WORD;
			return line;
		}
	}

	var main_itr = main(write, gets);

	/**
	 * @param {string|null} chunk 
	 */
	function get_chunk (chunk) {
		istream.pause();
		if (null === chunk) {
			lines.push(null);
		} else {
			rest += chunk;
			var line_exp = /.*(\r?\n|\r)/g;
			var line_match, lastIndex = 0;
			while (null !== (line_match = line_exp.exec(rest))) {
				lastIndex = line_exp.lastIndex;
				lines.push(line_match[0]);
			}
			rest = rest.substring(lastIndex);
		}
		loop();
	}

	function loop () {
		while (0 < lines.length) {
			switch (input_mode) {
				case INPUT_MODE_LINE:
				{
					words.push(lines.shift());
				}
				break;
				case INPUT_MODE_WORD:
				{
					if (null === lines[0]) {
						words.push(lines.shift());
					} else {
						var word_exp = /[^\s]+/g;
						var line_match;
						if (null !== (line_match = word_exp.exec(lines[0]))) {
							words.push(line_match[0]);
							lines[0] = lines[0].substring(word_exp.lastIndex);
						} else {
							lines.shift();
						}
					}
				}
				break;
			}

			while (0 < words.length) {
				var result = main_itr.next(words.shift());
				if (undefined !== result.value) {
					if ('string' === typeof result.value) {
						write(result.value, "");
					} else {
						write(`${result.value}`, "");
					}
				}
				if (result.done) return;
			}
		}

		ended ? setTimeout(get_chunk, 0, null) : process.stdin.resume();
	}
	istream.on('data', get_chunk);
	istream.on('end', function () {
		ended = true;
		get_chunk(null);
	});

	istream.setEncoding('utf8');
	get_chunk(null);
};

var os = require('os');
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var s string
	t := "MARCH"
	cnt := make([]int, len(t))
	for i := 0; i < n; i++ {
		fmt.Scan(&s)
		for j := 0; j < len(t); j++ {
			if t[j] == s[0] {
				cnt[j]++
				break
			}
		}
	}
	var ans int
	for i := 0; i < len(t); i++ {
		for j := i + 1; j < len(t); j++ {
			for k := j + 1; k < len(t); k++ {
				ans += cnt[i] * cnt[j] * cnt[k]
			}
		}
	}
	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
)

var N int
var S []string

func main() {
	fmt.Scanf("%d", &N)

	S = make([]string, N)

	for i := 0; i < N; i++ {
		fmt.Scanf("%s", &S[i])
	}

	m := make(map[string]int)
	for i := 0; i < N; i++ {
		c := []rune(S[i])[0]
		if c == 'M' || c == 'A' || c == 'R' || c == 'C' || c == 'H' {
			if _, ok := m[S[i]]; ok {
				m[S[i]]++
			} else {
				m[S[i]] = 1
			}
		}
	}

	if len(m) < 3 {
		fmt.Println(0)
		return
	}

	values := make(map[rune]int, 5)
	for k, _ := range m {
		c := []rune(k)[0]
		if _, ok := values[c]; ok {
			values[c]++
		} else {
			values[c] = 1
		}
	}

	ans := 0
	march := []rune{'M', 'A', 'R', 'C', 'H'}
	for i := 0; i < len(march); i++ {
		for j := i + 1; j < len(march); j++ {
			for k := j + 1; k < len(march); k++ {
				ans += values[march[i]] * values[march[j]] * values[march[k]]
			}
		}
	}

	fmt.Println(ans)
}

func fact(n int) int {
	if n == 0 {
		return 1
	}
	return n * fact(n-1)
}
//  [go]
package main

import "fmt"

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

	march := make(map[string]int)
	for i := 0; i < n; i++ {
		var tmp string
		fmt.Scan(&tmp)

		if tmp[0] == 'M' || tmp[0] == 'A' || tmp[0] == 'R' || tmp[0] == 'C' || tmp[0] == 'H' {
			march[string(tmp[0])]++
		}
	}

	var ans int
	ans += march["M"] * march["A"] * march["R"]
	ans += march["M"] * march["A"] * march["C"]
	ans += march["M"] * march["A"] * march["H"]
	ans += march["M"] * march["R"] * march["C"]
	ans += march["M"] * march["R"] * march["H"]
	ans += march["M"] * march["C"] * march["H"]
	ans += march["A"] * march["R"] * march["C"]
	ans += march["A"] * march["R"] * march["H"]
	ans += march["A"] * march["C"] * march["H"]
	ans += march["R"] * march["C"] * march["H"]

	fmt.Println(ans)
}
//  [ruby]
n = gets.to_i

M = []
A = []
R = []
C = []
H = []

pys = []

i = 0

n.times do
	pys << gets.chomp.split("").map(&:to_s)
end

pys.uniq!

while i < n

    if pys[i][0] == 'M'
	  M << pys[i].join
	end

	if pys[i][0] == 'A'
	  A << pys[i].join
	end

	if pys[i][0] == 'R'
	  R << pys[i].join
	end

	if pys[i][0] == 'C'
	  C << pys[i].join
	end

	if pys[i][0] == 'H'
	  H << pys[i].join
	end
	i += 1
end

puts (M.length*A.length*R.length)+(M.length*A.length*C.length)+(M.length*A.length*H.length)+(M.length*R.length*C.length)+(M.length*R.length*H.length)+(M.length*C.length*H.length)+(A.length*R.length*C.length)+(A.length*R.length*H.length)+(A.length*C.length*H.length)+(H.length*C.length*R.length)
//  [ruby]
nu = gets.to_i
na = Array.new(nu).map{Array.new(1, "+")}
for i in 0..nu - 1
  na[i] = gets.chomp.split("")
end
march = [0, 0, 0, 0, 0]
for i in 0..nu - 1
  if na[i][0] == "M"
    march[0] += 1
  elsif na[i][0] == "A"
    march[1] += 1
  elsif na[i][0] == "R"
    march[2] += 1
  elsif na[i][0] == "C"
    march[3] += 1
  elsif na[i][0] == "H"
    march[4] += 1
  end
end

ans = 0
count = [0, 1, 2]

while count[0] <= 2
  while count[1] <= 3
    while count[2] <= 4
      ans += march[count[0]]*march[count[1]]*march[count[2]]
      count[2] += 1
    end
    count[2] = 2 + count[1]
    count[1] += 1
  end
  count[0] += 1
  count[1] = 1 + count[0]
  count[2] = 2 + count[0]
end

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

n = gif
s =  Hash.new
rep n do
t = gc
s[t.first] ||= 0
s[t.first]+=1
end

num = []
alp = ['M','A','R','C','H']
s.each do |k,v|
  num << v if alp.include? k
end
ans = 0
num.combination(3).each do |i|
  ans += i.inject(:*)
end
puts ans
//  [rust]
use std::io::*;
use std::str::FromStr;

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

use std::collections::HashMap;
fn main() {
    let n = read::<usize>();
    let mut h = HashMap::new();
    h.insert('M', 0);
    h.insert('A', 1);
    h.insert('R', 2);
    h.insert('C', 3);
    h.insert('H', 4);
    let mut s = vec![vec![]; n];
    let mut ss = vec![0; 5];
    for i in 0..n {
        s[i] = read::<String>().chars().collect::<Vec<char>>();
        if h.get(&s[i][0]) != None {
            ss[h[&s[i][0]]] += 1;
        }
    }
    let mut ans:i64 = 0;
    for i in 0..3 {
        for j in i+1..4 {
            for k in j+1..5 {
                ans += ss[i] * ss[j] * ss[k];
            }
        }
    }
    println!("{}", ans);
}
//  [rust]
use std::io::*;
use std::str::FromStr;

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

fn main(){
    let n: usize = read();
    let mut c: Vec<u64> = (0..5).map(|_| 0).collect();

    for _ in 0..n {
        let tmp: Vec<char> = read::<String>().chars().collect();
        let s = tmp[0];
        match s{
            'M' => { c[0] += 1; },
            'A' => { c[1] += 1; },
            'R' => { c[2] += 1; },
            'C' => { c[3] += 1; },
            'H' => { c[4] += 1; },
            _ => (),
        }
    }

    let mut ret = 0;
    for i in 0..5 {
        for j in 0..i {
            for k in 0..j {
                ret += c[i] * c[j] * c[k];
            }
        }
    }
    println!("{}", ret);
}
//  [rust]
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}
 
fn main(){
    let n: usize = read();
    let mut c: Vec<u64> = (0..5).map(|_| 0).collect();
 
    for _ in 0..n {
        let tmp: Vec<char> = read::<String>().chars().collect();
        let s = tmp[0];
        match s{
            'M' => { c[0] += 1; },
            'A' => { c[1] += 1; },
            'R' => { c[2] += 1; },
            'C' => { c[3] += 1; },
            'H' => { c[4] += 1; },
            _ => (),
        }
    }
 
    let mut ret = 0;
    for i in 0..5 {
        for j in 0..i {
            for k in 0..j {
                ret += c[i] * c[j] * c[k];
            }
        }
    }
    println!("{}", ret);
}