This is the hard version of the problem. The only difference is the constraints on $$$n$$$ and $$$k$$$. You can make hacks only if all versions of the problem are solved.You have a string $$$s$$$, and you can do two types of operations on it:   Delete the last character of the string.  Duplicate the string: $$$s:=s+s$$$, where $$$+$$$ denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly $$$k$$$ that can be obtained by doing these operations on string $$$s$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a prefix of $$$b$$$, but $$$a\ne b$$$;  In the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5\cdot 10^5$$$) — the length of the original string $$$s$$$ and the length of the desired string. The second line contains the string $$$s$$$, consisting of $$$n$$$ lowercase English letters.

Print the lexicographically smallest string of length $$$k$$$ that can be obtained by doing the operations on string $$$s$$$.

NoteIn the first test, it is optimal to make one duplication: "dbcadabc" $$$\to$$$ "dbcadabcdbcadabc".In the second test it is optimal to delete the last $$$3$$$ characters, then duplicate the string $$$3$$$ times, then delete the last $$$3$$$ characters to make the string have length $$$k$$$."abcd" $$$\to$$$ "abc" $$$\to$$$ "ab" $$$\to$$$ "a" $$$\to$$$ "aa" $$$\to$$$ "aaaa" $$$\to$$$ "aaaaaaaa" $$$\to$$$ "aaaaaaa" $$$\to$$$ "aaaaaa" $$$\to$$$ "aaaaa".

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 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);
}

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


Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде. В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.

Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.

ПримечаниеВ первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.

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
    }
}


The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king. The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.

If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.

function toInt(v){ return parseInt(v); }
var _l = readline().split(' ');
var x0 = parseInt(_l[0]);
var y0 = parseInt(_l[1]);
var x1 = parseInt(_l[2]);
var y1 = parseInt(_l[3]);
var n = parseInt(readline());

var path = [];
var m = {};
for(var i=0; i<n; i++){
	_l = readline().split(' ').map(toInt);
	var x=_l[0];
	for(var y=_l[1]; y<=_l[2]; y++){
		path[i]=[x,y];
		m[''+x+'-'+y] = true;
	}
}

var q = [];
q.push([x0, y0]);
var _i=0;
var x = [-1,-1,-1, 1, 1, 1, 0, 0];
var y = [-1, 0, 1,-1, 0, 1,-1, 1];
out: for(var step=1; step<=1E5; step++){
	for(var l=q.length; _i<l; _i++){
		var now = q[_i];
		for(var i=0; i<8; i++){
			var xx = now[0]+x[i];
			var yy = now[1]+y[i];
			if(xx==x1&&yy==y1){
				print(step);
				break out;
			}
			if( m[''+xx+'-'+yy ] ){
				m[''+xx+'-'+yy ]=false;
				q.push([xx, yy]);
			}
		}
	}
}
if(step>1E5){
	print(-1)
}


You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.

'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)
  }
}

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);
    }
})

/*
* 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);
    }
}

"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);
  }
}

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);
  }
}


Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $$$a$$$ and $$$b$$$. It is known that $$$|b| \leq |a|$$$, that is, the length of $$$b$$$ is at most the length of $$$a$$$.The Cossack considers every substring of length $$$|b|$$$ in string $$$a$$$. Let's call this substring $$$c$$$. He matches the corresponding characters in $$$b$$$ and $$$c$$$, after which he counts the number of positions where the two strings are different. We call this function $$$f(b, c)$$$.For example, let $$$b = 00110$$$, and $$$c = 11000$$$. In these strings, the first, second, third and fourth positions are different.Vus the Cossack counts the number of such substrings $$$c$$$ such that $$$f(b, c)$$$ is even.For example, let $$$a = 01100010$$$ and $$$b = 00110$$$. $$$a$$$ has four substrings of the length $$$|b|$$$: $$$01100$$$, $$$11000$$$, $$$10001$$$, $$$00010$$$.  $$$f(00110, 01100) = 2$$$; $$$f(00110, 11000) = 4$$$; $$$f(00110, 10001) = 4$$$; $$$f(00110, 00010) = 1$$$. Since in three substrings, $$$f(b, c)$$$ is even, the answer is $$$3$$$.Vus can not find the answer for big strings. That is why he is asking you to help him.

The first line contains a binary string $$$a$$$ ($$$1 \leq |a| \leq 10^6$$$) — the first string. The second line contains a binary string $$$b$$$ ($$$1 \leq |b| \leq |a|$$$) — the second string.

NoteThe first example is explained in the legend.In the second example, there are five substrings that satisfy us: $$$1010$$$, $$$0101$$$, $$$1111$$$, $$$1111$$$.

"use strict";

var A = readline().split('').map(value => +value);
var B = readline().split('').map(value => +value);

var sumA = 0;
var sumB = 0;
for (var i = 0; i < B.length; ++i) {
    sumA += A[i];
    sumB += B[i];
}

var result = 0;
for (var i = B.length, j = 0; i <= A.length; ++i, ++j) {
    if (sumA%2 === sumB%2) {
        ++result;
    }
    sumA = (sumA - A[j]) + A[i];
}

write(result);


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.

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

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();

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)

// 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 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


The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers. All these integers are distinct, each value from $$$1$$$ to $$$n$$$ appears in the sequence exactly once.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[2, 1, 5, 4, 3]$$$ the answer is $$$4$$$ (you take $$$2$$$ and the sequence becomes $$$[1, 5, 4, 3]$$$, then you take the rightmost element $$$3$$$ and the sequence becomes $$$[1, 5, 4]$$$, then you take $$$4$$$ and the sequence becomes $$$[1, 5]$$$ and then you take $$$5$$$ and the sequence becomes $$$[1]$$$, the obtained increasing sequence is $$$[2, 3, 4, 5]$$$).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. All these integers are pairwise distinct.

In the first line of the output print $$$k$$$ — the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.

NoteThe first example is described in the problem statement.

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();
})

(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(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(''))
}());