jiahuimbzuai/CoQuIR huggingface dataset:
//  [typescript]
import { count } from 'console';

process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', (chunk) => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const [n, m, q] = inputs[0].split(' ').map(Number);
  const list = setArgList(inputs, q);
  // 全パターンの数列Aを取得
  const numListA = initNumList(1, 0, n, m, []);
  let max = 0;

  for (let i = 0; i < numListA.length; i++) {
    let numList = numListA[i];
    let totalScore = 0;
    for (let j = 0; j < q; j++) {
      if (numList[list[j][1] - 1] - numList[list[j][0] - 1] == list[j][2]) {
        totalScore += list[j][3];
      }
    }

    max = Math.max(max, totalScore);
  }

  console.log(max);
}

// 2行目以降の引数を取得
function setArgList(inputs: string[], q: number): number[][] {
  let list: number[][] = [];

  for (let i = 1; i <= q; i++) {
    list.push(inputs[i].split(' ').map(Number));
  }

  return list;
}

// 数列Aの初期化
function initNumList(j: number, k: number, n: number, m: number, list: number[]): number[][] {
  let numList: number[][] = [];

  if (k === n) {
    return [list];
  }

  for (let i = j; i <= m; i++) {
    numList = numList.concat(initNumList(i, k + 1, n, m, list.concat([i])));
  }
  return numList;
}
//  [typescript]
export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [n, m, q]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const l = Main.makeList(1, 0, n, m, []);
    const len = l.length;
    let result = [];
    for (let j = 0; j < len; j++) {
      result.push(0);
    }
    for (let i = 0; i < q; i++) {
      const x: number[] = tmp.shift().split(" ").map(int => parseInt(int));
      for (let j = 0; j < len; j++) {
        const list = l[j];
        if (list[x[1] - 1] - list[x[0] - 1] == x[2]) {
          result[j] = result[j] + x[3];
        }
      }
    }
    return `${Math.max.apply(null, result)}`;
  }

  static makeList(i, k, n, m, list) {
    if (k == n) {
      return [list];
    }
    let result = [];
    for (let j = i; j <= m; j++) {
      result = result.concat(Main.makeList(j, k + 1, n, m, list.concat([j])));
    }
    return result;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [python]
import numpy as np

N, K = map(int, input().split())
h = np.array(list(map(int, input().split())))

dp = np.zeros(N, dtype=int)
for i in range(1, N):
    dp[i] = min(dp[max(0,i-K):i]+abs(h[max(0,i-K):i]-h[i]))

print(dp[-1])
//  [python]
def main():
    N, K = map(int, input().split())
    h = [int(x) for x in input().split()]

    dp = [-1]*N
    dp[0] = 0
    dp[1] = abs(h[1]-h[0])

    for i in range(2,N):
        dp[i] = min(abs(h[i]-h[j]) + dp[j] for j in range(max(0,i-K),i))
    print(dp[N-1])

if __name__ == "__main__":
    main()
//  [python]
# numpy version

import numpy as np

n, k = map(int, input().split())
h = np.array(list(map(int, input().split())))

dp = np.zeros(n)

for i in range(1,n): 
    j = max(0, i-k)
    dp[i] = np.min(dp[j:i] + np.abs(h[i] - h[j:i]))

print(int(dp[-1]))
//  [java]
// package com.patra.cp.atcoder.practice.dp;

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

public class Main {
    private static int solve(int[] arr, int[] dp, int currPos, int K) {
        if(currPos >= arr.length) {
            return Integer.MAX_VALUE;
        }
        if(dp[currPos] != -1) {
            return dp[currPos];
        }
        int count = 0;
        int res = Integer.MAX_VALUE;
        if(currPos == arr.length - 1) {
            res = 0;
        }
        for(int i = currPos + 1; i < arr.length; i++) {
            if(count == K) {
                break;
            }
            count++;
            int temp = solve(arr, dp, i, K);
            res = Math.min(res, temp + Math.abs(arr[currPos] - arr[i]));
        }
        dp[currPos] = res;
        return dp[currPos];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String[] splits = line.split(" ");
        int N = Integer.parseInt(splits[0]);
        int K = Integer.parseInt(splits[1]);
        int[] arr = new int[N];
        int[] dp = new int[N];
        Arrays.fill(dp, -1);
        line = sc.nextLine();
        splits = line.split(" ");
        for(int i=0; i<N; i++) {
            arr[i] = Integer.parseInt(splits[i]);
        }
        System.out.println(solve(arr, dp, 0, K));
    }
}
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public int minJumps(int[] heights, int K) {
        int n = heights.length;
        int[] memo = new int[n];
        Arrays.fill(memo, -1);
        return dfs(heights, 0, K, memo);
    }
    private int dfs(int[] heights, int currPosition, int K, int[] memo) {
        int n = heights.length;
        if (currPosition >= n - 1) {
            return 0;
        }
        if (memo[currPosition] != -1) {
            return memo[currPosition];
        }
        int result = Integer.MAX_VALUE;
        for (int i = 1; i <= K; i++) {
            if (currPosition + i >= n) {
                break;
            }
            result = Math.min(result, Math.abs(heights[currPosition] - heights[currPosition + i]) + dfs(heights, currPosition + i, K, memo));
        }
        return memo[currPosition] = result;
    }


    public static void main(String[] args)  {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            String[] strs = br.readLine().split(" ");
            int n = Integer.parseInt(strs[0]);
            int K = Integer.parseInt(strs[1]);
            String heightsStr = br.readLine();
            String[] split = heightsStr.split(" ");
          	int[] heights = new int[n];
            for (int i = 0; i < n; i++) {
              	heights[i] = Integer.parseInt(split[i]);
            }
          	Main app = new Main();
            int result = app.minJumps(heights, K);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//  [cpp]
#include<bits/stdc++.h>

using namespace std;

#define ll long long
#define lop(b) for(int i = 1; i <= b; i++)

const int N = 1e5+4, K = 1e2+2;
const ll inf = 1e16;
int h[N], n, k;
ll dp[K][N];

ll f(int j, int t)
{
    if(j > n)
        return inf;

    if(dp[t][j] != -1)
        return dp[t][j];

    ll ans = inf;

    lop(k) ans = min(ans, f(j + i, i));

    if(ans == inf)
        ans = 0;

    return dp[t][j] = abs(h[j] - h[j - t]) + ans;
}

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

    cin >> n >> k;

    lop(n)
        cin >> h[i];

    memset(dp, -1, sizeof dp);

    cout << f(1, 0) << '\n';

    return 0;
}
//  [cpp]
#include <iostream>
#include <vector>
#include <cmath>
#include <set>
#include <queue>
#include <map>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
#include <algorithm>
#include <limits.h>
#include <bits/stdc++.h>
#define fw(x) freopen("x.txt","w",stdout)
#define For(i,a,b,c) for(int i = a;i < b;i+=c)
#define REP(i,n) for(int i = 0;i < n;++i)
#define REP1(i,n) for(int i = 1; i<=n;i++)
#define mem(a,s) memset(a,s,sizeof a)
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL)
#define pf printf
#define sc scanf
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(v) v.begin(),v.end()
#define vii vector<int>
#define vll vector<ll>
#define vss vector<string>
#define debug(x)  cout<<#x"="<<(x)<<endl
#define pb push_back


