"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n + 1 }).map((_, i) => i - 1);
    let visit = (i, j, a, initial = false) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n || j >= n || j > i) {
            return;
        }
        if (!initial) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            // [-1, 0],
            // [0, -1],
            // [0, 1],
            // [1, 0],
            [0, -1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a, true);
    });
    // console.log({ left });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j] || 0);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	const n = rn();
	const p = rna();

	let ans = Array.from(Array(n), x => Array(n));

	for (let i = 0; ans && i < n; i++) {
		ans[i][i] = p[i];

		let r = i, c = i;
		for (let j = 1; j < p[i]; j++) {
			if (c-1>=0 && !ans[r][c-1])
				ans[r][--c] = p[i];
			else if (r+1<n & !ans[r+1][c])
				ans[++r][c] = p[i];
			else
				ans = false;
		}
	}

	if (!ans)
		console.log(-1);
	else
		for (let i = 0; i < n; i++)
			console.log(ans[i].slice(0, i+1).join(' '));
}

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
    var t = Number(input[0]);
    var arr = input[1].split(" ").map((i) => {
        return Number(i);
    });
    var grid = [];
    for (var i = 0; i < arr.length; i++) {
        grid[i] = new Array(i + 1).fill(0);
        grid[i][i] = arr[i];
    }
    var dirs = [[0, -1],[1, 0]];
    function helper(grid, i, j, num, count, dirs) {
        grid[i][j] = num;
        count--;
        for (var k = 0; k < dirs.length; k++) {
            var x = i + dirs[k][0];
            var y = j + dirs[k][1];
            if (x < grid.length && y >= 0 && grid[x][y] === 0 && count > 0) {
                helper(grid, x, y, num, count, dirs);
                break;
            }
        }
    }
    for (var i = 0; i < grid.length; i++) {
        helper(grid, i, i, arr[i], arr[i], dirs);
    }
    for (var i = 0; i < grid.length; i++) {
        console.log(grid[i].join(" "));
    }
});

process.stdin.setEncoding('utf-8')
const readline = require('readline')

const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    }
)

let count = 2
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function calcRecursive(arr, a, b, c, d, e) {
    if (e === 0) return 1
    if (c - 1 >= 0) {
        if (arr[b][c - 1] === 0) {
            arr[b][c - 1] = a
            return calcRecursive(arr, a, b, c - 1, d, e - 1)
        } else {
            if (b + 1 < d) {
                if (arr[b + 1][c] == 0) {
                    arr[b + 1][c] = a
                    return calcRecursive(arr, a, b + 1, c, d, e - 1)
                } else return 0
            }
        }
    } else {
        if (b + 1 < d) {
            if (arr[b + 1][c] == 0) {
                arr[b + 1][c] = a
                return calcRecursive(arr, a, b + 1, c, d, e - 1)
            } else return 0
        }
    }
}

function solve(n, arr) {
    let arr2 = []
    for (let i = 0; i < n; ++i) {
        arr2.push(new Array(n).fill(0))
        arr2[i][i] = arr[i]
    }
    for (let i = 0; i < n; i++) {
        if (calcRecursive(arr2, arr2[i][i], i, i, n, arr2[i][i] - 1) === 0) {
            console.log(-1)
            return
        }
    }

    for (let i = 0; i < n; ++i) {
        let temp = []
        for (let j = 0; j <= i; ++j) {
            temp.push(arr2[i][j])
        }
        console.log(temp.join(' '))
    }
}

function main() {
    solve(inputArr[0][0], inputArr[1])
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------

function Main(){
	var N = nextInt();
	var list = nextIntArray(N);
	var output = new Array(N);
	for(var j = 0; j < N; j++){
		output[j] = new Array(j + 1);
	}
	for(var j = N - 1; j >= 0; j--){
		var y = j;
		var x = j;
		var count = list[j];
		while(count > 0){
			output[y][x] = list[j];
			count--;
			if(count == 0){
				break;
			}
			if(y + 1 < N && output[y + 1][x] == null){
				y++;
				continue;
			}else if(x - 1 >= 0 && output[y][x - 1] == null){
				x--;
				continue;
			}else{
				break;
			}
		}
	}
	for(var j = 0; j < N; j++){
		myout(myconv(output[j], 8));
	}
}

const n = parseInt(readline());
const a = readline().split(' ').map((item, i) => {
  b = new Array(n).fill(0);
  b[i] = parseInt(item);
  return b;
});

for (var i = 0; i < n; i++) {
  var x = a[i][i];
  var x_ = x - 1;
  var posX = i;
  var posY = i;
  while (x_) {
    if (posX > 0 && !a[posY][posX - 1]) {
      posX--;
      a[posY][posX] = x;
    } else {
      posY++;
      a[posY][posX] = x;
    }
    x_--;
  }
}

for (var i = 0; i < n; i++) {
  for (var j = 0; j <= i; j++)
    write(`${a[i][j]} `);
  write('\n');
}

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n }).map((_, i) => i - 1);
    let visit = (i, j, a) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n || j >= n || j > i) {
            return;
        }
        if (i !== j) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            [-1, 0],
            [0, -1],
            [0, 1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a);
    });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j]);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n }).map((_, i) => i - 1);
    let visit = (i, j, a) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n || j >= n) {
            return;
        }
        if (i !== j) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            [-1, 0],
            [0, -1],
            [0, 1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a);
    });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j]);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n }).map((_, i) => i - 1);
    let visit = (i, j, a) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n) {
            return;
        }
        if (i !== j) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            [0, -1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a);
    });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j]);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

const n = parseInt(readline());
const a = readline().split(' ').map((item, i) => {
  b = new Array(n).fill(0);
  b[i] = parseInt(item);
  return b;
});

for (var i = 0; i < n; i++) {
  var x = a[i][i];
  var x_ = x - 1;
  var posX = i;
  var posY = i;
  while (x_) {
    if (posX > 0 && !a[posY][posX - 1]) {
      posX--;
      a[posY][posX] = x;
    } else {
      posY++;
      a[posY][posX] = x;
    }
    x_--;
  }
}

for (var i = 0; i < n; i++) {
  for (var j = 0; j < n; j++)
    write(`${a[i][j]} `);
  write('\n');
}


process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))

  const [n, k] = arr.shift().split(' ').map(a => parseInt(a))

  const str = arr[0]
  const available = arr[1]
  let sum = 0, last = -1

  for(let i = 0; i < n; i++) {
    if(!available.includes(str[i])) {
      let x = i - last - 1
      // console.log('x:', x, sum, last, i)
      sum += (x + 1) * x / 2
      last = i
    }
  }
  if(last != n - 1) {
    let x = n - 1 - last
    // console.log('x:', x, sum, last)
    sum += (x + 1) * x / 2
  }

  console.log(sum)
})

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function getArray(str) {
    return str.split(' ').map(x => Number(x));
}

function getInt(str) {
    return Number(str);
}

function getStrArray(str) {
    return str.split(' ').map(x => x);
}

function create2DArray(rows) {
    var arr = [];

    for (var i = 0; i < rows; i++) {
        arr[i] = [];
    }

    return arr;
}
// ---------------------------------------

