In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.When a query appears server may react in three possible ways:   If server is free and query queue is empty, then server immediately starts to process this query.  If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue.  If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.

The first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue. Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1 ≤ ti, di ≤ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.

Print the sequence of n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or  - 1 if the corresponding query will be rejected.

NoteConsider the first sample.   The server will start to process first query at the moment 2 and will finish to process it at the moment 11.  At the moment 4 second query appears and proceeds to the queue.  At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected.  At the moment 11 server will finish to process first query and will take the second query from the queue.  At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue.  At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there.  Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue.  Server finishes to process query number 5 at the moment 22.

var tmp = readline().split(' ').map(Number);

var server = tmp[0];
var qlen = tmp[1];

var queue = [];
for(var i =0; i < server; i++)
{
    tmp = readline();
    queue.push(tmp.split(' ').map(Number));
}

var q = 0;
var qq = [];
var tm = queue[0][0];
var output = [];
for(var i = 0; i < server; i++)
{
    for(var j = 0; j < qq.length; j++)
    {
        if(qq[j] <= queue[i][0])
        {
            //var idx = qq.indexOf(qq[j]);
            qq.splice(j, 1);
            q--;
        } else {
            break;
        }
    }
    if(tm <= queue[i][0])
    {
        tm = queue[i][0] + queue[i][1];
        q = 0;
        write(tm);

    }else if(tm > queue[i][0] && q < qlen)
    {
        q++;
        qq.push(tm);
        tm += queue[i][1];
        write(tm);

    } else
    {
        write(-1);
    }
    write(' ');
}

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

var n = Number(input[0]),
    b = Number(input[1])

var endtime = 0,
    queue = []

var result = []

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

    var input = readline().split(' '),
        t = Number(input[0]),
        d = Number(input[1])

    var idx = findIndex(queue, t)

    if (t >= endtime) {
        endtime = t + d
        result.push(endtime)
    } else {
        if (queue.length - idx < b) {
            queue.push(endtime)
            endtime = endtime + d
            result.push(endtime)
        } else {
            result.push(-1)
        }
    }

}

function findIndex (array, value) {
    var from = 0, to = array.length
    while (to > from + 1) {
        var i = from + ((to - from) >>> 1)
        if (array[i] > value) {
            to = i
        } else {
            from = i
        }
    }

  return array[from] > value ? from : to
}

print(result.join(' ') + '\n')

var input = readline().split(' '), n = +input[0], b = +input[1], p = 0, q = [], result = [];

for (var i = 0; i < n; i++) {
	var query = readline().split(' ').map(Number);
	for (var j = 0; j < q.length; j++) {
		if (q[j] <= query[0]) {
			q.splice(j, 1);
		} else {
			break;
		}
	}
	if (p <= query[0]) {
		p = query[0] + query[1];
		q = [];
	} else if (q.length < (b + 1)) {
		p = p + query[1];
	} else {
		//print(-1);
		result.push(-1);
		continue;
	}
	query[2] = p;
	q.push(p);
	// print(p);
	result.push(p);
}

print(result.join(' '));

var readInt = () => parseInt(readline())
var readIntArray = () => readline().split(' ').map(item => parseInt(item))
function range(a, b) {
    var res = []
    for (var i = a; i <= b; i++) {
        res.push(i)
    }
    return res
}
var inputData = readIntArray()
var n = inputData[0]
var b = inputData[1]
var res = []

var q = []
var h = 0

var s = 0
var f = 0
for (var i = 0; i < n; i++) {
    var inputData = readIntArray()
    var t = inputData[0]
    var d = inputData[1]

    s = t
    while (t > f) {
        if (q.length - h > 0) {
            qh = q[h++] //pop
            f += qh.v
            res[qh.i] = f
        }
        else break;
    }
    if (t >= f) {
        f = t
        if (q.length - h > 0) {
            qh = q[h++] //pop
            f += qh.v
             res[qh.i] = f

            if (q.length-h+1 <= b)
            {
                q.push({i:i, v:d})
            } else res[i] = -1

        }
        else {
            f += d
            res[i] = f
        }
    }
    else {
        if (q.length-h+1 <= b)
        {
            q.push({i:i, v:d})
        } else res[i] = -1
    }
}
while (q.length > h) {
        qh = q[h++] //pop
        f += qh.v
        res[qh.i] = f
}
print(res.join(' '))

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
    input: process.stdin,
    // input: fs.createReadStream('src/day4/0.input1.json'),
    output: process.stdout,
    terminal: false,
});

let lines = [];

/**
 * Time complexity:
 * Space complexity:
 */
rl.on('line', function (line) {
    lines.push(line.trim().split(' ').map(Number));
}).on('close', () => {
    const length = lines[0][0];
    const maxQueue = lines[0][1];
    let freeMoment = 0;
    let momentQueue = [];

    const ableToPutInQueue = (t, queue) => {
        let l = 0,
            r = queue.length - 1;
        let pivot;

        if (l === r) {
            // l === r === 0
            return maxQueue >= 1;
        }

        if (r - l === 1) {
            if (t >= queue[l]) {
                return maxQueue >= 1;
            } else {
                return maxQueue >= 2;
            }
        }

        while (true) {
            pivot = Math.floor((l + r) / 2);
            if (queue[pivot] === t) {
                return queue.length - pivot - 1 <= maxQueue;
            }

            if (r - l === 1) {
                if (queue[l] > t) {
                    return queue.length - l <= maxQueue;
                }
                return queue.length - pivot - 1 <= maxQueue;
            }

            if (queue[pivot] >= t) {
                r = pivot;
            } else {
                l = pivot;
            }
        }
    };
    // const ableToPutInQueue = (t, queue) => {
    //     let count = 0;
    //     for (let i = queue.length - 1; i >= 0; i--) {
    //         if (queue[i] > t) {
    //             count++;
    //         }
    //         if (count > maxQueue) {
    //             return false;
    //         }
    //     }
    //     return true;
    // };

    for (let i = 1; i <= length; i++) {
        let t = lines[i][0];
        let d = lines[i][1];
        // is server free --> process
        // is server busy, and queue is not full --> push into the queue
        if (t > freeMoment) {
            freeMoment = t + d;
        } else if (ableToPutInQueue(t, momentQueue)) {
            freeMoment = freeMoment + d;
        } else {
            console.log(-1);
            continue;
        }
        console.log(freeMoment);
        momentQueue.push(freeMoment);
    }
});

var readline = require('readline');

var input = [];

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

// rl.prompt();

rl.on('line', function(cmd) {
  input.push(cmd);
});

// const string = `5 1
// 2 9
// 4 8
// 10 9
// 15 2
// 19 1`;

// input.push('6 1');
// input.push('2 9');
// input.push('4 8');
// input.push('10 9');
// input.push('15 2');
// input.push(' 19 1');
// input.push('10008348907 1');

rl.on('close', function(cmd) {
  let inputArray = input;
  // inputArray = input.split('\n');

  const infoQueries = inputArray[0]
    .split(' ')
    .filter(x => x)
    .map(s => parseInt(s, 10));

  inputArray.shift();

  const queries = inputArray
    .map(i =>
      i
        .split(' ')
        .filter(x => x)
        .map(s => parseInt(s, 10))
    )
    // .filter(q => q[0] <= 1000000000 && q[1] <= 1000000000)
    .map(q => ({
      startTime: q[0],
      processingTime: q[1],
      processedTime: 0
    }));

  const numberOfQueries = Math.min(infoQueries[0], queries.length);
  const queueSize = infoQueries[1];

  let timestamp = queries[0].startTime + queries[0].processingTime;
  queries[0].processedTime = timestamp;
  const queue = [];

  queue.push(timestamp);

  for (let i = 1; i < numberOfQueries; i++) {
    const query = queries[i];

    // Remove all processed queries
    while (queue.length && query.startTime >= queue[0]) {
      queue.shift();
    }

    if (query.startTime >= timestamp) {
      timestamp = query.startTime + query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
      continue;
    }

    if (queue.length > queueSize) {
      // console.log('exceeded!');
      query.processedTime = -1;
    } else {
      timestamp += query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
    }

    // console.log('queue', queue);
  }

  console.log(
    `${queries
      .map(x => x.processedTime)
      .filter(x => x)
      .join(' ')}`
  );

  process.exit(0);
});