using namespace std;


// moves

//int dx[]= {0,0,1,-1};/*4 side move*/
//int dy[]= {-1,1,0,0};/*4 side move*/
//int dx[]= {1,1,0,-1,-1,-1,0,1};/*8 side move*/
//int dy[]= {0,1,1,1,0,-1,-1,-1};/*8 side move*/
//int dx[]={1,1,2,2,-1,-1,-2,-2};/*knight move*/
//int dy[]={2,-2,1,-1,2,-2,1,-1};/*knight move*/


//big_mod

//ll bigmod(ll a,ll b,ll m)
//{if(b == 0) return 1%m;ll x = bigmod(a,b/2,m);x = (x * x) % m;if(b % 2 == 1) x = (x * a)% m;return x;}
//ll BigMod(ll B,ll P,ll M){ ll R=1%M; while(P>0) {if(P%2==1){R=(R*B)%M;}P/=2;B=(B*B)%M;} return R;} /// (B^P)%M

//ll getBit(ll num, int idx) {return ((num >> idx) & 1ll) == 1ll;}
//ll setBit1(ll num, int idx) {return num or (1ll<<idx);}
//ll setBit0(ll num, int idx) {return num & ~(1ll<<idx);}
//ll flipBit(ll num, int idx) {return num ^ (1ll<<idx);}