function main() {
    let [strLen, charOptions] = getArray(readline());
    let str = readline();
    let charArr = getStrArray(readline());
    let x = [];
    for (let i = 0; i < strLen; i++) {
        if (charArr.indexOf(str[i]) > -1) {
            x[i] = 1;
        } else {
            x[i] = 0;
        }
    }

    let count = 0;
    let ans = 0;
    for(let i= 0; i< strLen; i++) {
        if (x[i] === 0) {
            ans += count*(count+1)/2;
            count = 0
        } else if (x[i] === 1) {
            count++;
        }
    }
    if(count !== 0) {
        ans += count*(count+1)/2;
    }
    console.log(ans);
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data, letters) {
        const subAr = data.split(new RegExp(`[^${letters}]`))
        return subAr.reduce((acc, value) => {
            const n = value.length;
            return acc + ((n * (n + 1)) / 2);
        }, 0)
    }

    let result = foo(lines[1], lines[2].replace(/\s/g, ''));
    console.log(result);
})

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let result = 0;
    let list = [];
    str.split('').forEach((c, index) => {
        if (letters.indexOf(c) < 0) {
            list.push(index);
        }
    });
    list.push(str.length);

    let lastIndex = 0;
    list.forEach((v) => {
        if (v > 0 && v > lastIndex) {
            let len = v - lastIndex;
            result += len * (len + 1) / 2;
        }
        // console.log(lastIndex, v, result);
        lastIndex = v + 1;
    });

    // console.log(list);
    console.log(result);
});

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0;
});
for (let i = 0; i < txt.length; i += 3) {
    doit(txt[i + 1], txt[i + 2].split(" ").filter(data => {
        return data.length > 0
    }))
}

function doit(tab, keys) {
    let arr = []
    let seg=""
    for (let i = 0; i < tab.length; i++) {
        if(keys.includes(tab[i])){
            seg+=tab[i]
        }else if(seg.length>0){
            arr.push(seg.length);
            seg=""
        }

    }
    if(seg.length>0){
        arr.push(seg.length)
    }
    seg=0;
    arr.forEach(data=>{
        seg+=data*(data+1)/2
    })
    console.log(seg);
}

'use strict'

const problem = (n, k, s, t) => {
    let j = 0, r = 0, len = s.length;
    for (let i = 0; i < len; i++) {
        if (t.indexOf(s[i]) === -1) {
            if (j === -1) continue;
            r += (i-j)*(i-j+1) / 2;
            j = -1;
        } else {
            if (j === -1) j = i;
        }
    }
    if (j === -1) return r;
    r += (len-j)*(len-j+1) / 2;
    return r;
}

const nk = readline().split(' ').map(i => +i);
print(problem(nk[0], nk[1], readline(), readline()));

function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){print(t);}//standard output
//function myout(t){console.log(t);}//standard output
function myerr(t){console.err(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}

function Main() {
  //input = myconv(input,3);
  var first = readline();
  var N = myconv(first,4)[0];
  var k = myconv(first,4)[1];
  var list = myconv(readline(),6);
  var keys = myconv(readline(),2);
  var numlist = new Array(N).fill(0);
  for(var i = 0; i < N; i++){
    var tmps = list[i];
    if(keys.indexOf(list[i]) != -1){
       if(i == 0){
          numlist[i] = 1;
       }else{
          numlist[i] = numlist[i-1]+1;
       }
    }
  }
  var output = 0;
  for(var i = 0; i < N; i++){
    output += numlist[i];
  }
  myout(output);
}

Main();

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let result = 0;
    let list = [];
    str.split('').forEach((c, index) => {
        if (letters.indexOf(c) < 0) {
            list.push(index);
        }
    });
    list.push(str.length);

    let lastIndex = 0;
    list.forEach((v) => {
        if (v > 0 && v > lastIndex) {
            console.log(lastIndex, v);
            let len = v - lastIndex;
            result += len * (len + 1) / 2;
        }
        // console.log(lastIndex, v, result);
        lastIndex = v + 1;
    });

    // console.log(list);
    console.log(result);
});

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let lastIndex = 0;
    let result = 0;
    str.split('').forEach((c, index, array) => {
        // console.log(index, c, lastIndex, result);
        if ((letters.indexOf(c) < 0) && index > lastIndex) {
            // console.log('adding', lastIndex, index, index - lastIndex);
            let len = index + 1 - lastIndex;
            result += len * (len + 1) / 2;
        } else if ((letters.indexOf(c) < 0 || index === array.length - 1) && index > lastIndex) {

        }
        if (letters.indexOf(c) < 0) {
            lastIndex = index + 1;
        }
    });
    console.log(result);
});

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let lastIndex = 0;
    let result = 0;
    str.split('').forEach((c, index, array) => {
        // console.log(index, c, lastIndex, result);
        if (letters.indexOf(c) < 0 && index > lastIndex) {
            // console.log('adding', lastIndex, index, index - lastIndex);
            let len = index - lastIndex;
            result += len * (len + 1) / 2;
        } else if (index === array.length - 1 && index > lastIndex) {
            // console.log('adding', lastIndex, index, index + 1 - lastIndex);
            let len = index + 1 - lastIndex;
            result += len * (len + 1) / 2;
        }
        if (letters.indexOf(c) < 0) {
            lastIndex = index + 1;
        }
    });
    console.log(result);
});

'use strict'

const problem = (n, k, s, t) => {
    let j = 0, r = 0, len = s.length;
    for (let i = 0; i < len; i++) {
        if (t.indexOf(s[i]) === -1) {
            if (j === -1) continue;
            r += (i-j)*(i-j+1) / 2;
            j = -1;
        } else {
            if (j === -1) j = i;
        }
    }
    if (j === -1) return 0;
    r += (len-j)*(len-j+1) / 2;
    return r;
}

const nk = readline().split(' ').map(i => +i);
print(problem(nk[0], nk[1], readline(), readline()));

'use strict'

const problem = (n, k, s, t) => {
    let j = 0, r = 0, len = s.length;
    for (let i = 0; i < len; i++) {
        if (t.indexOf(s[i]) === -1) {
            if (j === -1) continue;
            r += (i-j)*(i-j+1) / 2;
            j = -1;
        } else {
            if (j === -1) j = i;
        }
    }
    r += (len-j)*(len-j+1) / 2;
    return r;
}

const nk = readline().split(' ').map(i => +i);
print(problem(nk[0], nk[1], readline(), readline()));


function main() {
    var homeTeam = next();
    var guestTeam = next();

    var n = nextInt();
    var status = {};
    var res = [];

    for (var i = 0; i < n; i++) {
        var time = nextInt();
        var team = next().charAt(0) === 'h' ? 0 : 1;
        var m = nextInt();
        var cardType = next().charAt(0);
        var name = team + '_' + m;
        var found = false;
        if (status[name] === 1) {
            status[name] = 2;
            found = true;
        } else if (status[name] === 2) {
        } else {
            status[name] = cardType === 'y' ? 1 : 2;
            found = status[name] === 2;
        }
        if (found)
          res.push([(team === 0 ? homeTeam : guestTeam), m, time]);
    }

    for (var j = 0; j < res.length; j++) {
        print(res[j][0] + ' ' + res[j][1] + ' ' + res[j][2]);
    }
}

// auxiliary code
var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

main();

function main(){
    var h = [];
    h.push(next());
    h.push(next());
    var E = [];
    E.push({});
    E.push({});
    var t = nextInt();
    var time,team,number,type;
    while(t-->0){
        time = nextInt();
        team = next().charAt(0)!="h" ? 1:0 ;
        number = nextInt();
        type = next();
        if(type == "r"){
            if(!E[team][number])
                E[team][number]=0;
            if(E[team][number]<=1){
                print(h[team]+" "+number+" "+time);
                }
            E[team][number]+=2;
            }
        else {
            if(!E[team][number])
               E[team][number]=0;
            if(E[team][number]==1){
                print(h[team]+" "+number+" "+time);
                }
            E[team][number]++;
            }
        }
    }
var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

main();