var readline = require('readline');

var input = [];

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

// rl.prompt();

rl.on('line', function(cmd) {
  input.push(cmd);
});

// const string = `5 1
// 2 9
// 4 8
// 10 9
// 15 2
// 19 1`;

// input.push('6 1');
// input.push('2 9');
// input.push('4 8');
// input.push('10 9');
// input.push('15 2');
// input.push(' 19 1');
// input.push('10008348907 1');

rl.on('close', function(cmd) {
  let inputArray = input;
  // inputArray = input.split('\n');

  const infoQueries = inputArray[0]
    .split(' ')
    .filter(x => x)
    .map(s => parseInt(s, 10));

  inputArray.shift();

  const queries = inputArray
    .map(i =>
      i
        .split(' ')
        .filter(x => x)
        .map(s => parseInt(s, 10))
    )
    // .filter(q => q[0] <= 1000000000 && q[1] <= 1000000000)
    .map(q => ({
      startTime: q[0],
      processingTime: q[1],
      processedTime: 0
    }));

  const numberOfQueries = Math.min(infoQueries[0], queries.length);
  const queueSize = infoQueries[1];

  let timestamp = queries[0].startTime + queries[0].processingTime;
  queries[0].processedTime = timestamp;
  const queue = [];

  queue.push(timestamp);

  for (let i = 1; i < numberOfQueries; i++) {
    const query = queries[i];

    // Remove all processed queries
    while (queue.length && query.startTime >= queue[0]) {
      queue.shift();
    }

    if (query.startTime >= timestamp) {
      timestamp = query.startTime + query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
      continue;
    }

    if (queue.length > queueSize) {
      // console.log('exceeded!');
      query.processedTime = -1;
    } else {
      timestamp += query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
    }

    // console.log('queue', queue);
  }

  s = queries
      .map(x => x.processedTime)
      .filter(x => x)
      .join(' ');
  console.log(s)

  process.exit(0);
});

var tmp = readline().split(' ').map(Number);

var server = tmp[0];
var qlen = tmp[1];

var queue = [];
for(var i =0; i < server; i++)
{
    tmp = readline();
    queue.push(tmp.split(' ').map(Number));
}

var q = 0;
var qq = [];
var tm = queue[0][0];
var output = [];
for(var i = 0; i < server; i++)
{
    for(var j = 0; j < qq.length; j++)
    {
        if(qq[j] <= queue[i][0])
        {
            //var idx = qq.indexOf(qq[j]);
            qq.splice(j, 1);
            q--;
        } else {
            break;
        }
    }
    if(tm <= queue[i][0])
    {
        tm += queue[i][1];
        q = 0;
        write(tm);

    }else if(tm > queue[i][0] && q < qlen)
    {
        q++;
        qq.push(tm);
        tm += queue[i][1];
        write(tm);

    } else
    {
        write(-1);
    }
    write(' ');
}
//print(output.join(' '));

var input = readline().split(' ')
  , n = +input[0]
  , b = +input[1]
  , p = 0
  , q = []
  , result = [];

for (var i = 0; i < n; i++ ) {
    var query = readline().split(' ').map(Number);
	for (var j = 0; j < q.length; j++) {
		if (q[0][2] <= query[0]) {
			q.splice(j, 1);
		} else {
			break;
		}
	}
    if (p <= query[0]) {
        p = query[0] + query[1];
		q = [];
    } else if (q.length < (b + 1)) {
        p = p + query[1];
    } else {
        //print(-1);
        result.push(-1);
        continue;
    }
    query[2] = p;
    q.push(query);
    // print(p);
    result.push(p);
}

print(result.join(' '));

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
    input: process.stdin,
    // input: fs.createReadStream('src/day4/0.input1.json'),
    output: process.stdout,
    terminal: false,
});

let lines = [];

/**
 * Time complexity:
 * Space complexity:
 */
rl.on('line', function (line) {
    lines.push(line.trim().split(' ').map(Number));
}).on('close', () => {
    const length = lines[0][0];
    const maxQueue = lines[0][1];
    let freeMoment = 0;
    let momentQueue = [];

    const ableToPutInQueue = (t, queue) => {
        let l = 0,
            r = queue.length - 1;
        let pivot;

        if (l === r) {
            // l === r === 0
            return maxQueue >= 1;
        }

        if (r - l === 1) {
            if (t >= queue[l]) {
                return maxQueue >= 1;
            } else {
                return maxQueue >= 2;
            }
        }

        while (true) {
            pivot = Math.floor((l + r) / 2);
            if (queue[pivot] === t || r - l === 1) {
                return queue.length - pivot - 1 <= maxQueue;
            }

            if (queue[pivot] >= t) {
                r = pivot;
            } else {
                l = pivot;
            }
        }
    };
    // const ableToPutInQueue = (t, queue) => {
    //     let count = 0;
    //     for (let i = queue.length - 1; i >= 0; i--) {
    //         if (queue[i] > t) {
    //             count++;
    //         }
    //         if (count > maxQueue) {
    //             return false;
    //         }
    //     }
    //     return true;
    // };

    for (let i = 1; i <= length; i++) {
        let t = lines[i][0];
        let d = lines[i][1];
        // is server free --> process
        // is server busy, and queue is not full --> push into the queue
        if (t > freeMoment) {
            freeMoment = t + d;
        } else if (ableToPutInQueue(t, momentQueue)) {
            freeMoment = freeMoment + d;
        } else {
            console.log(-1);
            continue;
        }
        console.log(freeMoment);
        momentQueue.push(freeMoment);
    }
});


You're given an array of $$$n$$$ integers between $$$0$$$ and $$$n$$$ inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is $$$[0, 2, 2, 1, 4]$$$, you can choose the second element and replace it by the MEX of the present elements  — $$$3$$$. Array will become $$$[0, 3, 2, 1, 4]$$$.You must make the array non-decreasing, using at most $$$2n$$$ operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them. –An array $$$b[1 \ldots n]$$$ is non-decreasing if and only if $$$b_1 \le b_2 \le \ldots \le b_n$$$.The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:  The MEX of $$$[2, 2, 1]$$$ is $$$0$$$, because $$$0$$$ does not belong to the array.  The MEX of $$$[3, 1, 0, 1]$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the array, but $$$2$$$ does not.  The MEX of $$$[0, 3, 1, 2]$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the array, but $$$4$$$ does not. It's worth mentioning that the MEX of an array of length $$$n$$$ is always between $$$0$$$ and $$$n$$$ inclusive.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 1000$$$) — length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$) — elements of the array. Note that they don't have to be distinct. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$.

For each test case, you must output two lines: The first line must contain a single integer $$$k$$$ ($$$0 \le k \le 2n$$$)  — the number of operations you perform. The second line must contain $$$k$$$ integers $$$x_1, \ldots, x_k$$$ ($$$1 \le x_i \le n$$$), where $$$x_i$$$ is the index chosen for the $$$i$$$-th operation. If there are many solutions, you can find any of them. Please remember that it is not required to minimize $$$k$$$.

NoteIn the first test case, the array is already non-decreasing ($$$2 \le 2 \le 3$$$).Explanation of the second test case (the element modified by each operation is colored in red):   $$$a = [2, 1, 0]$$$ ; the initial MEX is $$$3$$$.  $$$a = [2, 1, \color{red}{3}]$$$ ; the new MEX is $$$0$$$.  $$$a = [\color{red}{0}, 1, 3]$$$ ; the new MEX is $$$2$$$.  The final array is non-decreasing: $$$0 \le 1 \le 3$$$. Explanation of the third test case:   $$$a = [0, 7, 3, 1, 3, 7, 7]$$$ ; the initial MEX is $$$2$$$.  $$$a = [0, \color{red}{2}, 3, 1, 3, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, 1, \color{red}{4}, 7, 7]$$$ ; the new MEX is $$$5$$$.  $$$a = [0, 2, 3, 1, \color{red}{5}, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, \color{red}{4}, 5, 7, 7]$$$ ; the new MEX is $$$1$$$.  The final array is non-decreasing: $$$0 \le 2 \le 3 \le 4 \le 5 \le 7 \le 7$$$.