const int mod = 1000000007;
ll qpow(ll n,ll k)
{
    ll ans=1;
    assert(k>=0);
    n%=mod;
    while(k>0)
    {
        if(k&1)
            ans=(ans*n)%mod;
        n=(n*n)%mod;
        k>>=1;
    }
    return ans%mod;
}
int ar[100009];
int cost[100009];
void run(int i, int n, int k){
    if(i>=n) return;
    if(cost[i]== -1 ){
        REP1(j, k){
            if(i+j < n){
                run(i+j, n, k);
            }
            else break;
        }
    }
    int mn = INT_MAX;
    REP1(j, k){
        if(i+j <= n){
            int c1 = cost[i+j] + abs(ar[i]-ar[i+j]);
            if(mn>c1) mn=c1;
        }
        else break;
    }
    cost[i] = mn;
}
int main()
{
    fast;
    int n, k, v;
    cin>>n>>k;
    REP1(i, n){
        cin>>v;
        cost[i]= -1;
        ar[i] = v;
    }
    cost[n]=0;
    run(1, n, k);
    cout<<cost[1]<<'\n';
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define endl "\n"
#define mod 1000000007
#define fastio std::ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define deb(x) cout<<#x<<" "<<x<<endl;
const ll INF = 1e9 + 7;

int main(){
  fastio;
  ll n,k;
  cin>>n>>k;
  vector<ll> h(n+1);
  for (ll i = 1; i <= n; i++) {
    cin>>h[i];
    //deb(i);
  }
  vector<ll> jump(k+1,0);
  for (ll i = 1; i <= k; i++) {
    jump[i] = i;
  }

  vector<ll> dp(n+1,INF);

  dp[1] = 0;

  for (ll i = 1; i <= k; i++) {
    for (ll j = 1; j <= n; j++) {
      for (ll type = 1; type <= i; type++){
      ll diff = INF;
      if(j - jump[type] > 0) diff = dp[j-jump[type]] + abs(h[j] - h[j - jump[type]]);
      dp[j] = min(dp[j] , diff );
    }
  }
    // std::cout << '\n';
    // deb(jump[i]);
    // for (ll i = 0; i <= n; i++) {
    //   std::cout << dp[i] << ' ';
    // }
  }

  // for (ll i = 0; i <= n; i++) {
  //   std::cout << dp[i] << ' ';
  // }

  std::cout<< dp[n] << '\n';
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int abs(int a){
  if(a>=0) return a;
  else return -a;
}

int compare(const void* x, const void* y){
  if(*(int*)x<*(int*)y) return -1;
  else if(*(int*)x>*(int*)y) return 1;
  return 0;
}

int main(){
  int n,k;
  scanf("%d%d",&n,&k);
  int *h;
  h=(int*)malloc((n+1)*sizeof(int));
  for(int i=1;i<=n;i++) scanf("%d",&h[i]);

  int *dp;
  dp=(int*)malloc((n+1)*sizeof(int));
  dp[1]=0;

  if(k>=n-1){
    printf("%d",abs(h[n]-h[1]));
    return 0;
  }

  for(int i=2;i<=1+k;i++){
    dp[i]=abs(h[i]-h[1]);
  }
  for(int i=2+k;i<=n;i++){
    int *temp;
    temp=(int*)malloc(k*sizeof(int));
    for(int j=0;j<k;j++){
      temp[j]=dp[i-j-1]+abs(h[i]-h[i-j-1]);
    }
    qsort(temp,k,sizeof(int),compare);
    dp[i]=temp[0];
  }
  printf("%d\n",dp[n]);
  return 0;
}
//  [c]
#include<stdio.h>
#include<math.h>
#include<stdlib.h>

int compare(const void *a,const void *b){
	return *(int*)a-*(int*)b;
}

int minsiumai(int n, int a[n]){
    qsort(a,n,sizeof(a[n]),compare);
    return a[0];
}


int main(void){
    int n,i,k,j;
    scanf("%d",&n);
    scanf("%d",&k);

    int h[n],c[n],a[k];

    for(i=0;i<n;i++){
        scanf("%d",&h[i+1]);    
    }

/* kまでの最小　c[k] kの高さh[k]   */

    for(i=0;i<n+1;i++){
        c[i]=0;
    }

    for(i=0;i<n;i++){
        // if(i==0){
        //     c[i+2]=fabs(h[2]-h[1]);
        //     if(n==2){
        //         break;
        //     }else{
        //         continue;
        //     }
        // }


        if(i<k-1){
            for(j=0;j<i+1;j++){
                a[j] = c[ 1+j ] + fabs( h[ i+2 ] - h[ 1+j ] );
            }

            c[i+2] = minsiumai(i+1,a);
            // printf("%d\n",c[i+2]);
            continue;
        }







        if(i==n-1) break;
        
        for(j=0;j<k;j++){
            a[j] = c[i+j-k+2] + fabs( h[i+2] - h[i-k+2+j] );
        }





        c[i+2] = minsiumai(k,a);

        // printf("%d\n",c[i+2]);

        // a[0] = c[i + 1] + fabs(h[i + 2] - h[i + 1]) ;
        // a[1] =  c[i] + fabs(h[i + 2] - h[i]);



        // c[ i + k ] = minsiumai(k,a);

        // if(c[i + 1] + fabs(h[i + 2] - h[i + 1]) > c[i] + fabs(h[i + 2] - h[i])){
        //     c[i+2] =  c[i] + fabs(h[i + 2] - h[i]);
            
        // }else{
        //     c[i+2] = c[i+1] + fabs(h[i + 2] - h[i + 1]);
        // }

    }
    // for(i=0;i<n+1;i++){
    //     printf("%d\n",c[i]);
    // }
    printf("%d\n",c[n]);
    return 0;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include<stdbool.h>
#include<math.h>
#include<time.h>
#define ll long long
#define min(a,b) ((a)>(b)?(b):(a))
#define max(a,b) ((a)>(b)?(a):(b))

int n, k, h[111111], x[111111][111];

int nyan(int i, int j){
    if(x[i][j] >= 0)return x[i][j];
    if(j == 0 && i < n){
        return x[i][j] = abs(h[i-k] - h[i]) + nyan(i+1,k-1);
    }
    if(i >= n-1){
        return x[i][j] = abs(h[i-(k-j)] - h[n-1]);
    }
    return x[i][j] = min(nyan(i+1, j-1), abs(h[i-(k-j)] - h[i]) + nyan(i+1, k-1));
}

int main(){
    scanf("%d%d", &n, &k);
    for(int i = 0; i < n; i++){
        scanf("%d", &h[i]);
    }
    for(int i=0; i<111111; i++){
        for(int j=0; j<111; j++){
            x[i][j] = -1;
        }
    }
    printf("%d\n", nyan(0, k));
    return 0;
}
//  [javascript]
function main(input){
  var k = parseInt(input[0].split(' ')[1]);
  var line1 = input[1].split(' ');
  var arr = Array(line1.length);
  arr[0] = 0;
  for (var i=1; i<line1.length; i++){
    var min = null;
    for (var j=0; j<k; j++){
      if (i-j-1 >= 0) {
        var newMin = Math.abs(parseInt(line1[i-j-1]) - parseInt(line1[i])) + arr[i-j-1];
        if (min == null || newMin < min) min = newMin;
      }
    }
    arr[i] = min;
  }

  console.log(arr[line1.length-1]);
}


var input = '';

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
  input += chunk;
});
process.stdin.on('end', function() {
  input = input.split('\n');
  main(input);
});
//  [javascript]
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));

console.log(main());
function main(){
  var n = o.a();
  var k = o.a();
  var h = o.l();
  if(n <= k + 1)return Math.abs(h[n-1] - h[0]);
  var dp = [0];
  for(var i = 1; i <= k; i++)dp[i] = Math.abs(h[i] - h[0]);
  for(i = k+1; i < n; i++){
    var t = 9e99;
    for(var j = 1; j <= k; j++){
      var t2 = dp[i-j] + Math.abs(h[i] - h[i-j]);
      if(t > t2)t = t2;
    }
    dp[i] = t;
  }
  return dp[n-1];
}
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const K = parseInt(arg[0].split(" ")[1]);
    
    const steps = arg[1].split(" ").map(n=>parseInt(n));
    
    const dp = [...Array(N)].fill(Infinity);
    
    dp[0] = 0;
    
    for(let i=1; i<N; i++) {
        let temp = Infinity;
        
        for(let j=1; j<=K; j++) {
            if(i-j >= 0) {
                temp = Math.min(temp, dp[i-j] + Math.abs(steps[i] - steps[i-j]));
            }
        }
        
        dp[i] = temp;
    }
    
    console.log(dp[N-1]);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func oneInt() int {
	var a int
	fmt.Scan(&a)
	return a
}