var home = readline(),
			away = readline(),
			n = parseInt(readline()),
			homeCheck = {}, awayCheck = {};

		for(var i = 0; i < n; i++)	{
			var inputs = readline().split(/\s/gi),
				time = inputs[0],
				team = inputs[1],
				player = inputs[2],
				card = inputs[3];

			if(team == 'a')	{
				if(!awayCheck[player])	awayCheck[player] = { 'y' : 0, 'r' : 0, 'hasRed' : false };

				awayCheck[player][card] += 1;

				if((awayCheck[player].y >= 2 || awayCheck[player].r >= 1) && !awayCheck[player].hasRed)	{
					print(away + ' ' + player + ' ' + time);
					awayCheck[player].hasRed = true;
				}
			} else	{
				if(!homeCheck[player])	homeCheck[player] = { 'y' : 0, 'r' : 0, 'hasRed' : false };

				homeCheck[player][card] += 1;

				if((homeCheck[player].y >= 2 || homeCheck[player].r >= 1) && !homeCheck[player].hasRed)	{
					print(home + ' ' + player + ' ' + time);
					homeCheck[player].hasRed = true;
				}
			}
		}

function main(){
    var h = [];
    h.push(next());
    h.push(next());
    var E = [];
    E.push({});
    E.push({});
    var t = nextInt();
    var time,team,number,type;

    while(t-->0){
        time = nextInt();
        team = next().charAt(0)!="h";
        number = nextInt();
        type = next();
        if(type == "r"){
            if(!E[team][number])
                E[team][number]=0;
            if(E[team][number]<=1){
                print([team]+" "+number+" "+time);
                }
            E[team][number]+=2;
            }
        else {
            if(!E[team][number])
               E[team][number]=0;
            if(E[team][number]==1){
                print([team]+" "+number+" "+time);
                }
            E[team][number]++;
            }
        }
    }

var home = readline(),
			away = readline(),
			n = parseInt(readline()),
			homeCheck = {}, awayCheck = {};

		for(var i = 0; i < n; i++)	{
			var inputs = readline().split(/\s/gi),
				time = inputs[0],
				team = inputs[1],
				player = inputs[2],
				card = inputs[3];

			if(team == 'a')	{
				if(!awayCheck[player])	awayCheck[player] = { 'y' : 0, 'r' : 0 };

				awayCheck[player][card] += 1;

				if(awayCheck[player].y >= 2 || awayCheck[player].r >= 1)	{
					print(away + ' ' + player + ' ' + time);
				}
			}
			if(team == 'h')	{
				if(!homeCheck[player])	homeCheck[player] = { 'y' : 0, 'r' : 0 };

				homeCheck[player][card] += 1;

				if(homeCheck[player].y >= 2 || homeCheck[player].r >= 1)	{
					print(home + ' ' + player + ' ' + time);
				}
			}
		}

var home = readline(),
			away = readline(),
			n = parseInt(readline()),
			homeCheck = {}, awayCheck = {};

		for(var i = 0; i < n; i++)	{
			var inputs = readline().split(/\s/gi),
				time = inputs[0],
				team = inputs[1],
				player = inputs[2],
				card = inputs[3];

			if(team == 'a')	{
				if(!awayCheck[player])	{
					awayCheck[player] = {
						'y' : 0,
						'r' : 0
					};
				}

				awayCheck[player][card] += 1;

				if(awayCheck[player].y >= 2 || awayCheck[player].r >= 1)	{
					print(away + ' ' + player + ' ' + time);
				}
			} else	{
				if(!homeCheck[player])	{
					homeCheck[player] = {
						'y' : 0,
						'r' : 0
					};
				}

				homeCheck[player][card] += 1;

				if(homeCheck[player].y >= 2 || homeCheck[player].r >= 1)	{
					print(home + ' ' + player + ' ' + time);
				}
			}
		}


var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 1, p = 0;
	for (; i < s.length; i++) {
		if (s[i] < s[p]) {
			p = 0;
		} else if (s[i] == s[p]) {
			p++;
		} else {
			break;
		}
	}
	i = i - p;

	s = s.slice(0, i);
	s = s.repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

function solve() {
   var nk = readArray(Number);
   var n = nk[0];
   var k = nk[1];
   var str = read();
   var current = 1;
   var savepoint;
   var check;
   while(true) {
      if (current >= n) {
         break;
      }
      if (str[current] > str[0]) {
         str = str.substr(0, current);
         break;
      }
      if (str[current] < str[check]) {
         current++;
         continue;
      }
      savepoint = current;
      check = 0;
      while (current < 3 * n && str[current % n] === str[check]) {
         current++;
         check++;
         if (check >= savepoint) {
            check = 0;
         }
      }
      if (current !== 3 * n && str[current % n] > str[check]) {
         str = str.substr(0, savepoint);
         break;
      }
   }
   while(str.length < k) {
      str = str + str;
   }
   write(str.substr(0, k));
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function init() {
   try {
      var T;
      T = 1;
      //T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e);
   }
}

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

var matr = 'haha';

function create(str) {
   var hahaIndexArr = [];
   for (var i = 0; i < str.length; i++) {
      var hasWrong = false;
      for (var j = 0; j < matr.length; j++) {
         if (str[i + j] !== matr[j]) {
            hasWrong = true;
            break;
         }
      }
      if (!hasWrong) {
         hahaIndexArr.push(i);
      }
   }
   if (hahaIndexArr.length === 0) {
      if (str.length < 8) {
         return [str, -1, str];
      }
      return [str.substr(0, 4), 0, str.substr(str.length - 4, 0)];
   }
   var preff = str.substr(0, Math.min(4, hahaIndexArr[0])) || 'ha';
   var suff = str.substr(Math.max(hahaIndexArr[hahaIndexArr.length - 1] + 4, str.length - 4)) || 'ha';
   return [preff, hahaIndexArr.length, suff];
}
function summ(a, b) {
   var createMiddle = create(a[2] + b[0]);
   if (a[1] === -1 && b[1] === -1) {
      return createMiddle;
   }
   var preff = a[1] === -1 ? createMiddle[0] : a[0];
   var suff = b[1] === -1 ? createMiddle[2] : b[2];
   var asum = a[1] === -1 ? 0 : a[1];
   var bsum = b[1] === -1 ? 0 : b[1];
   var midSum = createMiddle[1] === -1 ? 0 : createMiddle[1];
   return [preff, asum + bsum + midSum, suff];
}

function solve() {
   var nk = readArray(Number);
   var n = nk[0];
   var k = nk[1];
   var str = read();
   var current = 1;
   var savepoint;
   var check;
   while(true) {
      if (current >= n) {
         break;
      }
      if (str[current] > str[0]) {
         str = str.substr(0, current);
         break;
      }
      if (str[current] < str[check]) {
         current++;
         continue;
      }
      savepoint = current;
      check = 0;
      while (current < n && str[current] === str[check]) {
         current++;
         check++;
         if (check >= savepoint) {
            check = 0;
         }
      }
      if (current !== n && str[current] > str[check]) {
         str = str.substr(0, savepoint);
         break;
      }
   }
   while(str.length < k) {
      str = str + str;
   }
   write(str.substr(0, k));

}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function init() {
   try {
      var T;
      T = 1;
      //T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e);
   }
}

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}


var fl=readline().split(' ');
var maxDistance=fl[1];