function solve() {
   var n = Number(read());
   var c = [];
   for (var i = 0; i < 2 * n + 10; i++) {
      c.push(0);
   }
   var a = read().split(' ').map(function(v) {
      var res = Number(v);
      c[res]++;
      return res;
   });
   var ans = [];
   var x;
   for (var i = 0; i < n; i++) {
      for (var j = i + 1; j < n; j++) {
         if (a[i] !== a[j]) {
            continue;
         }
         ans.push(j + 1);
         x = 0;
         while(c[x]) {
            x++;
         }
         c[x]++;
         c[a[j]]--;
         a[j] = x;
      }
   }
   x = 0;
   while(c[x]) {
      x++;
   }
   while (true) {
      if (!x || a[x - 1] === x) {
         var i = 0;
         while(i < n && a[i] === i + 1) {
            i++;
         }
         if (i === n) {
            break;
         }
         if (!x) {
            ans.push(i + 1);
            var temp = i;
            x = a[temp];
            a[temp] = 0;
         } else {
            x = i + 1;
         }
      } else {
         ans.push(x);
         var temp = x;
         x = a[temp - 1];
         a[temp - 1] = temp;
      }
   }
   write(ans.length);
   write(ans.join(' '));
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

function solve() {
   var n = Number(read());
   var c = [];
   var noZero = true;
   for (var i = 0; i < 2 * n + 10; i++) {
      c.push(0);
   }
   var a = read().split(' ').map(function(v) {
      var res = Number(v);
      if (res === 0) {
         noZero = false;
      }
      c[res]++;
      return res;
   });
   var ans = [];
   if (noZero) {
      ans.push(1);
      a[0] = 0;
   }
   var x;
   for (var i = 0; i < n; i++) {
      for (var j = i + 1; j < n; j++) {
         if (a[i] !== a[j]) {
            continue;
         }
         ans.push(j + 1);
         x = 0;
         while(c[x]) {
            x++;
         }
         c[x]++;
         c[a[j]]--;
         a[j] = x;
      }
   }
   x = n;
   while (x) {
      if (a[x - 1] === x) {
         x--;
         continue;
      }
      ans.push(x);
      x = a[x - 1];
   }
   write(ans.length);
   write(ans.join(' '));
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}


You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \le |s| \le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.

For each test case, print the resulting string $$$s$$$ with $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.

NoteIn the first test case, both $$$\operatorname{AB}(s) = 0$$$ and $$$\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\operatorname{AB}(s) = 1$$$ and $$$\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$.

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
	for(i = 1; i <= t; i++){
	    var a = lines[i].split('');
	    a[0] = a[a.length - 1];
	    var ans = '';
	    for(j = 0; j < a.length; j++){
	        ans += a[j];
	    }
	    console.log(ans);
	}
});

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 () {
	let t = rn();
	while (t--) {
		let s = rl();
		let n = s.length;

		let ans = s;
		if (s[0] != s[n - 1])
			ans = s[n - 1] + s.slice(1);

		console.log(ans);
	}
}

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 () {
	let t = rn();
	while (t--) {
		let s = rl();
		let n = s.length;

		let abcnt = bacnt = 0;
		for (let i = 0; i < n - 1; i++) {
			if (s[i] != s[i + 1]) {
				if (s[i] == 'a') abcnt++;
				else bacnt++;
			}
		}

		ans = s.split('');
		if (abcnt != bacnt)
			ans[n - 1] = s[n - 1] == 'a' ? 'b' : 'a';

		console.log(ans.join(''));
	}
}

// // Importing the module
// const readline = require("readline-sync");

// // Enter the number
// let s = String(readline.question());
// let array = [];
// let ab = 0;
// let ba = 0;

// if (s.length === 1) {
//     return;
// }

// else if (s.length === 2) {
//     if (s[0] === 'a' && s[1] === 'b') {
//         s = 'aa';
//     } else if (s[0] === 'b' && s[1] === 'a') {
//         s = 'aa';
//     }
// }

// for (let i = 0; i < s.length; ++i) {
//     if (s[i] === 'a' && s[i + 1] === 'b') {
//         ab++;
//     } else if (s[i] === 'b' && s[i + 1] === 'a') {
//         ba++
//     }
//     array.push(s[i]);
// }

// if (ab !== ba) {
//     let occurence = array.indexOf('a');

//     array[occurence] = 'b';
// }

process.stdin.setEncoding('utf-8');
const readline = require('readline'); // reading line

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

let count = -1
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) {
        main()
        process.exit(0)
    }
})

function solve(str) {
    if (str[str.length - 1] === str[0]) {
        console.log(str)
    } else {
        const res = str.split('')
        res.splice(0, 1, str[str.length - 1])
        console.log(res.join(''))
    }
}

function main() {
    for (let i = 0; i < inputArr.length; i++) {
        solve(inputArr[i]);
    }
}

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 str = lines[l++]
        output[i] = solve(str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(str) {
    let s1 = 0
    let s2 = 0
    for (let i = 1; i < str.length; i++) {
        const s = str[i - 1] + str[i]
        if (s === 'ab') s1++
        if (s === 'ba') s2++
    }
// console.log(s1, s2)
    if (s1 === s2) return str
    let d = Math.abs(s1 - s2)
    let a = 'a' // a -> b
    let b = 'b'
    if (s1 < s2) {
        a = 'b'
        b = 'a'
    }
    const ans = []
    for (let i = 0; i < str.length; i++) {
        if (d && str[i] === a && (!i || str[i - 1] !== b)) {
            ans.push(b)
            d--
        } else {
            ans.push(str[i])
        }
    }
    return ans.join('')
}

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

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

let count = -1
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) {
        main()
        process.exit(0)
    }
})

function solve(str) {
    if (str[str.length - 1] === str[0]) {
        console.log(str)
    } else {
        const res = str.split('')
        res.splice(0, 1, str[str.length - 1])
        console.log(res.join(''))
    }
}

function main() {
    for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])
}

//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 if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
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 t = nextInt();
	while(hasNext()){
		var s = nextCharArray();
		var N = s.length;
		if(s[0] != s[N - 1]){
			s[0] = s[N - 1];
		}
		myout(myconv(s, 0));
	}
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
	for(i = 1; i <= t; i++){
	    var a = lines[i].split('');
	    console.log(a);
	}
});


The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:There are space-separated non-empty words of lowercase and uppercase Latin letters.There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.You should write a program that will find minimal width of the ad.

The first line contains number k (1 ≤ k ≤ 105). The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 106 characters.