func oneInt64() int64 {
	var a int64
	fmt.Scan(&a)
	return a
}

func oneStr() string {
	var a string
	fmt.Scan(&a)
	return a
}

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

func scanNums() (nums []int) {
	s := nextLine()
	numStr := strings.Split(s, " ")

	for _, n := range numStr {
		i, _ := strconv.Atoi(n)
		nums = append(nums, i)
	}
	return nums
}

func scanStrings() (strs []string) {
	s := nextLine()
	list := strings.Split(s, " ")
	strs = append(strs, list...)
	return strs
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func sortAsc(a []int) []int {
	sort.Ints(a)
	return a
}

func sortDesc(a []int) []int {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	return a
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	if a == 0 && b == 0 {
		return 0
	}
	return a * b / gcd(a, b)
}

func permutation(n int, k int) int {
	v := 1
	if 0 < k && k <= n {
		for i := 0; i < k; i++ {
			v *= (n - i)
		}
	} else if k > n {
		v = 0
	}
	return v
}

func factorial(n int) int {
	return permutation(n, n-1)
}

func combination(n int, k int) int {
	return permutation(n, k) / factorial(k)
}

func homogeneous(n int, k int) int {
	return combination(n+k-1, k)
}

var memo []int
var hights []int
var k int

func main() {
	N := oneInt()
	k = oneInt()

	for index := 0; index < N; index++ {
		hights = append(hights, oneInt())
		memo = append(memo, math.MaxInt64)
	}

	fmt.Print(rec(N - 1))
}

func rec(i int) int {
	if memo[i] < math.MaxInt64 {
		return memo[i]
	}

	if i == 0 {
		memo[i] = 0
		return 0
	}

	var scores []int
	for index := 1; index <= k; index++ {
		if i >= index {
			scores = append(scores, abs(hights[i]-hights[i-index])+rec(i-index))
		}
	}

	memo[i] = min(scores...)
	return memo[i]
}
//  [go]
package main

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

type IntMap map[ // IntMap は、map[Int][Int]に便利メソッドを追加します.
int]int

func lib_AbsInt(value int) int {
	return int(math.Abs(float64(value)))
}
func lib_MinInt(values ...int) (min int, err error) {
	if len(values) == 0 {
		return 0, errors.New("empty slice is given")
	}
	min = values[0]
	for _, value := range values {
		if min > value {
			min = value
		}
	}
	return
}
func lib_NewIntMap() IntMap {
	return map[int]int{}
}
func (m IntMap) ChMin(key, value int, values ...int) (replaced bool, valueAlreadyExist bool) {
	min, _ := lib_MinInt(append(values, value)...)
	if v, ok := m[key]; ok {
		if v > min {
			m[key] = min
			return true, true
		} else {
			return false, true
		}
	}
	m[key] = min
	return true, false
}
func main() {
	scanner := bufio.NewScanner(os.Stdin)
	const initialBufSize = 4096
	const maxBufSize = 1000000
	scanner.Buffer(make([]byte, initialBufSize), maxBufSize)
	scanner.Split(bufio.ScanWords)
	var N int64
	scanner.Scan()
	N, _ = strconv.ParseInt(scanner.Text(), 10, 64)
	var K int64
	scanner.Scan()
	K, _ = strconv.ParseInt(scanner.Text(), 10, 64)
	h := make([]int, N)
	for i := int64(0); i < N; i++ {
		scanner.Scan()
		t, _ := strconv.ParseInt(scanner.Text(), 10, 64)
		h[i] = int(t)
	}
	fmt.Println(solve(int(N), int(K), h))
}
func solve(N int, K int, h []int) int {
	m := lib_NewIntMap()
	m[0] = 0
	for i := 0; i < N; i++ {
		for j := 1; j <= K; j++ {
			if i+j < len(h) {
				m.ChMin(i+j, m[i]+lib_AbsInt(h[i+j]-h[i]))
			}
		}
	}
	return m[N-1]
}
//  [go]
package main

import (
"fmt"
"math"
)

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func main(){
	var n,k,num int
	var ashiba []int
	var DP []int

	//case when k == 2
	fmt.Scan(&n,&k)
	for i:=0;i<n;i++{
		fmt.Scan(&num)
		ashiba = append(ashiba,num)
		DP = append(DP,1000000000)
	}
	DP[0] = 0
	for i:=1;i<n;i++{
		for j:=0;j<min(i,k)+1;j++{
			DP[i] = min(DP[i-j] + abs(ashiba[i] - ashiba[i-j]),DP[i])
		}
	}
	fmt.Println(DP[n-1])
	//DP[3] = DP[3-2]+(3-(3-2))_move,DP[3-1]+(3-(3-1))_move
	// ...
	//DP[x] = DP[x-k]+abs(DP[x]-DP[x-k]) ... DP[x-3]+abs(DP[x]-DP[(x-3)-k]),DP[x-2]+abs(DP[x]-DP[(x-2)-k]),DP[x-1]+abs(DP[x]-DP[(x-1)-k])
}
//  [ruby]
n, k= gets.split(' ').map(&:to_i)
h = gets.split(' ').map(&:to_i)

dp = Array.new(h.length,1000000000)
dp[0] = 0
for i in 1..h.length-1
	j = 0
	while i-j-1>=0 && j < k do
		dp[i] = dp[i-j-1]+(h[i-j-1]-h[i]).abs if dp[i] > dp[i-j-1]+(h[i-j-1]-h[i]).abs
		
	j += 1
	end
end

puts dp[h.length-1]
//  [ruby]
n, k = STDIN.gets.split.map(&:to_i)
h = STDIN.gets.split.map(&:to_i)

tiles = Array.new(n)
tiles[0] = 0

for i in 1...n do
  tiles[i] = tiles[i - 1] + (h[i] - h[i - 1]).abs

  for j in 1..k do
    break if i - j < 0

    if tiles[i] > tiles[i - j] + (h[i] - h[i - j]).abs
      tiles[i] = tiles[i - j] + (h[i] - h[i - j]).abs
    end
  end
end

puts tiles[-1]
//  [ruby]
N, K, *H = [*gets.split, *gets.split].map(&:to_i)

dp = [0]
1.step(N-1) do |i|
  dp[i] = Float::INFINITY
  1.step(K) do |j|
    break if i-j < 0
    cost = dp[i-j] + (H[i]-H[i-j]).abs
    dp[i] = cost if cost < dp[i]
  end
end
puts dp.last
//  [rust]
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

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

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

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

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

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

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

#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Rev<T>(pub T);

impl<T: PartialOrd> PartialOrd for Rev<T> {
    fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}
impl<T: Ord> Ord for Rev<T> {
    fn cmp(&self, other: &Rev<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}

struct DepthFirstSearch {
    n: usize,
    k: usize,
    h: Vec<i32>,
    memo: Vec<i32>,
}
impl DepthFirstSearch {
    fn rec(&mut self, k: usize) -> i32 {
        if self.memo[k] != -1 {
            return self.memo[k];
        }

        let res = if k + 1 == self.n {
            0
        } else {
            let mut vals: Vec<i32> = Vec::new();
            for i in 1..(self.k + 1) {
                if k + i == self.n {
                    break;
                }
                let val = self.rec(k + i) + (self.h[k + i] - self.h[k]).abs();
                vals.push(val);
            }
            vals.sort_by_key(|&x| x);
            vals[0]
        };
        self.memo[k] = res;
        res
    }
}

fn main() {
    input! {
        n: usize,
        k: usize,
        h: [i32; n],
    }
    let memo: Vec<i32> = vec![-1; n];
    let mut dfs = DepthFirstSearch{ n: n, k:k, h: h, memo: memo };
    println!("{}", dfs.rec(0));
}
//  [typescript]
const lines: string[] = [];
const reader = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});
reader.on("line", function (line: string) {
  lines.push(line);
});