var stations=readline().split(' ');
var distantions=stations.map((i,k,a)=>i-(a[k-1]||0)).slice(1);
if(distantions.some(i=>i>maxDistance)){
    print('-1');
}
else{
    var count=1;
    var currentCredit=maxDistance;
    for(var k=0; k<distantions.length; k++){
        if(distantions[k]<=currentCredit){

            currentCredit-=distantions[k];
        }
        else{

            count++;
            currentCredit=maxDistance-distantions[k];
        }
    }
    print(count);
}

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var maxKmImmut = maxKm;
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < points.length; i++) {
        if ((points[i] - temp) > maxKmImmut) {
            return 0;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm < points[i+1] - points[i]) {
                if (i == points.length-1) {
                    return changes;
                }
                changes++;
                maxKm = maxKmImmut;
            }
        } else {
            changes++;
            maxKm = maxKmImmut;
        }
        temp = points[i];
    }
    return changes;
}
var res = operate();
write((res == 0) ? -1 : res);

'use strict';var _slicedToArray=function(){function b(c,d){var e=[],f=!0,g=!1,h=void 0;try{for(var l,j=c[Symbol.iterator]();!(f=(l=j.next()).done)&&(e.push(l.value),!(d&&e.length===d));f=!0);}catch(m){g=!0,h=m}finally{try{!f&&j['return']&&j['return']()}finally{if(g)throw h}}return e}return function(c,d){if(Array.isArray(c))return c;if(Symbol.iterator in Object(c))return b(c,d);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),data=[];data.push(readline()),data.push(readline());var pI=function(b){return parseInt(b,10)};function solve(){for(var _data$0$split$map=data[0].split(' ').map(pI),_data$0$split$map2=_slicedToArray(_data$0$split$map,2),b=_data$0$split$map2[0],c=_data$0$split$map2[1],d=data[1].split(' ').map(pI),e=1,f=0,g=0;g<b-1;g++){if(d[g+1]-d[g]>c)return void print(-1);d[g+1]-d[g]+f>c?(f=d[g+1]-d[g],e+=1):f+=d[g+1]-d[g]}print(e)}solve();

var first = readline().split(' ');
var second = readline().split(' ');
var count = +first[0];
var max = +first[1];
var current=0;
var tempor=1;
var return_val=0;
while (current<count-1)
{
	if (second[current + 1] - second[current] > max)
	{
		return_val=-1;
		current=count;
	}
	else if (second[tempor] - second[current] > max)
	{
		current = tempor-1;
		return_val++;
	}
	else if (tempor == count)
	{
		return_val++;
		current=count;
	}
	else tempor++;
}
print(return_val);

//var readline = require('lol-io').readline
//var print = require('lol-io').print

var l1 = readline().split(' ');
var n = parseInt(l1[0]);
var k = parseInt(l1[1]);

var lx = readline().split(' ');
var x = [];
for (var i=0;i<n;i++){
  x.push(parseInt(lx[i]));
}
var ans = 0;
var i = 0;
while (true){
  var t = x[i] + k;
  var j = i + 1;
  while(true){
    if (j + 1 < n && x[j+1]<=t){
      j++;
    }
    else {
      break;
    }
  }
  if (t<x[j]){
    ans = -1;
    break;
  }
  ans++;
  i = j;

  if (i==n-1){
    break;
  }
}
print(ans);

var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
var bikeRentPoints = readline().split(" ").map(function(x) { return parseInt(x); });
var n = numbers[0];
var k = numbers[1];
var numberOfBikes = 1;
var currentDistance = 0;

for(var i = 1; i < n; i++) {
    var difference = bikeRentPoints[i] - bikeRentPoints[i - 1];
    if(difference > k) {
        numberOfBikes = -1;
        break;
    } else {
        if(currentDistance + difference > k) {
            numberOfBikes++;
            currentDistance = difference;
        } else {
            currentDistance += difference;
        }
    }
}

print(numberOfBikes);

var line1 = readline()
var line2 = readline()

line1 = line1.split(' ')
var coordinates = line2.split(' ')

var n = line1[0]
var step = Number(line1[1])
var pos = Number(coordinates[0])
var bikes = 0

while(true) {

    var nearest = coordinates[n - 1]
    pos = pos + step
    var distances = []

    for (var i = 0; i < n; i++) {
        distances.push(pos - coordinates[i])
    }
    for (var i = 0; i < distances.length; i++) {
        if (distances[i] >= 0) {
            nearest = coordinates[i]
        }
    }
    bikes++
    if(nearest == pos - step) {
        print(-1)
        break
    }
    pos = Number(nearest)
    if (pos == coordinates[n - 1]) {
        print(bikes)
        break
    }
}

// process.stdin.resume();
// process.stdin.setEncoding('utf-8');

// let inputString = '';
// let currentLine = 0;
// let lines = 0;

// process.stdin.on('data', inputStdin => {
//     inputString += inputStdin;
//     lines++;
//     // if(lines >= 2) {
//     //     inputString = inputString.trim().split('\n').map(str => str.trim());
//     //     return main()
//     // }
// });

// process.stdin.on('end', _ => {
//     inputString = inputString.trim().split('\n').map(str => str.trim());

//     main();
// });

// function readLine() {
//     return inputString[currentLine++];
// }

function findPathFrom(rentals, from, dist, counter) {
    var maxDist = rentals[from] + dist;

    if(maxDist >= rentals[rentals.length - 1]) return counter;

    var nextRentals = [];
    for(var i = from + 1; rentals[i] <= maxDist; i++) nextRentals.push(i);
    if(!nextRentals.length) return -1;
    var nextRental = nextRentals.pop();
    return findPathFrom(rentals, nextRental, dist, counter + 1);
}

function main() {
    var f = readline().split(' ').map(Number);
    var rentals = readline().split(' ').map(Number);
    print(findPathFrom(rentals, 0, f.pop(), 1));
}

main()

var l = readline().split(' ');
var n = l[0];
var k = l[1];
var l1 = readline().split(' ');
var v = [];
var count = 0;
for(p=0;p<n;p++) {
	v.push(l1[p]);
}
function start() {

    for(i=v.length - 1;i>-1;i--) {
		if(i === 0) {
		count = -1;
		break;
		}
        if((v[i] - k) <= v[0]) {

			count++;

            v = v.splice(i, v.length);
			if(v.length != 1) {
			start();
			}
            break;

        }

    }
}
start();
print(count);

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var maxKmImmut = maxKm;
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if ((points[i] - temp) > maxKmImmut) {
            return 0;
        }
        if (i == number - 1) {
            return changes;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0) {
                changes++;
                maxKm = 3;
            }
        } else {
            changes++;
            maxKm = 3;
        }
        temp = points[i];
    }
    return changes;
}
write((operate() == 0) ? -1 : operate());

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var maxKmImmut = maxKm;
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if ((points[i] - temp) > maxKmImmut) {
            return 0;
        }
        // if (i == number - 1) {
        //     return changes;
        // }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0 && i != number - 1) {
                changes++;
                maxKm = 3;
            }
        } else {
            changes++;
            maxKm = 3;
        }
        temp = points[i];
    }
    return changes;
}
write((operate() == 0) ? -1 : operate());

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if (i == number - 1) {
            return changes;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0) {
                changes++;
                maxKm = 3;
            }
        } else {
            changes++;
            maxKm = 3;
        }
        temp = points[i];
    }
    return changes;
}
write((operate() == 1) ? -1 : operate());

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if ((points[i] - temp) > 3) {
            return 1;
        }
        if (i == number - 1) {
            return changes;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0) {
                changes++;
                maxKm = 3;
            }
        } else {
            changes++;
            maxKm = 3;
        }
        temp = points[i];
    }
    return changes;
}
write((operate() == 1) ? -1 : operate());

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if ((points[i] - temp) > 3) {
            return 0;
        }
        if (i == number - 1) {
            return changes;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0) {
                changes++;
                maxKm = 3;
            }
        } else {
            changes++;
            maxKm = 3;
        }
        temp = points[i];
    }
    return changes;
}
write((operate() == 0) ? -1 : operate());

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var maxKmImmut = maxKm;
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if ((points[i] - temp) > maxKmImmut) {
            return 0;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0 && i != number - 1) {
                changes++;
                maxKm = maxKmImmut;
            }
        } else {
            changes++;
            maxKm = maxKmImmut;
        }
        temp = points[i];
    }
    return changes;
}
write((operate() == 0) ? -1 : operate());

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var maxKmImmut = maxKm;
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < points.length; i++) {
        if ((points[i] - temp) > maxKmImmut) {
            return 0;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0) {
                if (i == points.length-1) {
                    return changes;
                }
                changes++;
                maxKm = maxKmImmut;
            }
        } else {
            changes++;
            maxKm = maxKmImmut;
        }
        temp = points[i];
    }
    return changes;
}
var res = operate();
write((res == 0) ? -1 : res);

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var maxKmImmut = maxKm;
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if ((points[i] - temp) > maxKmImmut) {
            return 0;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0 && (i != number - 1)) {
                changes++;
                maxKm = maxKmImmut;
            }
        } else {
            changes++;
            maxKm = maxKmImmut;
        }
        temp = points[i];
    }
    return changes;
}
write((operate() == 0) ? -1 : operate());