NoteHere all spaces are replaced with dots.In the first example one of possible results after all word wraps looks like this:garage.for.sa-leThe second example:Edu-ca-tion-al.Ro-unds.are.so.fun

  var k, tmp, word, ad;

  var read = function() {
    k = parseInt(readline());
    // var ad = readline().split(/ |-/);
    tmp = readline();
  };
  read();
  var split = function() {
    word = '';
    ad = [];
    for(var i = 0; i < tmp.length; i += 1) {
      if(tmp[i] === ' ' || tmp[i] === '-') {
        ad.push(word);
        word = '';
      } else {
        word += tmp[i];
      }
    }
    if(word.length > 0) {
      ad.push(word);
    }
  };
  split();
  var test = function(m) {
    var ls = 0;
    var ll = 0;
    var idx = 0;
    while(idx < n) {
      if(ls > k) {
        ls = Infinity;
        break;
      }
      var wl = ad[idx].length + (idx === n - 1 ? 0 : 1);
      if(wl > m) {
        ls = Infinity;
        break;
      }
      if(wl + ll > m) {
        ls += 1;
        ll = 0;
      } else {
        ll += wl;
        idx += 1;
      }
    }
    return ls < k;
  }
  var l = 1;
  var r = 1000001;
  var n = ad.length;
  var bs = function() {
    while(l <= r) {
      var m = (l + r) / 2 | 0;
      if(test(m)) {
        r = m - 1;
      } else {
        l = m + 1;
      }
    }
  };
  bs();
  print(l);

  var k = parseInt(readline());
  var ad = readline().split(/ |-/);

  var l = 1;
  var r = 1000500;
  var n = ad.length;
  while(l <= r) {
    var m = (l + r) / 2 | 0;
    var ls = 0;
    var ll = 0;
    var idx = 0;
    while(idx < n) {
      var wl = ad[idx].length + (idx === n - 1 ? 0 : 1);
      if(wl > m) {
        lines = Infinity;
        break;
      }
      if(wl + ll > m) {
        ls += 1;
        ll = 0;
      } else {
        ll += wl;
        idx += 1;
      }
    }
    if(ls < k) {
      r = m - 1;
    } else {
      l = m + 1;
    }
  }
  print(l);

  var k = parseInt(readline());
  var ad = readline().split(/ |-/);

  var l = 1;
  var r = 1000001;
  var n = ad.length;
  while(l <= r) {
    var m = (l + r) / 2 | 0;
    var ls = 0;
    var ll = 0;
    var idx = 0;
    while(idx < n) {
      if(ls > m) {
        ls = -Infinity;
        break;
      }
      var wl = ad[idx].length + (idx === n - 1 ? 0 : 1);
      if(wl > m) {
        ls = Infinity;
        break;
      }
      if(wl + ll > m) {
        ls += 1;
        ll = 0;
      } else {
        ll += wl;
        idx += 1;
      }
    }
    if(ls < k) {
      r = m - 1;
    } else {
      l = m + 1;
    }
  }
  print(l);

  var k = parseInt(readline());
  var ad = readline().split(/ |-/);

  var l = 1;
  var r = 1000001;
  var n = ad.length;
  while(l <= r) {
    var m = (l + r) / 2 | 0;
    var ls = 0;
    var ll = 0;
    var idx = 0;
    while(idx < n) {
      var wl = ad[idx].length + (idx === n - 1 ? 0 : 1);
      if(wl > m || ls > m) {
        ls = Infinity;
        break;
      }
      if(wl + ll > m) {
        ls += 1;
        ll = 0;
      } else {
        ll += wl;
        idx += 1;
      }
    }
    if(ls < k) {
      r = m - 1;
    } else {
      l = m + 1;
    }
  }
  print(l);


Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:  a < b < c;  a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has  groups of three.Help Xenia, find the required partition or else say that it doesn't exist.

The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.

If the required partition exists, print  groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  const len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const map = {};
  const limit = Math.floor(len / 3);
  let [count124, count126, count136] = [0, 0, 0];
  for (let value of arr) {
    map[value] = (map[value] || 0) + 1;
  }

  if (
    map[1] >= limit &&
    ((map[1] && map[2] && map[4]) || (map[1] && map[2] && map[6]) || (map[1] && map[3] && map[6]))
  ) {
    if (map[1] > 0 && map[2] > 0 && map[4] > 0) {
      count124 = Math.min(map[1], map[2], map[4]);
      map[1] -= count124;
      map[2] -= count124;
      map[4] -= count124;
    }
    if (map[1] > 0 && map[2] > 0 && map[6] > 0) {
      count126 = Math.min(map[1], map[2], map[6]);
      map[1] -= count126;
      map[2] -= count126;
      map[6] -= count126;
    }
    if (map[1] > 0 && map[3] > 0 && map[6] > 0) {
      count136 = Math.min(map[1], map[3], map[6]);
      map[1] -= count136;
      map[3] -= count136;
      map[6] -= count136;
    }
    if (count124 + count126 + count136 === limit) {
      for (let i = 0; i < count124; i++) console.log(`${1} ${2} ${4}`);
      for (let i = 0; i < count126; i++) console.log(`${1} ${2} ${6}`);
      for (let i = 0; i < count136; i++) console.log(`${1} ${3} ${6}`);
    } else {
      console.log(-1);
    }
  } else {
    console.log(-1);
  }
}

var am = readline()
var nums = readline().split(' ')
var c1 = c2 = c3 = c4 = c6 = 0
for(var i=0; i<am; i++){
    switch(nums[i]){
        case 1:
            c1+=1;
    }
}
print(c1)

var num = readline()
var line = readline().split(' ')
print(num)


Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.

The first line of the input contains a single integer n (3 ≤ n ≤ 100 000). Each of the next n lines contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.

Print three distinct integers on a single line — the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.

NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture.   Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).


The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).  If the wind blows to the east, the boat will move to (x + 1, y).  If the wind blows to the south, the boat will move to (x, y - 1).  If the wind blows to the west, the boat will move to (x - 1, y).  If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?

The first line contains five integers t, sx, sy, ex, ey (1 ≤ t ≤ 105,  - 109 ≤ sx, sy, ex, ey ≤ 109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).

If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).

NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination.

//constrains
//  * 1 <= t <= ^5
//  * -10^9 <= direction < 10^9

//Input
var firstLine = "5 0 0 1 1"; var direction = "SESNW";           // 4
// var firstLine = "10 5 3 3 6"; var direction = "NENSWESNEE";     // -1
// var firstLine = "19 172106364 468680119 172106365 468680119"; var direction = "SSEEESSSESESWSEESSS";
//              13
// var firstLine = "19 172106364 468680119 172106363 468680119"; var direction = "SSEEESSSESESWSEESSS";
// var firstLine = "1 0 0 0 -1"; var direction = "S";           // 4

var firstLine = readline(); var direction = readline();

retorno = eval(firstLine, direction);

//Solution
function eval(firstLine, direction){
    var tmp = firstLine.split(" ").map(function(x){ return parseInt(x)});
    var t = tmp[0];
    var start = {
        x: tmp[1],
        y: tmp[2]    };
    var end = {
        x: tmp[3],
        y: tmp[4]    };
    write( timeToReach(t, start, end, direction) );
    //console.log(timeToReach(t, start, end, direction));
};

function timeToReach(t, s, e, direction){
    var ap = {
        x: s.x,
        y: s.y};

    // console.log("s.x: " + s.x + "    s.y: " + s.y + "        e.x: " + e.x + "    e.y: " + e.y);
    // console.log("\nap.x: " + ap.x + "    ap.y: " + ap.y);
    // console.log("\nDx: " + Math.abs(e.x - s.x) + "    Dy: " + Math.abs(e.y - s.y) + "\n\n" );

    var totalCount = -1;
    for(var i = 0 ; i < t ; i++){
        //console.log(direction[i]);
        switch(direction[i]){
            case "N": // north direction
                if( Math.abs(e.y - (ap.y + 1)) < Math.abs(e.y - ap.y) ){
                    ap.y ++;
                };
                break;

            case "S": //south direction
                if( Math.abs(e.y - (ap.y - 1)) < Math.abs(e.y - ap.y) ){
                    ap.y --;
                };
                break;

            case "E": // east direction
                if( Math.abs(e.x - (ap.x + 1)) < Math.abs(e.x - ap.x) ){
                    ap.x++;
                };
                break;

            case "W": //west direction
            //console.log("entró");
                if( Math.abs(e.x - (ap.x - 1)) < Math.abs(e.x - ap.x) ){
                    //console.log("entró al if");
                    ap.x--;
                };
                break;
        };
        //console.log(i + "    ap.x: " + ap.x + "    ap.y: " + ap.y);
        // console.log("(e.x == ap.x) && (e.y == ap.y): " + ( (e.x == ap.x) && (e.y == ap.y) ) );
        if( (e.x == ap.x) && (e.y == ap.y) ){
            totalCount = i + 1;
            break;
        };
    };
    return totalCount;
};