reader.on("close", function () {
  const rule = lines.shift().split(" ").map(Number);
  const data: number[] = lines
    .shift()
    .split(" ")
    .map((int) => parseInt(int));

  const dp = data.map(() => Infinity);
  dp[0] = 0;

  for (let i = 1; i < rule[0]; i++) {
    for (let j = i - rule[1]; j < i; j++) {
      if (j >= 0) {
        dp[i] = Math.min(dp[i], dp[j] + abs(data[j] - data[i]));
      }
    }
  }

  console.log(dp[rule[0] - 1]);
});

function abs(val: number) {
  return val < 0 ? -val : val;
}
//  [typescript]
// https://atcoder.jp/contests/dp/tasks/dp_b

import * as fs from "fs";

const split = (str: string): string[] => str.split(" ").map((v: string) => v.trim());
const split_number = (str: string): number[] => split(str).map((v: string) => +v);

export function main(input: string) {
  const lines = input.split("\n");
  const [n, k] = split_number(lines[0]);

  const h: number[] = split_number(lines[1]);
  let dp: number[] = new Array(n).fill(Infinity);
  dp[0] = 0;

  for (let i = 0; i < n; i++) {
    for (let j = 1; j < k + 1; j++) {
      if (i >= j) {
        dp[i] = Math.min(dp[i], dp[i - j] + Math.abs(h[i] - h[i - j]));
      }
    }

  }

  return dp[n - 1];
}

if (!process.env.LOCAL_DEBUG) {
  console.log(main(fs.readFileSync("/dev/stdin", "utf8")));
}
//  [typescript]
const lines: string[] = [];
const reader = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});
reader.on("line", function (line: string) {
  lines.push(line);
});

reader.on("close", function () {
  const rule = lines.shift().split(" ").map(Number);
  const data: number[] = lines
    .shift()
    .split(" ")
    .map((int) => parseInt(int));

  const dp = new Array(data.length).fill(Infinity);
  dp[0] = 0;

  for (let i = 1; i < rule[0]; i++) {
    for (let j = i - rule[1]; j < i; j++) {
      if (j >= 0) {
        dp[i] = Math.min(dp[i], dp[j] + abs(data[j] - data[i]));
      }
    }
  }

  console.log(dp[rule[0] - 1]);
});

function abs(val: number) {
  return val < 0 ? -val : val;
}
//  [python]
from time import sleep
n, a, b = map(int, input().split())
sleep(1.98)
print(min(a * n, b))
//  [python]
import numpy as np
import copy


def main():
    N, A, B = map(int, input().split())

    print(int(min([A * N, B])))


if __name__ == '__main__':
    main()
//  [python]
import numpy as np
import math
n, a, b = (int(i) for i in input().split()) 

print(min(a *n , b))
//  [java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] arg) {

        try (Scanner scanner = new Scanner(System.in)){
            long[] in = Arrays.stream(scanner.nextLine().split(" ")).mapToLong(Long::parseLong).toArray();
            long n = in[0];
            long a = in[1];
            long b = in[2];
            if (n * a > b) System.out.println(b);
            else System.out.println(n * a);
        }

    }
}
//  [java]
import java.util.*;
public class Main {
	public static void main(String args[] ){
		Scanner sc =new Scanner(System.in);
		int n =sc.nextInt();
		int a=sc.nextInt();
		int b=sc.nextInt();
		if(n*a <b) {
			System.out.println(n*a);
			
		} else {
			System.out.println(b);
		}
	}

}
//  [java]
import java.util.*;
import java.lang.*;
import java.io.*;