var user_input = readline().split(" ");
var number = parseInt(user_input[0]);
var maxKm = parseInt(user_input[1]);
var maxKmImmut = maxKm;
var points = readline().split(" ");
var changes = 1;
var temp = points[0];
var operate = function() {
    for (var i = 1; i < number; i++) {
        if ((points[i] - temp) > maxKmImmut) {
            return 0;
        }
        if ((points[i] - temp) <= maxKm) {
            maxKm -= points[i] - temp;
            if (maxKm <= 0) {
                if (i == number-1) {
                    return changes;
                }
                changes++;
                maxKm = maxKmImmut;
            }
        } else {
            changes++;
            maxKm = maxKmImmut;
        }
        temp = points[i];
    }
    return changes;
}
var res = operate();
write((res == 0) ? -1 : res);

var line1 = readline()
var line2 = readline()

line1 = line1.split(' ')
var coordinates = line2.split(' ')

var n = line1[0]
var step = Number(line1[1])
var pos = Number(coordinates[0])
var bikes = 0

while(true) {
    var nearest = coordinates[n - 1]
    pos = pos + step
    var distances = []

    for (var i = 0; i < n; i++) {
        distances.push(pos - coordinates[i])
    }
    for (var i = 0; i < distances.length; i++) {
        if (distances[i] >= 0 && distances[i] < nearest) {
            nearest = coordinates[i]
        }
    }

    bikes++

    if(nearest == pos - step) {
        print(-1)
        break
    }

    pos = Number(nearest)

    if (pos == coordinates[n - 1]) {
        print(bikes)
        break
    }
}

var line1 = readline()
var line2 = readline()

line1 = line1.split(' ')
var coordinates = line2.split(' ')

var n = line1[0]
var step = Number(line1[1])
var pos = Number(coordinates[0])
var bikes = 0

while(true) {

    var nearest = coordinates[n - 1]
    pos = pos + step
    var distances = []

    for (var i = 0; i < n; i++) {
        distances.push(pos - coordinates[i])
    }

    for (var i = 0; i < distances.length; i++) {
        if (distances[i] >= 0 && distances[i] <= nearest) {
            nearest = coordinates[i]
        }
    }

    if(Number(nearest) == pos - step) {
        print(-1)
        break
    }

    bikes++

    pos = Number(nearest)
    if (pos == Number(coordinates[n - 1])) {
        print(bikes)
        break
    }
}


/*
* auther yeling
*
*
*/
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
function print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();

function begin(n, q, nums, querys) {
    //print(n, q, nums, querys);
    let odd = 0;
    let even = 0;
    let sum = 0;
    for (let i = 0; i < n; i++) {
        if (nums[i] % 2 == 0) {
            even++;
        } else {
            odd++;
        }
        sum += nums[i];
    }
    for (let i = 0; i < q; i++) {
        if (querys[i][0] == 0) {
            if (querys[i][1] % 2 == 0) {
                sum += even * querys[i][1];
            } else {
                sum += even * querys[i][1];
                odd += even;
                even = 0;
            }
        } else if (querys[i][0] == 1) {
            if (querys[i][1] % 2 == 0) {
                sum +=  odd * querys[i][1];
            } else {
                sum +=  odd * querys[i][1];
                even += odd;
                odd = 0;
            }
        }
        print(sum);
    }
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));

        var x = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));

        let querys = [];
        for (let j = 0; j < n[1]; j++) {
            var temp = readline()
                .trim()
                .split(' ')
                .map((y) => parseInt(y, 10));
            querys.push(temp);

        }
        begin(n[0], n[1], x, querys);
    }
}

const lines = [];
const _rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
_rl.on('line', line => lines.push(line));
_rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);
const rl = readline;

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const sumab = (a, b) => {
    if (a > b) return 0;
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return x * y;
}

const calc = (t)=>{
    /* read */
    let [n, q] = ra();
    let a = ra();

    let even = 0;
    let evenCount = 0;
    let odd = 0;
    let oddCount = 0;

    for (let i = 0; i < n; i++) {
        if (a[i] % 2 === 0) {
            even += a[i];
            evenCount++;
        } else {
            odd += a[i];
            oddCount++;
        }
    }

    for (let qq = 0; qq < q; qq++) {
        let [type, x] = ra();
        if (type === 0) { // even
            let sum = even + evenCount * x;
            process.stdout.write(`${sum + odd}\n`);
            if (sum === 0) continue;
            if (x % 2 === 0) {
                even = sum;
            } else {
                oddCount = n;
                odd += sum;
                even = 0;
                evenCount = 0;
            }
        } else { // odd
            let sum = odd + oddCount * x;
            process.stdout.write(`${sum + even}\n`);
            if (sum === 0) continue;
            if (x % 2 === 0) {
                odd = sum;
            } else {
                evenCount = n;
                even += sum;
                odd = 0;
                oddCount = 0;
            }
        }
    }
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        calc(t);
        // out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    // process.stdout.write(out.join('\n')+'\n');
}

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    let cnt=0;
    for(let _=1;_<=t;_++)
    {
        let [n,q]=line[++cnt].split(' ').map(x=>{return parseInt(x)});
        let a=line[++cnt].split(' ').map(x=>{return parseInt(x)});
        let odd=0,even=0;
        let sum1=0,sum2=0;
        for(let i=0;i<n;i++)
        {
            if(a[i]&1)
            {
                odd+=a[i];
                sum1++;
            }
            else
            {
                even+=a[i];
                sum2++;
            }
        }
        for(let z=1;z<=q;z++)
        {
            let [p,x]=line[++cnt].split(' ').map(x=>{return parseInt(x)});
            if(p==0)
            {
                if(x%2==0)
                {
                    even+=sum2*x;
                }
                else
                {
                    even+=sum2*x;
                    odd+=even;
                    sum1+=sum2;
                    sum2=0;
                    even=0;
                }
            }
            else
            {
                if(x%2==1)
                {
                    odd+=sum1*x;
                    even+=odd;
                    sum2+=sum1;
                    odd=0;
                    sum1=0;
                }
                else
                {
                    odd+=sum1*x;
                    // even+=odd;
                }
            }
            console.log(odd+even);
        }
        // console.log(a);
    }
})

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = BInpArr();
    let ods = 0n,
      evs = 0n,
      odd = 0n,
      even = 0n;
    for (let i = 0; i < n; i++) {
      if (arr[i] % 2n === 0n) {
        evs += arr[i];
        even++;
      } else {
        ods += arr[i];
        odd++;
      }
    }
    for (let i = 0; i < k; i++) {
      let [p, v] = BInpArr();
      if (p === 0n) {
        if (v % 2n === 0n) {
          v = v * even;
          evs += v;
          console.log(ods + evs + "");
        } else {
          v = v * even;
          evs += v;
          console.log(ods + evs + "");
          ods += evs;
          odd += even;
          evs = 0n;
          even = 0n;
        }
      } else {
        if (v % 2n === 0n) {
          v = v * odd;
          ods += v;
          console.log(ods + evs + "");
        } else {
          v = v * odd;
          ods += v;
          console.log(ods + evs + "");
          evs += ods;
          even += odd;
          ods = 0n;
          odd = 0n;
        }
      }
    }
  }
};
solve();

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, q] = rns(),
        a = rns();
  let sum = 0n,
      odd = 0,
      even = 0;
  for (let i = 0; i < n; i++) {
    sum += BigInt(a[i]);
    if (a[i] & 1) odd++;else even++;
  }
  let res = new Array(q);
  for (let i = 0; i < q; i++) {
    const [t, v] = rns();
    if (v & 1) {
      if (t === 0) {
        sum += BigInt(v * even);
        odd += even;
        even = 0;
      } else {
        sum += BigInt(v * odd);
        even += odd;
        odd = 0;
      }
    } else {
      if (t === 0) {
        sum += BigInt(v * even);
      } else {
        sum += BigInt(v * odd);
      }
    }
    res[i] = sum;
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, q] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, arr, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, qs) {
    let even = 0
    let ce = 0
    let odd = 0
    let co = 0
    for (let x of arr) {
        if (x & 1) {
            odd += x
            co++
        } else {
            even += x
            ce++
        }
    }
    return qs.map(([t, x]) => {
        if (t === 0) {
            // to even
            if (x & 1) {
                odd += even + ce * x
                co += ce
                even = 0
                ce = 0
            } else {
                even += ce * x
            }
        } else {
            if (x & 1) {
                even += odd + co * x
                ce += co
                odd = 0
                co = 0
            } else {
                odd += co * x
            }
        }
        return even + odd
    }).join('\n')
}