function main()
{
    var tmp = readline().split(" ").map(function (x) { return parseInt(x); });
    var t = tmp[0],
        sx = tmp[1],
        sy = tmp[2],
        ex = tmp[3],
        ey = tmp[4];
    tmp = readline();
    var ans = 0;
    if ( sx > ex )
    {
        var i;
        var cnt = sx - ex;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "W" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    else if ( sx < ex )
    {
        var i;
        var cnt = ex - sx;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "E" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    if ( sy > ey )
    {
        var i;
        var cnt = sy - ey;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "S" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    else if ( sy < ey )
    {
        var i;
        var cnt = ey - sy;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "N" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    print(ans);
}

main();

function main(){
    var tmp = readline().split(" ").map(function (x) { return parseInt(x); });
    var t = tmp[0],
        sx = tmp[1],
        sy = tmp[2],
        ex = tmp[3],
        ey = tmp[4];
    tmp = readline();
    var ans = 0;
    if ( sx > ex ){
        var i;
        var cnt = sx - ex;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "W" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    else if ( sx < ex ){
        var i;
        var cnt = ex - sx;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "E" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    if ( sy > ey ){
        var i;
        var cnt = sy - ey;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "S" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    else if ( sy < ey ){
        var i;
        var cnt = ey - sy;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "N" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    print(ans);
}

main();

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}

function main() {
  const [len, sx, sy, ex, ey] = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const str = readLine();
  const [diffX, diffY] = [ex - sx, ey - sy];
  let [x, countX, y, countY] = ["", Math.abs(diffX), "", Math.abs(diffY)];

  if (diffX > 0) x = "E";
  else x = "W";
  if (diffY > 0) y = "N";
  else y = "S";

  let map = {};
  for (let i = 0; i < len; i++) {
    const char = str[i];

    map[char] = (map[char] || 0) + 1;

    if (diffX === 0 && map[y] >= countY) {
      console.log(i + 1);
      return;
    } else if (diffY === 0 && map[x] >= countX) {
      console.log(i + 1);
      return;
    } else if (map[x] >= countX && map[y] >= countY) {
      console.log(i + 1);
      return;
    }
  }

  console.log(-1);
}


Hongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.

The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece. The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space. It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.

Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.

NoteFor the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................

var n = parseInt( readline().split( " " )[0], 10 );
var pieceParts = new Set();
var line;
while( line = readline() ) {
  if ( line.indexOf( "X" ) > -1 ) {
    pieceParts.add(line);
  }
}
print( pieceParts.size === 1 ? "YES" : "NO" );

var canMakeRectangle = function( piece ) {
  var i,
    j,
    row,
    withinRowFragment,
    captureFragment,
    fragmentLength,
    rectangleSide,
    noChance;
  /*
    This implementation check whether piece is a rectangle.
  */
  verticalBreakCaptured = false;
  for ( i = 0; i < piece.length; ++i ) {
    withinRowFragment = false;
    captureFragment = false;
    fragmentLength = 0;
    row = piece[ i ];
    for ( j = 0; j < row.length; ++j ) {
      if ( row[ j ] ) {
        if ( !withinRowFragment ) {
          if ( captureFragment ) {
            noChance = true;
            break;
          }
          withinRowFragment = true;
        }
        ++fragmentLength;
        captureFragment = true;
      } else {
        withinRowFragment = false;
      }
    }
    if ( noChance ) {
      break;
    } else if ( typeof rectangleSide === "undefined" &&  fragmentLength !== 0) {
      rectangleSide = fragmentLength;
    } else if  ( typeof rectangleSide !== "undefined" && fragmentLength !== 0 && fragmentLength !== rectangleSide ) {
      noChance = true;
      break;
    }
  }
  return !noChance;
};

var piece = [];
var input = readline().split( " " ).map( i => parseInt( i, 10 ) );
var n = input[ 0 ];
var m = input[ 1 ];
for ( var i = 0; i < n; ++i ) {
  piece.push( readline().split( "" ).map( i => i === "X" ) );
}
print( canMakeRectangle( piece ) ? "YES" : "NO" );


Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array.  The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.

Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).

var arrayLength = readline();
var input = {};
readline().split(" ").map((entry, index) => input[entry] = index);

var searchLength = readline();
var searchFor = readline().split(" ");

counterA = 0;
counterB = 0;
var index;
for (var j = 0; j < searchLength; j++) {
    index = input[searchFor[j]];
   counterA += index + 1;
   counterB += arrayLength - index;

}
print(counterA + " " + counterB);

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]] !== 0) {
            totalBeginChecks += ((i + 1) * queryFlag[list[i]]);
            totalEndChecks += ((list.length - i) * queryFlag[list[i]]);
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(1000000).fill(0);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] += 1;
    }
    console.log(solve().join(' '));
});

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]] !== 0) {
            totalBeginChecks += ((i + 1) * queryFlag[list[i]]);
            totalEndChecks += ((list.length - i) * queryFlag[list[i]]);
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(100001).fill(0);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] += 1;
    }
    console.log(solve().join(' '));
});

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len = +readLine();
  const items = readLine()
    .split(" ")
    .reduce((obj, n, index) => {
      obj[n] = index;
      return obj;
    }, {});
  const queryLen = +readLine();
  const queries = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let [person1, person2] = [0, 0];

  for (query of queries) {
    const position = items[query] + 1;
    if (position > 0) {
      person1 += position;
      person2 += len - position + 1;
    }
  }
  console.log(`${person1} ${person2}`);
}

//Effective Approach

const {EOL} = require('os');

let inp = '';

process.stdin.on('data', c => inp += c);