public class Main{
public static void main (String[] args){
	Scanner sc = new Scanner(System.in);
	int n = Integer.parseInt(sc.next());
	int a = Integer.parseInt(sc.next());
	int b = Integer.parseInt(sc.next());
	int c = Math.min(n*a,b);
	System.out.println(c);
}
}
//  [cpp]
#include<iostream>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<map>
#include<iomanip>
#include<sstream>
#include<vector>
#include<stack>
#include<math.h>
#include<queue>
#include<complex>
using namespace std;

long long int n,m,k;
long long int used[100005]={};
queue<long long int> qu[100005];

int main() {
    const long long int mod = 1000000007,INF=99999999999999;
	map<long long int, long long int>mp;
    string str[2005],tmp;
	cout << fixed << setprecision(10);
    cin>>n>>m>>k;
    cout<<min(k,n*m);
    
}
//  [c]
#include <stdio.h>
//#include <string.h>

int main(void){

  int n,a,b= 0;
  scanf("%d %d %d", &n, &a, &b);
  
  if(n*a>=b) printf("%d", b);
  else printf("%d", n*a);

  return 0;
}
//  [c]
#include<stdio.h>
int main()
{
    int N,A,B;
    scanf("%d%d%d",&N,&A,&B);
    if(N>=1&&N<=20&&A>=1&&A<=50&&B>=1&&B<=50)
    {
        int a;
        a=N*A;
        if(a<B)
        {
            printf("%d\n",a);
        }
        if(a>B)
        {
            printf("%d\n",B);
        }
        if(a==B)
        {
            printf("%d\n",B);
        }
    }
}
//  [c]
#include<stdio.h>
main()
{
    int n,a,b;
    scanf("%d %d %d",&n,&a,&b);
    if(n*a>b)
        printf("%d\n",b);
    else
        printf("%d\n",n*a);

}
//  [javascript]
"use strict";
const Main = (input) =>{
   let xs = input.trim().split(' ').map(v=>parseInt(v,10));
   let ans1 = xs[0] * xs[1];
   let ans2 = xs[2];
   if(ans1 > ans2){
     console.log(ans2);
   }else if(ans1 < ans2){
     console.log(ans1);
   }else{
     console.log(ans1)
   }
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const A = parseInt(arg[0].split(" ")[1]);
    const B = parseInt(arg[0].split(" ")[2]);
    
    const train = N * A;
    const bus  = B;
    
    console.log(Math.min(train, bus));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
"use strict"
function main(arg) {
    var data = arg.trim().split("\n")[0].split(" ").map(Number)
    var n = data[0]
    var a = data[1]
    var b = data[2]
    var densha = n * a
    var taxi = b
    if (densha < taxi) {
        console.log(densha)
    } else {
        console.log(taxi)
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

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

var (
	BufferSize = 10 * 10 * 10 * 10 * 10 * 10 * 10
)

func scanStr(sc *bufio.Scanner) string {
	if !sc.Scan() {
		panic(nil)
	}

	return sc.Text()
}

func scanInt(sc *bufio.Scanner) int {
	if !sc.Scan() {
		panic(nil)
	}

	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}

	return i
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	buf := make([]byte, BufferSize)
	sc.Buffer(buf, BufferSize)
	sc.Split(bufio.ScanWords)

	n := scanInt(sc)
	a := scanInt(sc)
	b := scanInt(sc)

	if a*n < b {
		fmt.Printf("%d\n", a*n)
	} else {
		fmt.Printf("%d\n", b)
	}

}
//  [go]
package main

import "fmt"

func main() {
	var n, a,b int
	fmt.Scan(&n, &a, &b)
	
	if a * n > b {
		fmt.Println(b)
		return
	}
	fmt.Println(a*n)
	
}
//  [ruby]
a,b,c=gets.split.map &:to_i
p [a*b,c].min
//  [ruby]
#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

N, A, B = get_ints

train = N * A
taxi = B

puts train > taxi ? taxi : train
//  [ruby]
n,a,b = gets.chomp.split(' ').map(&:to_i)
puts [n*a,b].min
//  [rust]
use proconio::{input, fastout};

#[fastout]
fn main() {
    input!{
        n: i32,
        a: i32,
        b: i32,
    }
    let t = std::cmp::min(n * a, b);
    println!("{}", t);
}
//  [swift]
import Foundation

let array = readLine()!.componentsSeparatedByString(" ")
let numOfPeople = Int(array[0])!
let trainFee = Int(array[1])!
let taxiFee = Int(array[2])!

if trainFee * numOfPeople < taxiFee {
  print(trainFee * numOfPeople)
} else {
  print(taxiFee)
}
//  [swift]
import Foundation

let arr = readLine()!.componentsSeparatedByString(" ")

let member = Int(arr[0])!
let train  = Int(arr[1])!
let taxi   = Int(arr[2])!

let fee = taxi < (member * train) ? taxi : member * train
print(fee)
//  [swift]
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nab = readInts()
    let n = nab[0]
    let a = nab[1]
    let b = nab[2]
    
    if n * a > b {
        print(b)
    } else {
        print(n * a)
    }
}

main()
//  [typescript]
// general helpers
const debug = (message?: any, ...optionalParams: any[]) => {
  if (process.env.LOCAL_DEBUG === '1') console.log(message, ...optionalParams)
}

// helpers
const parseLines = (
  lines: string[]
): { N: number, A: number, B: number } => {
  const [N, A, B] = lines[0].split(' ').map(line => +line)
  const obj = { N, A, B }
  debug(obj)
  return obj
}
// solver
export const solve = (lines: string[]): string => {
  const { N, A, B } = parseLines(lines)
  const answer = N * A < B ? N * A : B
  return `${answer}`

}

// main
const main = (lines: string[]) => {
  console.log(solve(lines))
}

// exec main function for submit
if (process.env.LOCAL_DEBUG !== '1') {
  const { stdin: input, stdout: output } = process
  input.resume()
  input.setEncoding('utf8')
  const lines: string[] = []
  require('readline')
    .createInterface({ input, output })
    .on('line', (line: string) => lines.push(line))
    .on('close', () => main(lines))
}
//  [typescript]
import * as fs from "fs";

const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
//const n = +input[0];
//const a = [];
//for(let i=0;i<n;i++){
//	a.push(input[i+1].split(" ").map((x:string):number=>+x));
//}

//const [n, m] = input[0].split(" ").map((x: string): number => +x);
//const a = input[1].split(" ").map((x: string): number => +x);

function compareFunc(a, b){
    return a-b;
}

const [n, a, b]: number[] = input[0].split(' ').map((x: string): number => +x);

const ans = Math.min(n*a, b);
console.log(ans);
//  [typescript]
'use strict'
const main = (input: string) => {
    const [n,a,b] = input.split(' ').map(Number)
    console.log(Math.min(n*a, b))
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [python]
from copy import deepcopy
import math
import string
import collections
from collections import Counter
from collections import deque
from decimal import Decimal
import sys
import fractions
from operator import itemgetter
import itertools
import copy


def readints():
    return list(map(int, input().split()))


def nCr(n, r):
    return math.factorial(n)//(math.factorial(n-r)*math.factorial(r))


def has_duplicates2(seq):
    seen = []
    for item in seq:
        if not(item in seen):
            seen.append(item)
    return len(seq) != len(seen)


def divisor(n):
    divisor = []
    for i in range(1, n+1):
        if n % i == 0:
            divisor.append(i)
    return divisor


def gcd(a, b):
    while(b != 0):
        a, b = b, a % b
    return a


# coordinates
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
s = list(map(str, input().split()))
# print(s)
tmp = []
for i in range(3):
    tmp.append(s[i][0])
print(''.join(tmp))
//  [python]
s = input()
 
print("A"+s[8]+"C")
//  [python]
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
from collections import deque
from fractions import gcd
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def inputI(): return int(input().strip())
def inputS(): return input().strip()
def inputIL(): return list(map(int,input().split()))
def inputSL(): return list(map(str,input().split()))
def inputILs(n): return list(int(input()) for _ in range(n))
def inputSLs(n): return list(input().strip() for _ in range(n))
def inputILL(n): return [list(map(int, input().split())) for _ in range(n)]
def inputSLL(n): return [list(map(str, input().split())) for _ in range(n)]

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])
    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])
    return arr

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#############
# Main Code #
#############