const readNum = () => +readline();
const readStr = () => readline();
const readStrArr = () => readline().split(' ');
const readNumArr = () => readline().split(' ').map(item => +item);
const createEmptyArr = (number) => new Array(number).fill(0);
const getSum = (arr) => {
  var sum = 0;
  for(var si = 0; si < arr.length; si++) {
    sum+=(+arr[si])
  }
  return sum;
}
const sumNItems = (n) => {
  var sum = 0;
  for(var si = n; si > 0; si--) {
    sum+=si;
  }
  return sum;
}

var n = +readline();
for(var i = 0; i < n; i++) {
  var vars = readline().split(' ').map(item => +item);
  var arr = readline().split(' ').map(item => +item);
  var c1 = 0, c2 = 0, sum = 0;
  for(var k = 0; k < vars[0]; k++) {
    if(arr[k] % 2 === 1) {
      c1++;
    } else {
      c2++;
    }
    sum += arr[k];
  }
  for(var j = 0; j < vars[1]; j++) {
    var item = readline().split(' ').map(item => +item);
    if(item[0] === 0) {
      sum += c2 * item[1];
    } else {
      sum += c1 * item[1];
    }
    if(item[0] === 1 && c1 > 0 && item[1] % 2 === 1) {
      c2 = vars[0];
      c1 = 0;
    }
    if(item[0] === 0 && c2 > 0 && item[1] % 2 === 1) {
      c1 = vars[0];
      c2 = 0;
    }
    print(sum);
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
    var n = +readline();

    for(var i = 0; i < n; i++) {

      var opNums = readline().split(' ')[1];
      var arr = readline().split(' ').map(el => +el);

        var ops = []

        for(var j=0; j<opNums; j++) {
            ops.push(readline().split(' ').map(el => +el))
        }

     foo(arr, ops)
    }
}

function foo(arr, operations) {
  var juftNums = 0
  var toqNums = 0
  var sum = 0

  for(var i = 0; i<arr.length; i++) {
    sum += arr[i]
    if(arr[i] % 2 === 0) juftNums++
    else toqNums++
  }

  for(var j = 0; j<operations.length; j++) {
    if(operations[j][0] === 0) {
      sum = juftNums * operations[j][1] + sum
      if(operations[j][1] % 2 === 1) {
        toqNums += juftNums
        juftNums = 0
      }
    }
    else {
      sum = toqNums * operations[j][1] + sum
      if(operations[j][1] % 2 === 1) {
        juftNums += toqNums
        toqNums = 0
      }
    }

    console.log(sum)
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
    var n = +readline();

    for(var i = 0; i < n; i++) {

      var opNums = readline().split(' ')[1];
      var arr = readline().split(' ').map(el => +el);

        var ops = []

        for(var j=0; j<opNums; j++) {
            ops.push(readline().split(' ').map(el => +el))
        }

     foo(arr, ops)
    }
}

function foo(arr, operations) {
  var juftNums = 0
  var toqNums = 0
  var sum = 0
//   var results = []

  for(var i = 0; i<arr.length; i++) {
    sum += arr[i]
    if(arr[i] % 2 === 0) juftNums++
    else toqNums++
  }

  for(var j = 0; j<operations.length; j++) {
    if(operations[j][0] === 0) {
      sum = juftNums * operations[j][1] + sum
      if(operations[j][1] % 2 === 1) {
        toqNums += juftNums
        juftNums = 0
      }
    }
    else {
      sum = toqNums * operations[j][1] + sum
      if(operations[j][1] % 2 === 1) {
        juftNums += toqNums
        toqNums = 0
      }
    }

    console.log(sum)
  }
}

var n = +readline();
for(var i = 0; i < n; i++) {
  var vars = readline().split(' ').map(item => +item);
  var arr = readline().split(' ').map(item => +item);
  var c1 = 0, c2 = 0, sum = 0;
  for(var k = 0; k < vars[0]; k++) {
    if(arr[k] % 2 === 1) {
      c1++;
    } else {
      c2++;
    }
    sum += arr[k];
  }
  for(var j = 0; j < vars[1]; j++) {
    var item = readline().split(' ').map(item => +item);
    if(item[0] === 0) {
      sum += c2 * item[1];
    } else {
      sum += c1 * item[1];
    }
    if(item[0] === 1 && c1 > 0 && item[1] % 2 === 1) {
      c2 = vars[1];
      c1 = 0;
    }
    if(item[0] === 0 && c2 > 0 && item[1] % 2 === 1) {
      c1 = vars[1];
      c2 = 0;
    }
    print(sum);
  }
}


var l = readline().split(' ')
var n = l[0]
var m = l[1]
var pc = l[2]
var ptb = false

var prl, ps, pe, tia
var zt = 0
var tc = {}

for (var i = 0; i < n; i++) {
  l = readline()
  if (ptb) {
    if (~l.indexOf(pc)) {
      tc[l[ps - 1]] = true
      tc[l[pe + 1]] = true
    } else {
      tia = l.substring(ps, pe + 1)
      ;[].forEach.call(tia, function (v) {tc[v] = true})
      break
    }
  } else if (~l.indexOf(pc)) {
    ptb = true
    ps = l.indexOf(pc)
    pe = l.lastIndexOf(pc)
    if (prl) {
      tia = prl.substring(ps, pe + 1)
      ;[].forEach.call(tia, function (v) {tc[v] = true})
    }
    tc[l[ps - 1]] = true
    tc[l[pe + 1]] = true
  }
  prl = l
}

delete tc['.']
delete tc[undefined]

print(Object.keys(tc).length)

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var data = tokenize(readline());
	var rowNum = parseInt(data[0]), colNum = parseInt(data[1]),
		presidentColor = data[2];

	var grid = [];
	for (var r = 0; r < rowNum; r += 1) {
		grid.push(trim(readline()));
	}

	var dr = [-1, 0, 1, 0], dc = [0, 1, 0, -1];

	var count = 0;
	var colors = { '.': true };
	colors[presidentColor] = true;

	for (var r = 0; r < rowNum; r += 1) {
		for (var c = 0; c < colNum; c += 1) {
			if (grid[r][c] != presidentColor) {
				continue;
			}
			for (var i = 0; i < 4; i += 1) {
				var R = r+dr[i], C = c+dc[i];
				if (R < 0 || R >= rowNum || C < 0 || C >= colNum) {
					continue;
				}
				if (colors[grid[R][C]] === undefined) {
					colors[grid[R][C]] = true;
					count += 1;
				}
			}
		}
	}

	print(count);
}

main();

// Generated by CoffeeScript 1.4.0
(function() {
  var board, c, count, done, h, i, input, j, k, m, n, neighbours, w, x, y, _i, _j, _k, _l, _m, _ref, _ref1, _ref2, _ref3, _ref4;

  input = readline().split(' ');

  _ref = [parseInt(input[0]), parseInt(input[1]), input[2]], n = _ref[0], m = _ref[1], c = _ref[2];

  board = [];

  for (i = _i = 1; 1 <= n ? _i <= n : _i >= n; i = 1 <= n ? ++_i : --_i) {
    board.push(readline());
  }

  done = false;

  _ref1 = [0, 0], i = _ref1[0], j = _ref1[1];

  for (i = _j = 0; 0 <= n ? _j < n : _j > n; i = 0 <= n ? ++_j : --_j) {
    for (j = _k = 0; 0 <= m ? _k < m : _k > m; j = 0 <= m ? ++_k : --_k) {
      if (board[i][j] === c) {
        done = true;
        break;
      }
    }
    if (done) {
      break;
    }
  }

  _ref2 = [1, 1], w = _ref2[0], h = _ref2[1];

  while (board[i][j + w] === c) {
    w++;
  }

  while (board[i + h] && board[i + h][j] === c) {
    h++;
  }

  neighbours = {};

  for (y = _l = i, _ref3 = i + h; i <= _ref3 ? _l < _ref3 : _l > _ref3; y = i <= _ref3 ? ++_l : --_l) {
    neighbours[board[y][j - 1] || '.'] = true;
    neighbours[board[y][j + w] || '.'] = true;
  }

  for (x = _m = j, _ref4 = j + w; j <= _ref4 ? _m < _ref4 : _m > _ref4; x = j <= _ref4 ? ++_m : --_m) {
    if (board[i - 1]) {
      neighbours[board[i - 1][x]] = true;
    }
    if (board[i + h]) {
      neighbours[board[i + h][x]] = true;
    }
  }

  count = 0;

  for (k in neighbours) {
    if (k !== '.') {
      count++;
    }
  }

  print(count);

}).call(this);

// Generated by CoffeeScript 1.10.0
(function() {
  var arr, c, finish, j, k, l, line, m, map, n, ref, ref1, ref2, ref3, ref4, ref5, start, wrapArray, x, y;

  ref = readline().split(" "), n = ref[0], m = ref[1], c = ref[2];

  arr = [];

  wrapArray = function(arr, el) {
    var i, length, results, tmp;
    length = arr[0].length;
    tmp = [];
    while (length--) {
      tmp.push(el);
    }
    arr.unshift(tmp.slice(0));
    arr.push(tmp.slice(0));
    results = [];
    for (i in arr) {
      arr[i].push(el);
      results.push(arr[i].unshift(el));
    }
    return results;
  };

  start = false;

  finish = {
    x: 0,
    y: 0
  };

  for (y = j = 1, ref1 = n; 1 <= ref1 ? j <= ref1 : j >= ref1; y = 1 <= ref1 ? ++j : --j) {
    line = readline().split("");
    if (line.indexOf(c) > -1) {
      if (!start) {
        start = {
          y: y - 1,
          x: line.indexOf(c)
        };
      }
      finish = {
        y: y - 1,
        x: line.lastIndexOf(c)
      };
    }
    arr.push(line);
  }

  wrapArray(arr, ".");

  map = {};

  for (y = k = ref2 = start.y + 1, ref3 = finish.y + 1; ref2 <= ref3 ? k <= ref3 : k >= ref3; y = ref2 <= ref3 ? ++k : --k) {
    for (x = l = ref4 = start.x + 1, ref5 = finish.x + 1; ref4 <= ref5 ? l <= ref5 : l >= ref5; x = ref4 <= ref5 ? ++l : --l) {
      map[arr[y - 1][x]] = 1;
      map[arr[y + 1][x]] = 1;
      map[arr[y][x - 1]] = 1;
      map[arr[y][x + 1]] = 1;
    }
  }

  delete map["."];

  delete map[c];

  write(Object.keys(map).length);

}).call(this);

//# sourceMappingURL=index.js.map

var s = readline().split(' ');
var r = parseInt(s[0]);
var c = parseInt(s[1]);
var PC = s[2];

var arr = []
for(var i=0; i<r; i++){
	arr.push( readline().split('') );
}

var _f = false;

var map ={

}
for(var i=0; i<r; i++){
	for(var j=0; j<c; j++){
		if(arr[i][j]==PC){

			map[ arr[i-1] && arr[i-1][j] || '.'] =
			map[ arr[i+1] && arr[i+1][j] || '.'] =
			map[ arr[i][j-1]||'.' ] =
			map[ arr[i][j+1]||'.' ] = true;
		}
	}
}

var ret = 0;
for(var k in map){
	if(k!=='.'&&k!==PC){
		ret++;
	}
}

print(ret);

var l = readline().split(' ')
var n = l[0]
var m = l[1]
var pc = l[2]
var ptb = false

var prl, ps, pe, tia
var zt = 0
var tc = {}

for (var i = 0; i < n; i++) {
  l = readline()
  if (ptb) {
    tc[l[ps - 1]] = true
    tc[l[pe + 1]] = true
    if (!~l.indexOf(pc)) {
      tia = l.substring(ps, pe + 1)
      ;[].forEach.call(tia, function (v) {tc[v] = true})
      break
    }
  } else if (~l.indexOf(pc)) {
    ptb = true
    ps = l.indexOf(pc)
    pe = l.lastIndexOf(pc)
    if (prl) {
      tia = prl.substring(ps, pe + 1)
      ;[].forEach.call(tia, function (v) {tc[v] = true})
    }
    tc[l[ps - 1]] = true
    tc[l[pe + 1]] = true
  }
  prl = l
}

delete tc['.']
delete tc[undefined]

print(Object.keys(tc).length)

// Generated by CoffeeScript 1.10.0
(function() {
  var arr, c, finish, j, k, l, len, len1, line, m, map, n, ref, ref1, ref2, ref3, start, wrapArray, x, y;

  ref = readline().split(" "), n = ref[0], m = ref[1], c = ref[2];

  arr = [];

  wrapArray = function(arr, el) {
    var i, length, results, tmp;
    length = arr[0].length;
    tmp = [];
    while (length--) {
      tmp.push(el);
    }
    arr.unshift(tmp.slice(0));
    arr.push(tmp.slice(0));
    results = [];
    for (i in arr) {
      arr[i].push(el);
      results.push(arr[i].unshift(el));
    }
    return results;
  };

  start = false;

  finish = {
    x: 0,
    y: 0
  };

  for (y = j = 1, ref1 = n; 1 <= ref1 ? j <= ref1 : j >= ref1; y = 1 <= ref1 ? ++j : --j) {
    line = readline().split("");
    if (line.indexOf(c) > -1) {
      if (!start) {
        start = {
          y: y - 1,
          x: line.indexOf(c)
        };
      }
      finish = {
        y: y - 1,
        x: line.lastIndexOf(c)
      };
    }
    arr.push(line);
  }

  wrapArray(arr, ".");

  map = {};

  ref2 = [start.y + 1, finish.y + 1];
  for (k = 0, len = ref2.length; k < len; k++) {
    y = ref2[k];
    ref3 = [start.x + 1, finish.x + 1];
    for (l = 0, len1 = ref3.length; l < len1; l++) {
      x = ref3[l];
      map[arr[y - 1][x]] = 1;
      map[arr[y + 1][x]] = 1;
      map[arr[y][x - 1]] = 1;
      map[arr[y][x + 1]] = 1;
    }
  }

  delete map["."];

  delete map[c];

  write(Object.keys(map).length);

}).call(this);

//# sourceMappingURL=index.js.map


(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var n = read.number();
    var a = read.arrNumber( ' ');

    var res = [];
    var last = 0;
    var resIndex = 1;
    var rIndex = n - 1;
    var lIndex = 0;

    if(a[rIndex] >  a[lIndex]) {
        last = a[lIndex];
        res.push('L');
        lIndex++;
    }
    else {
        last = a[rIndex];
        res.push('R');
        rIndex--;
    }

    for(var i = 1; i < n; i++) {
        if(a[rIndex] >  a[lIndex] && last < a[lIndex]) {
            res.push('L');
            last = a[lIndex];
            lIndex++;
        }
        else if (last < a[rIndex]) {
            last = a[rIndex];
            res.push('R');
            rIndex--;
        }
        else if( last < a[lIndex]) {
            res.push('L');
            last = a[lIndex];
            lIndex++;
        }
        else {
            break;
        }
    }

    print(res.length);
    print(res.join(''))
}());