process.stdin.on('end', () => {
    let lines = inp.split(EOL);

    let dex = {};
    for(let i = 1; i <= 100000; i++)  {
    	dex[i] = -1;
    }

    let n = lines[1].split(' ').map(c => +c);

    for(let i = 0; i < n.length; i++)  {
    	dex[n[i]] = i;
    }

    let c = lines[3].split(' ').map(r => +r);

    let tota = 0, totb = 0;
    for(let i = 0; i < c.length; i++)  {
    	if(dex[c[i]] != -1)  {
    		tota += dex[c[i]] + 1;
    		totb += n.length - dex[c[i]];
    	}
    }

    process.stdout.write(tota + ' ' + totb);

    return;
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function multiply(a, b) {
	a = a.toString(10).split('').reverse();
	b = b.toString(10).split('').reverse();

	if (a.length < b.length) {
		[a, b] = [b, a];
	}

	let res = Array(a.length + b.length).fill(0);
	for (let i = 0, lb = b.length; i < lb; ++i) {
		let carry = 0;
		let scarry = 0;
		for (let j = 0, la = a.length; j < la; ++j) {
			let m = b[i] * a[j];
			m += carry;

			if (m > 9) {
				let [c, d] = m.toString(10).split('');
				res[i + j] += (scarry >> 0) + (d >> 0);
				carry = c >> 0;
			} else {
				res[i + j] += (scarry >> 0) + m;
				carry = 0;
			}

			if (res[i + j] > 9) {
				let [c, d] = res[i + j].toString(10).split('');
				res[i + j] = d >> 0;
				scarry = c;
			} else {
				scarry = 0;
			}
		}
		if (carry > 0) res[a.length + i] = carry;
		if (scarry > 0) res[a.length + i] = scarry;
	}

	res.reverse();
	let mulVal = '';
	let flag = false;
	res.forEach(d => {
		if (!flag && d !== 0) flag = true;
		if (flag) mulVal += d;
	});
	return mulVal;
}

function main() {
	let n = readLine() >> 0;
	let nums = readLine()
		.split(' ')
		.map(x => x >> 0);
	let m = readLine() >> 0;
	let b = readLine()
		.split(' ')
		.map(x => x >> 0);

	let query = {};
	b.forEach(x => (query[x] = (query[x] || 0) + 1));

	let i = 0;
	let l = 0,
		r = 0;
	while (i < n) {
		if (query[nums[i]] !== undefined && query[nums[i]] > 0) {
			l += (i + 1) * query[nums[i]];
			r += (n - i) * query[nums[i]];
		}
		i++;
	}
	console.log(l, r);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
// function main() {
//     let n = parseInt(readLine());
//     let mainArray = readLine().split(' ').map(Number);
//     let m = parseInt(readLine());
//     let qureyArray = readLine().split(' ').map(Number);
//     let Vasyacount = 0;
//     for (let i = 0; i < qureyArray.length; i++) {
//         for (let j = 0; j < mainArray.length; j++) {
//             Vasyacount++;
//             if (qureyArray[i] === mainArray[j]) {
//                 break;
//             }
//         }
//     }

//     let Petyas_count = 0;
//     for (let i = 0; i < qureyArray.length; i++) {
//         for (let j = mainArray.length - 1; j >= 0; j--) {
//             Petyas_count++;
//             if (qureyArray[i] === mainArray[j]) {
//                 break;
//             }
//         }
//     }

//     console.log(Vasyacount, Petyas_count);
// }

function main() {
    let n = parseInt(readLine());
    let mainArray = readLine().split(' ').map(Number);
    let m = parseInt(readLine());
    let qureyArray = readLine().split(' ').map(Number);

    let indexArray = new Array(n);
    for (let i = 0; i < n; i++) {
        let test = mainArray[i];
        indexArray[test] = i;
    }
    let Vasya = 0;
    // console.log(indexArray);
    // console.log(indexArray[qureyArray[2]] + 1);

    for (let i = 0; i < m; i++) {
        Vasya = Vasya + indexArray[qureyArray[i]] + 1;
    }
    let Petya = 0;
    for (let i = 0; i < m; i++) {
        Petya = Petya + (n - indexArray[qureyArray[i]]);
    }
    console.log(Vasya, Petya);
}

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]]) {
            totalBeginChecks += i + 1;
            totalEndChecks += list.length - i;
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(100000).fill(false);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] = true;
    }
    console.log(solve().join(' '));
});

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]] !== 0) {
            totalBeginChecks += ((i + 1) * queryFlag[list[i]]);
            totalEndChecks += ((list.length - i) * queryFlag[list[i]]);
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(100000).fill(0);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] += 1;
    }
    console.log(solve().join(' '));
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function multiply(a, b) {
	a = a.toString(10).split('').reverse();
	b = b.toString(10).split('').reverse();

	if (a.length < b.length) {
		[a, b] = [b, a];
	}

	let res = Array(a.length + b.length).fill(0);
	for (let i = 0, lb = b.length; i < lb; ++i) {
		let carry = 0;
		let scarry = 0;
		for (let j = 0, la = a.length; j < la; ++j) {
			let m = b[i] * a[j];
			m += carry;

			if (m > 9) {
				let [c, d] = m.toString(10).split('');
				res[i + j] += (scarry >> 0) + (d >> 0);
				carry = c >> 0;
			} else {
				res[i + j] += (scarry >> 0) + m;
				carry = 0;
			}

			if (res[i + j] > 9) {
				let [c, d] = res[i + j].toString(10).split('');
				res[i + j] = d >> 0;
				scarry = c;
			} else {
				scarry = 0;
			}
		}
		if (carry > 0) res[a.length + i] = carry;
		if (scarry > 0) res[a.length + i] = scarry;
	}

	res.reverse();
	let mulVal = '';
	let flag = false;
	res.forEach(d => {
		if (!flag && d !== 0) flag = true;
		if (flag) mulVal += d;
	});
	return mulVal;
}

function main() {
	let n = readLine() >> 0;
	let nums = readLine()
		.split(' ')
		.map(x => x >> 0);
	let m = readLine() >> 0;
	let b = readLine()
		.split(' ')
		.map(x => x >> 0);

	let query = {};
	b.forEach(x => (query[x] = (query[x] || 0) + 1));

	let i = 0;
	let l = 0,
		r = 0;
	while (i < n) {
		if (query[nums[i]] !== undefined && query[nums[i]] > 0) {
			l += i + 1;
			r += n - i;
		}
		i++;
	}
	console.log(l, r);
}


Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.So imagine Monocarp got recommended $$$n$$$ songs, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th song had its predicted rating equal to $$$p_i$$$, where $$$1 \le p_i \le n$$$ and every integer from $$$1$$$ to $$$n$$$ appears exactly once. In other words, $$$p$$$ is a permutation.After listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string $$$s$$$, such that $$$s_i=0$$$ means that he disliked the $$$i$$$-th song, and $$$s_i=1$$$ means that he liked it.Now the service has to re-evaluate the song ratings in such a way that:  the new ratings $$$q_1, q_2, \dots, q_n$$$ still form a permutation ($$$1 \le q_i \le n$$$; each integer from $$$1$$$ to $$$n$$$ appears exactly once);  every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all $$$i, j$$$ such that $$$s_i=1$$$ and $$$s_j=0$$$, $$$q_i>q_j$$$ should hold). Among all valid permutations $$$q$$$ find the one that has the smallest value of $$$\sum\limits_{i=1}^n |p_i-q_i|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$.Print the permutation $$$q_1, q_2, \dots, q_n$$$. If there are multiple answers, you can print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of songs. The second line of each testcase contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the permutation of the predicted ratings. The third line contains a single string $$$s$$$, consisting of $$$n$$$ characters. Each character is either a $$$0$$$ or a $$$1$$$. $$$0$$$ means that Monocarp disliked the song, and $$$1$$$ means that he liked it. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a permutation $$$q$$$ — the re-evaluated ratings of the songs. If there are multiple answers such that $$$\sum\limits_{i=1}^n |p_i-q_i|$$$ is minimum possible, you can print any of them.

NoteIn the first testcase, there exists only one permutation $$$q$$$ such that each liked song is rating higher than each disliked song: song $$$1$$$ gets rating $$$2$$$ and song $$$2$$$ gets rating $$$1$$$. $$$\sum\limits_{i=1}^n |p_i-q_i|=|1-2|+|2-1|=2$$$.In the second testcase, Monocarp liked all songs, so all permutations could work. The permutation with the minimum sum of absolute differences is the permutation equal to $$$p$$$. Its cost is $$$0$$$.

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 () {
	let T = rn();
	while (T--) {
		const n = rn();
		const p = rna();
		const s = rl();

		let cnt = 0;
		for (const c of s) cnt += c == '0';

		const ans = [];
		const used = new Set();
		for (let i = 0; i < n; i++) {
			if (s[i] == '0' && p[i] <= cnt || s[i] == '1' && p[i] > cnt) {
				ans[i] = p[i];
				used.add(p[i]);
			}
		}

		let l = 1, r = n;
		for (let i = 0; i < n; i++) {
			if (!ans[i]) {
				if (s[i] == '0') {
					while (used.has(l)) l++;
					ans[i] = l;
					l++;
				} else {
					while(used.has(r)) r--;
					ans[i] = r;
					r--;
				}
			}
		}

		console.log(ans.join(' '));
	}
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const p = (await getLine()).split(' ').map(num => parseInt(num));
        const s = await getLine();
        const res = new Array(n);
        let ptr = n - 1;
        const order = new Array(n);
        for(let i = 0; i < n; i++) {
            order[p[i] - 1] = i + 1;
        }
        for(let i = n - 1; i >= 0; i--) {
            if (s.charAt(order[i] - 1) === '1') {
                res[ptr] = order[i];
                ptr--;
            }
        }

        for(let i = n - 1; i >= 0; i--) {
            if (s.charAt(order[i] - 1) === '0') {
                res[ptr] = order[i];
                ptr--;
            }
        }

        for(let i = 0; i < n; i++) {
            order[res[i] - 1] = i + 1;
        }

        console.log(order.join(' '));
    }
}

solve();