s = inputSL()

print("A"+s[1][0]+"C")
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String A = sc.next();
		String B = sc.next();
		String C = sc.next();

		System.out.println("A" + B.substring(0, 1) + "C");
	}
}
//  [java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {

    new Main().a();

  }

  private void a() {
    try (Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)))) {

      String input = in.nextLine();
      String[] words = input.split(" ");

      for (final String word:words
           ) {
        System.out.print(word.charAt(0));
      }
      System.out.println();
    }
  }
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;

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

        String name = sc.nextLine();

        System.out.println(solve(name));

        sc.close();
    }

    static String solve(String name) {
        return Arrays.stream(name.split(" ")).map(part -> part.substring(0, 1)).collect(Collectors.joining());
    }
}
//  [cpp]
#include <iostream>
#include <string>
using namespace std;

int main() {
  std::string a, b, c;
  cin >> a >> b >> c;
  cout << a[0] << b[0] << c[0] << endl;

  return 0;
}
//  [cpp]
# include <bits/stdc++.h>
# define maxn 300003
# define ll long long
# define clock (clock() * 1000.0 / CLOCKS_PER_SEC)
# define rc(s) return cout << s,0
# define _ ios_base::sync_with_stdio(false);cin.tie(0);
# define pb push_back
# define mp make_pair
using namespace std;