let n;
let a = [];

const run = () => {
  if (a.length === 1) {
    console.log('1')
    console.log('L')
    return;
  }
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = -1;
  while (left <= right) {
    if (a[left] < a[right]) {
      if (last < a[left]) {
        result.push('L');
        last = a[left];
        ++left;
      } else if (last < a[right]) {
        result.push('R')
        last = a[right];
        --right;
      } else {
        break;
      }
    } else if (a[left] > a[right]) {
      if (last < a[right]) {
        result.push('R')
        last = a[right];
        --right;
      } else if (last < a[left]) {
        result.push('L');
        last = a[left];
        ++left;
      } else {
        break;
      }
    } else {
      if (last < a[left]) {
        result.push('L')
        last = a[left];
        ++left;
      }
      break;
    }
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  if (a.length === 1) {
    console.log(a.lenght)
    console.log('L')
    return;
  }
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = 0;
  while (left <= right) {
    if (left == right && last < a[left]) {
      result.push('L')
      break;
    }
    if (last < a[left] && a[left] < a[right]) {
      result.push('L')
      last = a[left];
      ++left;
      continue;
    }
    if (last < a[right] && a[right] < a[left]) {
      result.push('R')
      last = a[right];
      --right;
      continue;
    }
    break;
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  if (a.length === 1) {
    console.log('1')
    console.log('L')
    return;
  }
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = 0;
  while (left <= right) {
    if (left == right && last < a[left]) {
      result.push('L')
      break;
    }
    if (a[left] < a[right] && last < a[left]) {
      result.push('L')
      last = a[left];
      ++left;
      continue;
    }
    if (last < a[right]) {
      result.push('R')
      last = a[right];
      --right;
      continue;
    }
    break;
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  if (a.length === 1) {
    console.log('1')
    console.log('L')
    return;
  }
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = -1;
  while (left <= right) {
    if (last < a[left] || last < a[right]) {
      if (a[left] < a[right]) {
        result.push('L');
        last = a[left];
        ++left;
      } else if (a[left] > a[right]) {
        result.push('R')
        last = a[right];
        --right;
      } else {
        if (last < a[left]) {
          result.push('L')
          last = a[left];
          ++left;
        }
        break;
      }
    }
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last;
  while (left <= right) {
    if (a[left] < a[right]) {
      result.push('L')
      last = left;
      ++left;
    } else if (a[left] > a[right]) {
      result.push('R')
      last = right;
      --right;
    } else {
      if (left == right && last !== undefined && a[last] < a[left]) {
        result.push('L')
      }
      break;
    }
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  if (a === undefined) {
    a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  }
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = 0;
  while (left <= right) {
    if (left == right && last < a[left]) {
      result.push('L')
      break;
    }
    if (a[left] < a[right] && last < a[left]) {
      result.push('L')
      last = a[left];
      ++left;
      continue;
    }
    if (last < a[right]) {
      result.push('R')
      last = a[right];
      --right;
      continue;
    }
    break;
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  if (a.length === 1) {
    console.log('1')
    console.log('L')
    return;
  }
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = -1;
  while (left <= right) {
    if (last < a[left] || last < a[right]) {
      if (a[left] < a[right]) {
        result.push('L');
        ++left;
      } else if (a[left] > a[right]) {
        result.push('R')
        --right;
      } else {
        result.push('L')
        break;
      }
    }
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  if (a.length === 1) {
    console.log('1')
    console.log('L')
    return;
  }
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = -1;
  while (left <= right) {
    if (left == right && last < a[left]) {
      result.push('L')
      break;
    }
    if (a[left] < a[right] && last < a[left]) {
      result.push('L')
      last = a[left];
      ++left;
      continue;
    }
    if (last < a[right]) {
      result.push('R')
      last = a[right];
      --right;
      continue;
    }
    break;
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

let n;
let a = [];

const run = () => {
  if (a.length === 1) {
    console.log('1')
    console.log('L')
    return;
  }
  let left = 0;
  let right = a.length - 1;
  let result = [];
  let last = -1;
  while (left <= right) {
    if (last < a[left] || last < a[right]) {
      if (a[left] < a[right]) {
        result.push('L');
        last = a[left];
        ++left;
      } else if (a[left] > a[right]) {
        result.push('R')
        last = a[right];
        --right;
      } else {
        result.push('L')
        last = a[left];
        ++left;
        break;
      }
    }
  }
  console.log(result.length)
  console.log(result.join(''))
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false,
});

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  a = data.toString().trim().split(' ').filter(Boolean).map(Number);
  run();
  rl.close();
})

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var n = read.number();
    var a = read.arrNumber( ' ');

    var res = [];
    var last = 0;
    var resIndex = 1;
    var rIndex = n - 1;
    var lIndex = 0;

    if(a[rIndex] >  a[lIndex]) {
       last = a[lIndex];
        res.push('L');
        lIndex++;
    }
    else {
         last = a[rIndex];
        res.push('R');
        rIndex--;
    }

    for(var i = 1; i < n; i++) {
        if(a[rIndex] >  a[lIndex] && last < a[lIndex]) {
            res.push('L');
            last = a[lIndex];
            lIndex++;
        }
        else if (last < a[rIndex]) {
             last = a[rIndex];
            res.push('R');
            rIndex--;
        }
        else {
            break;
        }
    }

    print(res.length);
    print(res.join(''))
}());