const solve = (arr,str)=>{
     let zero = [],one = [];
     for(let i=0;i<str.length;i++){
          if(str[i]==="0") zero.push(arr[i]);
          else one.push(arr[i]);
     }
     if(!zero.length || !one.length) return arr.join(" ");
     zero.sort((a,b)=>a-b);
     one.sort((a,b)=>a-b);
     let cnt1 = 1;
     let cnt2 = zero.length+1;
     let obj = {},res = "";
     for(let i=0;i<zero.length;i++) obj[zero[i]] = cnt1++;
     for(let i=0;i<one.length;i++) obj[one[i]] = cnt2++;
     for(let i=0;i<arr.length;i++) res+=obj[arr[i]]+" ";
     return res;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = (readline().trim().split(" ").map(cur=>parseInt(cur)));
       let str = readline().trim();
       console.log(solve(arr,str));
  }
}
main();

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 = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        const str = lines[l++]
        output[i] = solve(n, arr, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, str) {
    const liked = []
    const unliked = []
    for (let i = 0; i < arr.length; i++) {
        if (str[i] === '1') {
            liked.push([i, arr[i]])
        } else {
            unliked.push([i, arr[i]])
        }
    }
    liked.sort((a, b) => a[1] - b[1])
    unliked.sort((a, b) => a[1] - b[1])
    // console.log(liked, unliked)
    const ans = Array(n)
    for (let i = 0; i < arr.length; i++) {
        if (i < unliked.length) {
            ans[unliked[i][0]] = i + 1
        } else {
            ans[liked[i - unliked.length][0]] = i + 1
        }
    }
    return ans.join(' ')
}

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 () {
	let T = rn();
	while (T--) {
		const n = rn();
		const p = rna();
		const s = rl();

		let cnt = 0;
		for (const c of s) cnt += c == '1';

		const ans = [];
		const used = new Set();
		for (let i = 0; i < n; i++) {
			if (s[i] == '0' && p[i] <= cnt || s[i] == '1' && p[i] > cnt) {
				ans[i] = p[i];
				used.add(p[i]);
			}
		}

		let l = 1, r = n;
		for (let i = 0; i < n; i++) {
			if (!ans[i]) {
				if (s[i] == '0') {
					while (used.has(l)) l++;
					ans[i] = l;
					l++;
				} else {
					while(used.has(r)) r--;
					ans[i] = r;
					r--;
				}
			}
		}

		console.log(ans.join(' '));
	}
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const p = (await getLine()).split(' ').map(num => parseInt(num));
        const s = await getLine();
        const res = new Array(n);
        let ptr = n - 1;
        for(let i = n - 1; i >= 0; i--) {
            if (s.charAt(p[i] - 1) === '1') {
                res[ptr] = p[i];
                ptr--;
            }
        }

        for(let i = n - 1; i >= 0; i--) {
            if (s.charAt(p[i] - 1) === '0') {
                res[ptr] = p[i];
                ptr--;
            }
        }

        console.log(res.join(' '));
    }
}

solve();


John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$) — the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$.

Print the rank of Thomas Smith. Thomas's id is $$$1$$$.

NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$.

function main(){
    var n = +readline();
    var a = [];

    for(var i = 0;i < n;i++){
        a.push(readline().split(' ').reduce((sum,o) => sum + +o, 0));
    }
    var t = a[0];

    print(a.sort((s,q)=>q-s).indexOf(+t) +1);
}

main();

var n = +readline();
var total = [];
var id = 1;

for (var i=0; i<n; i++){
	var p = readline().split(' ').map(Number);
	total[i] = p[0] + p[1] + p[2] + p[3];
}

for (var j=1; j<n; j++){
	if (total[0] < total[j]) id++;
}

print (id);

var n = readline()
var res = n;
var p = readline().split(" ")
var tomas = p.map((a) => Number(a)).reduce((a, b) => a + b, 0);

for (var i = 1; i < n; i++) {
    var p = readline().split(" ")
    var point = p.map((a) => Number(a)).reduce((a, b) => a + b, 0);
    (tomas >= point)?res--:0;
}

print(res)

function main() {
  const is = new Scanner();
  const n = is.nextInt();
  const scores = new Array(n);
  for (let i = 0; i < n; i += 1) {
    scores[i] = is.nextArray(Number);
    scores[i] = [scores[i].reduce((accum, item) => accum + item, 0), i + 1];
  }
  scores.sort((a, b) => {
    if (a[0] === b[0])
      return a[1] - b[1];
    return b[0] - a[0];
  });

  for (let i = 0; i < n; i += 1) {
    if (scores[i][1] === 1) {
      console.log(i + 1);
      break;
    }
  }

}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

const vIn = [];
let itIn = 0;
const getNext = () => vIn[itIn++];
const getInt = () => parseInt(getNext(), 10);
const forEachN = (n, cb, flagInt = false) => {
  const nextItIn = itIn + n;
  const fn = flagInt ? getInt : getNext;
  while (itIn !== nextItIn) cb(fn());
};

class SolveProblemClass {
  constructor() {
  }

  solveAll() {
    const n = getInt();
    const v = [];
    for (let i = 0; i < n ; i++) {
      let sum = 0;
      forEachN(4, (x) => {
        sum += x;
      }, true);
      v.push({ i, sum });
    }
    v.sort((a, b) => {
      if (b.sum > a.sum) return 1;
      if (b.sum < a.sum) return -1;
      return a.i - b.i;
    });
    const pos = v.reduce((i, obj, it) => {
      if (obj.i === 0) return it + 1;
      return i;
    }, -1);
    console.log(pos);
  }
}

const processData = (input) => {
  input.split('\n').forEach(line => {
    // vIn.push(line);
    line.split(' ').forEach(item => { vIn.push(item); });
  });
};

const solveP = new SolveProblemClass();
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", (input) => {
  _input += input;
});
process.stdin.on("end", () => {
  processData(_input);
  solveP.solveAll();
});

const readline = require('readline')
const rl = readline.createInterface({input: process.stdin})

let n, sums = [], numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        n = parseInt(line)
    } else {
        const currentSum = line.split(' ').map(x => parseInt(x)).reduce((a, x) => a + x)
        sums.push(currentSum)
    }
}).on('close', () => {
    const thomasSum = sums.shift()
    const thomasRank = 1 + sums.filter(x => x > thomasSum).length
    process.stdout.write(`${thomasRank}`)
})

var readline = require('readline');

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

buf = '';
ctr = 0;
var n;
var m = 0;
var lst = [];
var split;

rl.on('line', function (line) {
	split = line.trim().split(' ').map(x => parseInt(x))
	if( split.length == 1){
		n = parseInt(line);
	}
	else {

		lst[m] = {idx: m+1, val: split.reduce( (full, curr) => full + curr )}
		m++;
		n--;
		if(n == 0){
			var srt = lst.sort( (a, b) => {
				return a.val != b.val ? b.val - a.val : a.idx - b.idx
			})
			srt.forEach( ({idx}, id) => idx == 1 ? console.log(id+1) : 0 )
			// console.log(srt)
			process.exit()
		}
	}
});

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let me = 0;
let ans = 1;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const sum = arr.reduce((a, b) => a + b, 0);

  if (c === 1) {
    me = sum;
  }

  if (sum > me) {
    ans++;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});

let input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
    let n = parseInt(input[0]);

    let data = []; let t_pos = 1, t_points = 0;
    for(let i = 0; i < n; i++){
        let sum = 0; input[i+1].split(' ').forEach( j => sum+= parseInt(j) );
        data.push(sum);
        if(i == 0)
            t_points = sum;
        else {
            if(sum > t_points)
                t_pos++;
        }
    }
    console.log(t_pos);
});

function main(){
    var n = +readline();
    var a = [];
    var t = readline().split(' ').reduce((sum,o) => +sum + +o, 0)

    for(var i = 0;i< n-1;i++){
        a.push(readline().split(' ').reduce((sum,o) => +sum + +o, 0));
        print(a[i])
    }
    var r = a.sort((s,q)=>q-s).indexOf(t);
    if(r > -1){
        print(r + 1);
    }
    else{
        if(t > a[0]){
            print(1);
        }
        else{
            print(n);
        }
    }

}

main()

function main(){
    var n = +readline();
    var a = [];
    var t = readline().split(' ').reduce((sum,o) => sum + +o, 0)

    for(var i = 0;i< n-1;i++){
        a.push(readline().split(' ').reduce((sum,o) => sum + +o, 0));
    }
    var r = a.sort((s,q)=>q-s).indexOf(+t);

    if(r > -1){
        print(r + 1);
    }
    else{
        if(t > a[0] || !a.length){
            print(1);
        }
        else{
            print(n);
        }
    }
}