int main(){_
    string s1,s2,s3;
    cin >> s1 >> s2 >> s3;
    cout << s1[0] << s2[0] << s3[0];
    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
int main(void){
  char a[100],c[100],s[100];
  scanf("%s %s %s",a,s,c);
  
  printf("%c%c%c",a[0],s[0],c[0]);
  return 0;
}
//  [c]
#include <stdio.h>

int main()
{
	char s[3][101];
	scanf("%s %s %s", s[0], s[1], s[2]);
	printf("%c%c%c\n", s[0][0], s[1][0], s[2][0]);
	fflush(stdout);
	return 0;
}
//  [c]
#include <stdio.h>

int main(){
  char S[102];
  scanf("AtCoder %s Contest",S);
  printf("A%cC\n",S[0]);
  return 0;
}
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.on('SIGINT', function(){
    input_stdin_array = input_stdin.split("\n");
    main();
    process.exit();
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
	var s = readLine().split(" ");
	console.log("A"+s[1][0]+"C");
}
//  [javascript]
var reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

var args = [];

reader.on('line', function (input) {
  args.push(input);
});


reader.on('close', function () {
    var str = args[0].split(" ");
    console.log("A" + str[1].substr(0, 1) + "C");
});
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	input = input.split("\n"); // 1行目がinput[0], 2行目がinput[1], …に入る
	// ここに処理を書く
    ss = input[0].split(" ");
	// console.logは標準出力に1行出力します (自動的に最後に改行が入ります)
	console.log(ss[0][0] + ss[1][0] + ss[2][0]);
}
 
// ※この行以降は編集しない (標準入力から一度に読み込みMainを呼び出します)
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

/*
// inputに入力データ全体が入る
function Main(input) {
    console.log(input);
	input = input.split("\n"); // 1行目がinput[0], 2行目がinput[1], …に入る
	// ここに処理を書く
	var result = input[1];
    console.log(result);
	var score = 0;
	for (var i = 0; i < result.length; i++) {
		if (result[i] == "A") score += 4;
		else if (result[i] == "B") score += 3;
		else if (result[i] == "C") score += 2;
		else if (result[i] == "D") score += 1;
	}
	// console.logは標準出力に1行出力します (自動的に最後に改行が入ります)
	console.log(score / result.length);
}
 
// ※この行以降は編集しない (標準入力から一度に読み込みMainを呼び出します)
console.log("test");
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
*/
//  [go]
package main

import (
	"fmt"
)

func main() {
	var a, b, c string
	fmt.Scan(&a, &b, &c)
	fmt.Print(a[:1], b[:1], c[:1])
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

func main() {
	var a , s , c string

	fmt.Scan(&a, &s, &c)

	data := strings.Split(s, "")

	ans := "A" + data[0] + "C"

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

import "fmt"

func main() {
	// Code for A - AtCoder *** Contest
	var s1, s2, s3 string
	fmt.Scanf("%s %s %s", &s1, &s2, &s3)

	fmt.Println(string(s1[0]) + string(s2[0]) + string(s3[0]))
}
//  [ruby]
arr = gets.chomp.split

ans = ''
arr.each do |s|
  ans += s[0]
end

puts ans
//  [ruby]
a,b ,c = gets.chomp.split(" ")
print "A"
print b[0]
print "C"
print "\n"
//  [ruby]
gets.chomp.split.each{|s| print s[0]}
puts
//  [rust]
use proconio::input;

fn main() {
	input!(_a: String);
	input!(x: String);
	input!(_c: String);

	println!("A{}C", x.chars().nth(0).unwrap());
}
//  [rust]
#![allow(unused_imports)]
// use itertools::Itertools;
use proconio::{input, marker::*};

fn main() {
    input! {
        _s0: Chars,
        s1: Chars,
        _s2: Chars
    };
    println!("A{}C", s1[0]);
}
//  [rust]
use std::io::Read;

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 s1 = iterator.next().unwrap();
    let s2 = iterator.next().unwrap();
    let s3 = iterator.next().unwrap();

    let ans = format!(
        "{}{}{}",
        s1.chars().next().unwrap(),
        s2.chars().next().unwrap(),
        s3.chars().next().unwrap()
    );

    return ans;
}
//  [swift]
extension String: CollectionType {
    func toInts() -> [Int] {
        return self.split(" ").map {Int($0)!}
    }
    
    func toStrings() -> [String] {
        return self.split(" ")
    }
}

let values = readLine()!.toStrings()
let capital = String(values[1].characters.first!)
print("A\(capital)C")
//  [typescript]
import * as fs from 'fs';

const [s1, s2, s3]: string[] = fs.readFileSync('/dev/stdin', 'utf8').trim().split(' ');
console.log(s1.substring(0, 1) + s2.substring(0, 1) + s3.substring(0, 1));
//  [typescript]
import { readFileSync } from "fs";

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

const main = (input: string[][]) => {
  const x = input[0][1][0];

  return `A${x}C`;
};

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

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

console.log(`A${s[1][0]}C`)
//  [python]
N = int(input())
ans = 100000
for i in range(1, 17 * 10 ** 6):
    if N % i == 0:
        ans = min(ans, max(len(str(i)), len(str(N // i))))

print(ans)
//  [python]
from sys import setrecursionlimit; setrecursionlimit(10**9)
N = int(input())

def factorize(n):
    # NOTE: if n == 1, return []
    if n < 1:
        raise Exception('Invalid input: n = {}'.format(n))
    i = 2
    ret = []
    while i * i <= n:
        while n % i == 0:
            n //= i
            ret.append(i)
        i += 1
    if n > 1:
        ret.append(n)
    return ret

A = factorize(N)
l = len(A)

def res(i, B, C):
    if i >= l:
        val = 1
        for b in B:
            val *= b
        C.append(max(len(str(val)), len(str(N//val))))
        return None
    B.append(A[i])
    res(i+1, B, C)
    B.pop()
    res(i+1, B, C)
    return C

if N == 1:
    print(1)
else:
    C = res(0, [], [])
    print(min(C))
//  [python]
import itertools

n = int(input())


def prime_decomposition(n):
    i = 2
    table = []
    while i * i <= n:
        while n % i == 0:
            n /= i
            table.append(i)
        i += 1
    if n > 1:
        table.append(n)
    return table


n_table = prime_decomposition(n)
if not n_table:
    n_table.append(1)
f = 9999
#print(n_table)

for i in range(len(n_table) + 1):
#    print("\n" + str(i))
    i_a = itertools.combinations(n_table, i)

    while True:
        try:
            a = 1
            for j in next(i_a):
#                print("i_a=" + str(j))
                a *= j
            b = int(n / a)
#            print("b=" + str(b))
            _f = (len(str(max(a, b))))
        except StopIteration:
            break

        if _f < f:
            f = _f

print(f)
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		long N = sc.nextLong();
		sc.close();
		
		long k = (int) Math.sqrt(N);
		while(N%k!=0){
			k--;
		}
		System.out.println(func(k,N/k));

	}
	
	public static int func(long a, long b){
		return Math.max(String.valueOf(a).length(), String.valueOf(b).length());
	}

}