main()

function main(){
    var n = +readline();
    var a = [];
    var t = readline().split(' ').reduce((sum,o) => +sum + +o, 0)

    for(var i = 0;i< n-1;i++){
        a.push(readline().split(' ').reduce((sum,o) => +sum + +o, 0));
    }
    var r = a.sort((s,q)=>q-s).indexOf(t);
    if(r > -1){
        print(r + 1);
    }
    else{
        if(t > a[0]){
            print(1);
        }
        else{
            print(n);
        }
    }

}

main()

var readline = require('readline');

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

rl.on('line', function (line) {
  console.log(2);
  process.exit()
});

var readline = require('readline');

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

buf = '';
ctr = 0;
var n;
var m = 0;
var lst = [];
var split;

rl.on('line', function (line) {
	split = line.trim().split(' ').map(x => parseInt(x))
	if( split.length == 1){
		n = parseInt(line);
	}
	else {

		lst[m] = {idx: m+1, val: split.reduce( (full, curr) => full + curr )}
		m++;
		n--;
		if(n == 0){
			var srt = lst.sort( (a, b) => {
				return a.val != b.val ? b.val - a.val : b.idx - a.idx
			})
			srt.forEach( ({idx}, id) => idx == 1 ? console.log(id+1) : 0 )
			// console.log(srt)
			process.exit()
		}
	}
});

process.stdin.resume()
process.stdin.setEncoding("ascii");
buf = ''
ctr = 0
var n
var m = 0
var lst = []
var split
process.stdin.on('data', input => {
	split = input.trim().split(' ').map(x => parseInt(x))
	if( split.length == 1){
		n = parseInt(input);
	}
	else {

		lst[m] = {idx: m+1, val: split.reduce( (full, curr) => full + curr )}
		m++;
		n--;
		if(n == 0){
			var srt = lst.sort( (a, b) => {
				return a.val != b.val ? b.val - a.val : b.idx - a.idx
			})
			// console.log(srt)
			srt.forEach( ({idx}, id) => idx == 1 ? console.log(id+1) : 0 )
			process.exit(0)
		}
	}
})
// process.stdin.on("end", () => {
// 	console.log(buf)
// })

// process.stdin.resume()
process.stdin.setEncoding("ascii");
buf = ''
ctr = 0
var n
var m = 0
var lst = []
var split
process.stdin.on('data', input => {
	split = input.trim().split(' ').map(x => parseInt(x))
	if( split.length == 1){
		n = parseInt(input);
	}
	else {

		lst[m] = {idx: m+1, val: split.reduce( (full, curr) => full + curr )}
		m++;
		n--;
		if(n == 0){
			var srt = lst.sort( (a, b) => {
				return a.val != b.val ? b.val - a.val : b.idx - a.idx
			})
			srt.forEach( ({idx}, id) => idx == 1 ? console.log(id+1) : 0 )
			// console.log(srt)
			process.exit()
		}
	}
})
// process.stdin.on("end", () => {
// 	var lid
// 	srt.forEach( ({idx}, id) => idx == 1 ? lid=id+1: 0 )
// 	console.log(lid)
// 	process.exit(lid)
// })

process.stdin.resume()
process.stdin.setEncoding("ascii");
buf = ''
ctr = 0
var n
var m = 0
var lst = []
var split
process.stdin.on('data', input => {
	split = input.trim().split(' ').map(x => parseInt(x))
	if( split.length == 1){
		n = parseInt(input);
	}
	else {

		lst[m] = {idx: m+1, val: split.reduce( (full, curr) => full + curr )}
		m++;
		n--;
		if(n == 0){
			var srt = lst.sort( (a, b) => {
				return a.val != b.val ? b.val - a.val : b.idx - a.idx
			})
			srt.forEach( ({idx}, id) => idx == 1 ? console.log(id+1) : 0 )
			console.log(srt)
			process.exit(0)
		}
	}
})
// process.stdin.on("end", () => {
// 	var lid
// 	srt.forEach( ({idx}, id) => idx == 1 ? lid=id+1: 0 )
// 	console.log(lid)
// 	process.exit(lid)
// })


The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.

The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.

NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.

const rl = require("readline").createInterface({
	input: process.stdin, //or fileStream
  	output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
const readln = async () => (await it.next()).value;
const writeln = (value) => process.stdout.write(`${value}\n`);
const run = async (proc)  => { await proc(); rl.close(); };

const query = async (b,e) =>
{
	if (b==e) return 0;
	writeln(`? ${b} ${e}`);
	return parseInt(await readln());
};

const outputAns = async (a) =>
{
	writeln(`! ${a}`);
};

run(async () =>
{
	const n = parseInt(await readln());
	let b = 1;
	let e = n;
	let s = await query(b,e);

	while(b!=e)
	{
		let m = Math.floor((b+e)/2);
		if (s<=m)
		{
			if ((await query(1,m))==s)
			{
				e = m;
			}
			else
			{
				b = m+1;
			}
		}
		else
		{
			if ((await query(m+1,n))==s)
			{
				b = m+1;
			}
			else
			{
				e = m;
			}
		}
	}

	outputAns(b);
});

const rl = require("readline").createInterface({
	input: process.stdin, //or fileStream
  	output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
const readln = async () => (await it.next()).value;
const writeln = (value) => process.stdout.write(`${value}\n`);
const run = async (proc)  => { await proc(); rl.close(); };

const query = async (b,e) =>
{
	if (b==e) return 0;
	writeln(`? ${b} ${e}`);
	return parseInt(await readln());
};

const outputAns = async (a) =>
{
	writeln(`! ${a}`);
};

run(async () =>
{
	const n = parseInt(await readln());
	let b = 1;
	let e = n;
	let s = await query(b,e);

	while(b!=e)
	{
		let m = Math.floor((b+e)/2);
		if (s<=m)
		{
			if ((await query(1,m))==s)
			{
				e = m;
			}
			else
			{
				b = m+1;
			}
		}
		else
		{
			if ((await query(m,n))==s)
			{
				b = m;
			}
			else
			{
				e = m-1;
			}
		}
	}

	outputAns(b);
});

const rl = require("readline").createInterface({
	input: process.stdin, //or fileStream
  	output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
const readln = async () => (await it.next()).value;
const writeln = (value) => process.stdout.write(`${value}\n`);
const run = async (proc)  => { await proc(); rl.close(); };

const query = async (b,e) =>
{
	writeln(`? ${b} ${e}`);
	return parseInt(await readln());
};

const outputAns = async (a) =>
{
	writeln(`! ${a}`);
};

run(async () =>
{
	const n = parseInt(await readln());
	let b = 1;
	let e = n;
	let s = await query(b,e);

	while(b!=e)
	{
		let m = Math.floor((b+e)/2);
		if (s<=m)
		{
			if ((await query(1,m))==s)
			{
				e = m;
			}
			else
			{
				b = m+1;
			}
		}
		else
		{
			if ((await query(m,n))==s)
			{
				b = m;
			}
			else
			{
				e = m-1;
			}
		}
	}

	outputAns(b);
});

let gotN = false;
let clarif = false;
let n,b,e,lastA;

process.stdin.on("data",(c) =>
{
	if (!gotN)
	{
		n = parseInt(c);
		gotN = true;
		b = 1;
		e = n;
		calc();
	}
	else
	{
		let a = parseInt(c);
		if (clarif)
		{
			if (a==lastA)
			{
				e = lastA-1;
			}
			else
			{
				b = lastA+1;
			}
			clarif = false;
			calc();
		}
		else
		{
			if (a==b)
			{
				b++;
				calc();
			}
			else if (a==e)
			{
				e--;
				calc();
			}
			else
			{
				clarif = true;
				lastA = a;
				process.stdout.write(`? ${b} ${a}\n`);
			}
		}
	}
});

function calc()
{
	if (b==e)
	{
		process.stdout.write(`! ${b}\n`);
	}
	else
	{
		process.stdout.write(`? ${b} ${e}\n`);
	}
}