Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.

The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000).

In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.

'use strict'

let lll = readline().split(' ').map(v => parseInt(v))
let N = lll[0]
let H = lll[1]
let R = lll[2]
let h = H
let d = 0

let ss = []

while (lll = readline()) {
  ss.push(lll.split(' ').map(v => parseInt(v)))
}

let fail = false
let t = 0
let uss = []
let i = 0
while (h > 0) {
  h = Math.min(h - d + R, H)
  let bs = gbs()
  let bsi = ss.indexOf(bs)
  if (bs && h > 0) {
    d += bs[1]
    bs[0] = -1
    uss.push([t, bsi + 1])
  } else if (h == H) {
    fail = true
    break
  }
  t++
}

if (fail) {
  print('NO')
} else {
  print('YES')
  print(t - 1 + ' ' + uss.length)
  uss.forEach(v => print(v.join(' ')))
}

function gbs () {
  let lim = h / H * 100
  return ss.filter(s => s[0] >= lim)
    .sort((a, b) => b[1] - a[1])
    [0]
}

'use strict'

let lll = readline().split(' ').map(v => parseInt(v))
let N = lll[0]
let H = lll[1]
let R = lll[2]
let h = H
let d = 0

let ss = []

while (lll = readline()) {
  ss.push(lll.split(' ').map(v => parseInt(v)))
}

let fail = false
let t = 0
let uss = []
let i = 0
while (h > 0 && !fail) {
  h -= d
  h = Math.min(h + R, H)
  let bs = gbs()
  let bsi = ss.indexOf(bs)
  if (bs) {
    d += bs[1]
    bs[0] = -1
    uss.push([t, bsi + 1])
  } else if (h == H) {
    fail = true
  }
  t++
}

if (fail) {
  print('NO')
} else {
  print('YES')
  print(t - 1 + ' ' + uss.length)
  uss.forEach(v => print(v.join(' ')))
}

function gbs () {
  let lim = h / H * 100
  return ss.filter(s => s[0] >= lim)
    .sort((a, b) => b[1] - a[1])
    [0]
}

'use strict'

let lll = readline().split(' ').map(v => parseInt(v))
let N = lll[0]
let H = lll[1]
let R = lll[2]
let h = H
let d = 0

let ss = []

while (lll = readline()) {
  ss.push(lll.split(' ').map(v => parseInt(v)))
}

let fail = false
let t = 0
let uss = []
let i = 0
while (true) {
  h -= d
  if (h < 0) break
  h = Math.min(h + R, H)
  let bs = gbs()
  let bsi = ss.indexOf(bs)
  if (bs) {
    d += bs[1]
    bs[0] = -1
    uss.push([t, bsi + 1])
  } else if (h == H) {
    fail = true
    break
  }
  t++
}

if (fail) {
  print('NO')
} else {
  print('YES')
  print(t + ' ' + uss.length)
  uss.forEach(v => print(v.join(' ')))
}

function gbs () {
  let lim = h / H * 100
  return ss.filter(s => s[0] >= lim)
    .sort((a, b) => b[1] - a[1])
    [0]
}


This is an interactive problem.Vasya and Petya are going to play the following game: Petya has some positive integer number $$$a$$$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $$$(x, y)$$$. Petya will answer him:   "x", if $$$(x \bmod a) \geq (y \bmod a)$$$.  "y", if $$$(x \bmod a) < (y \bmod a)$$$. We define $$$(x \bmod a)$$$ as a remainder of division $$$x$$$ by $$$a$$$.Vasya should guess the number $$$a$$$ using no more, than 60 questions.It's guaranteed that Petya has a number, that satisfies the inequality $$$1 \leq a \leq 10^9$$$.Help Vasya playing this game and write a program, that will guess the number $$$a$$$.

NoteIn the first test, you should play $$$3$$$ games with Petya's numbers $$$1$$$, $$$2$$$ and $$$3$$$.In the first game, Petya will answer "x" (without quotes) to any question, because $$$(x \bmod 1) = 0$$$ for any integer $$$x$$$. In the second game, if you will ask pair $$$(0, 0)$$$, the answer will be "x" (without quotes), because $$$(0 \bmod 2) \geq (0 \bmod 2)$$$. But if you will ask pair $$$(2, 5)$$$, the answer will be "y" (without quotes), because $$$(2 \bmod 2) < (5 \bmod 2)$$$, because $$$(2 \bmod 2) = 0$$$ and $$$(5 \bmod 2) = 1$$$.

var x, y, mid;

function q(a, b) {
    print('? ' + a + ' ' + b);
}

while(true) {
    var s = readline();

    if(s === 'start') {
        x = 1, y = 2;
        while(true) {
            q(x, y)
            c = readline();
            if(c === 'y') {
                x *= 2;
                y *= 2;
            }
            else {
                break;
            }
        }

        while(y - x > 1) {
            mid = Math.floor((x + y) / 2);
            q(x, mid);
            c = readline();
            if(c === 'y') {
                x = mid;
            }
            else {
                y = mid;
            }
        }

        q(y, x);

        c = readline();

        if(c === 'x') {
            print('! ' + x);
        }
        else {
            print('! ' + y);
        }
    }
    else {
        break;
    }
}


The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of $$$m$$$ pages.Polycarp also has $$$n$$$ cups of coffee. The coffee in the $$$i$$$-th cup Polycarp has $$$a_i$$$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).Let's consider some day of Polycarp's work. Consider Polycarp drinks $$$k$$$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $$$a_{i_1}, a_{i_2}, \dots, a_{i_k}$$$. Then the first cup he drinks gives him energy to write $$$a_{i_1}$$$ pages of coursework, the second cup gives him energy to write $$$max(0, a_{i_2} - 1)$$$ pages, the third cup gives him energy to write $$$max(0, a_{i_3} - 2)$$$ pages, ..., the $$$k$$$-th cup gives him energy to write $$$max(0, a_{i_k} - k + 1)$$$ pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of cups of coffee and the number of pages in the coursework. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the caffeine dosage of coffee in the $$$i$$$-th cup.

If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.

NoteIn the first example Polycarp can drink fourth cup during first day (and write $$$1$$$ page), first and second cups during second day (and write $$$2 + (3 - 1) = 4$$$ pages), fifth cup during the third day (and write $$$2$$$ pages) and third cup during the fourth day (and write $$$1$$$ page) so the answer is $$$4$$$. It is obvious that there is no way to write the coursework in three or less days.In the second example Polycarp can drink third, fourth and second cups during first day (and write $$$4 + (2 - 1) + (3 - 2) = 6$$$ pages) and sixth cup during second day (and write $$$4$$$ pages) so the answer is $$$2$$$. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15$$$ pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) = 14$$$ pages of coursework and during second day he will write $$$5$$$ pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1.

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0], m = nums[1];
var s = readline().split(" ").map(function(x) { return parseInt(x); });

//var sum = 0;
//for (var i=0; i<n; i++) sum += s[i];
s.sort(function(a,b) {return a-b;});

var down = 1, up = Math.min(m, n) + 1;
while (up>down) {
//write(" down = ", down, "\n");
//write(" up = ", up, "\n\n");
	var mid = Math.floor((up+down)/2);
	//var res = sum;
	var dvv = Math.floor(n/mid);
	var rem = n % mid;

	var res = 0;
	var fr = 0;
	if (rem > 0) {
		for (var i=0; i<rem; i++) res += Math.max(0, s[i] - dvv);
		fr = rem;
	}
	for (var i=fr; i<n; i+=mid) {
		dvv--;
		for (var j=0; j<mid; j++) res += Math.max(0, s[i+j] - dvv);
	}

	//0...dvv-1
	//res -= Math.floor(dvv*(dvv-1)/2);
	//var rem = n % mid;
	//if (rem > 0)
	//	res -= rem * dvv;

	if (res >= m) up = mid;
	else down = mid + 1;
}
if (down > Math.min(n,m)) write("-1");
else write(down);

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0], m = nums[1];
var s = readline().split(" ").map(function(x) { return parseInt(x); });

var sum = 0;
for (var i=0; i<n; i++) sum += s[i];

var down = 0, up = Math.min(m, n) + 1;
while (up>down) {
	var mid = Math.floor((up+down)/2);
	var res = sum;
	var dvv = Math.floor(n/mid);
	//0...dvv-1
	res -= Math.floor(dvv*(dvv-1)/2);
	var rem = n % mid;
	if (rem > 0)
		res -= rem * dvv;
	if (res >= m) up = mid;
	else down = mid + 1;
}
if (down > Math.min(n,m)) write("-1");
else write(down);


You are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.Segment [l1, r1] lies within segment [l2, r2] iff l1 ≥ l2 and r1 ≤ r2.Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

The first line contains one integer n (1 ≤ n ≤ 3·105) — the number of segments. Each of the next n lines contains two integers li and ri (1 ≤ li ≤ ri ≤ 109) — the i-th segment.

Print two distinct indices i and j such that segment ai lies within segment aj. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

NoteIn the first example the following pairs are considered correct:  (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders;  (3, 2), (4, 2), (3, 5), (4, 5) — touch one border;  (5, 2), (2, 5) — match exactly.

var n = readline(), arr = []; ansl = -1, ansr = -1;
for(var i = 0; i < n; i++) {
    var tp = readline().split(' ');
    arr[i] = {id: i + 1, li: parseInt(tp[0]), ri: parseInt(tp[1])};
}
arr.sort((p1, p2) => {
    if(p1.li === p2.li) return p2.ri - p1.ri;
    return p1.li - p2.li
});
for(var i = 1, tl = arr[0].id, max = arr[0].ri; i < n; i++) {
    if(arr[i].ri > max) tl =  arr[i].id, max = arr[i].ri;
    else {
        ansl = tl, ansr = arr[i].id;
        break;
    }
}
print(ansr, ansl);

var n = readline(), arr = []; ansl = -1, ansr = -1;
for(var i = 0; i < n; i++) {
    var tp = readline().split(' ');
    arr[i] = {id: i + 1, li: parseInt(tp[0]), ri: parseInt(tp[1])};
}
arr.sort((p1, p2) => p1.li - p2.li);
for(var i = 1, tl = arr[0].id, max = arr[0].ri; i < n; i++) {
    if(arr[i].ri > max) tl =  arr[i].id, max = arr[i].ri;
    else {
        ansl = tl, ansr = arr[i].id;
        break;
    }
}
print(ansr, ansl);

var nq = readline().split(' ');
var n = +nq[0], q = +nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(+item));
ki = readline().split(' ').map(item => Math.floor(+item));
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( hi- (hi - lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1) sum = 0, ans = n;
    else if(hi === -1) ans = n;
    else ans = n - hi - 1;
    print(ans);
}

var n = readline(), arr = []; ansl = -1, ansr = -1;
for(var i = 0; i < n; i++) {
    var tp = readline().split(' ');
    arr[i] = {id: i + 1, li: parseInt(tp[0]), ri: parseInt(tp[1])};
}
arr.sort((p1, p2) => p1.li - p2.li);
for(var i = 1, tl = arr[0].id, max = arr[0].ri; i < n; i++) {
    if(arr[i].ri > max) tl =  arr[i].id, max = arr[i].ri;
    else {
        ansl = tl, ansr = arr[i].id;
        break;
    }
}
print(ansl, ansr);


You've got an array a, consisting of n integers: a1, a2, ..., an. Your task is to find a minimal by inclusion segment [l, r] (1 ≤ l ≤ r ≤ n) such, that among numbers al,  al + 1,  ...,  ar there are exactly k distinct numbers.Segment [l, r] (1 ≤ l ≤ r ≤ n; l, r are integers) of length m = r - l + 1, satisfying the given property, is called minimal by inclusion, if there is no segment [x, y] satisfying the property and less then m in length, such that 1 ≤ l ≤ x ≤ y ≤ r ≤ n. Note that the segment [l, r] doesn't have to be minimal in length among all segments, satisfying the given property.

The first line contains two space-separated integers: n and k (1 ≤ n, k ≤ 105). The second line contains n space-separated integers a1, a2, ..., an — elements of the array a (1 ≤ ai ≤ 105).

Print a space-separated pair of integers l and r (1 ≤ l ≤ r ≤ n) such, that the segment [l, r] is the answer to the problem. If the sought segment does not exist, print "-1 -1" without the quotes. If there are multiple correct answers, print any of them.

NoteIn the first sample among numbers a1 and a2 there are exactly two distinct numbers.In the second sample segment [2, 5] is a minimal by inclusion segment with three distinct numbers, but it is not minimal in length among such segments.In the third sample there is no segment with four distinct numbers.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const input = readline().split(' ').map(Number)
  const [length, distinct] = input
  const nums = readline().split(' ').map(Number)
  helper(nums, length, distinct)
}

function helper(nums, length, distinct) {
  let cnt = new Map()
  let unique = 0
  let j = 0

  for (let i = 0; i < length; i++) {
    const num = nums[i]
    if (!cnt.has(num))
      unique++
    cnt.set(num, (cnt.get(num) || 0) + 1)
    while (unique === distinct) {
      cnt.set(nums[j], cnt.get(nums[j])-1);
      if (cnt.get(nums[j]) === 0) {
        console.log((j + 1) + ' ' + (i + 1))
        return
      }
      j++
    }
  }

  console.log('-1 -1')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array(100010);
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array(100010).fill(0);
    // for (let i = 0; i <= 100010; i++) {
    //     counts[i] = 0;
    // }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = [];
    // const counts = new Array(100010);
    // for (let i = 0; i <= 100010; i++) {
    //     counts[i] = 0;
    // }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array(100010);
    // for (let i = 0; i <= 100010; i++) {
    //     counts[i] = 0;
    // }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment2(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    // const counts = new Array(100010).fill(0);
    const counts = [];
    for (let i = 0; i <= 100010; i++) {
        counts.push(0);
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[start] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
}

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
}

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ');
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array(100001);
    // const counts = new Array(100010);
    // for (let i = 0; i <= 100010; i++) {
    //     counts[i] = 0;
    // }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[parseInt(ar[i], 10)]) {
            counts[parseInt(ar[i], 10)] = `${i}`;
            if (ar[i] == ar[start]) {
                while (counts[parseInt(ar[start], 10)] != start) {
                    start++;
                }
            }
            continue;
        }
        counts[parseInt(ar[i], 10)] = `${i}`;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array(100001).fill(0);
    // const counts = new Array(100010);
    // for (let i = 0; i <= 100010; i++) {
    //     counts[i] = 0;
    // }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    // const counts = new Array(100010).fill(0);
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array();
    // const counts = new Array(100010);
    // for (let i = 0; i <= 100010; i++) {
    //     counts[i] = 0;
    // }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    printResult(result);
}

const countSegment = (n, k, ar) => {
    const counts = new Array(100001);
    // for (let i = 0; i <= 100010; i++) {
    //     counts[i] = 0;
    // }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

function giaiBai(inp1, inp2) {
    inp1 = inp1.split(' ').map(e => parseInt(e))
    inp2 = inp2.split(' ').map(e => parseInt(e))
    inp2.unshift(0)

    let n = inp1[0],
        k = inp1[1],
        a = inp2,
        c = new Array(10e5).fill(0),
        count = 0,
        j = 0

    for(var i = 1; i <= n; i++) {
        c[a[i]]++
        if (c[a[i]] === 1) {
            count++
        }
        while (count === k) {
            j++
            c[a[j]]--
            if(c[a[j]] === 0) {
                console.log(j, i)
                break
            }
        }
        if(count === k) {
            break
        }
    }
    if (count === k) {
        return
    }
    console.log('-1 -1')
}

var readline = require('readline');
// Get process.stdin as the standard input object.
var standard_input = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

// Set input character encoding.
// standard_input.setEncoding('utf-8');

// Prompt user to input data in console.
// console.log("Please input text in command line.");

// When user input data and click enter key.
standard_input.on('line', function (inp1) {
//     console.log(inp1);
    standard_input.on('line', function (inp2) {
        // Print user input in console.
        inp1 = inp1.trim()
        inp2 = inp2.trim()
        giaiBai(inp1, inp2)
        process.exit();
    });
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const input = readline().split(' ').map(Number)
  const [length, distinct] = input
  const nums = readline().split(' ').map(Number)
  helper(nums, length, distinct)
}

function helper(nums, length, distinct) {
  let cnt = new Map()
  let unique = 0
  let j = 0

  for (let i = 0; i < length; i++) {
    const num = nums[i]
    if (!cnt.has(num))
      unique++
    cnt.set(num, (cnt.get(num) || 0) + 1)
    while (unique === distinct) {
      cnt.set(num, cnt.get(num)-1);
      if (cnt.get(num) === 0) {
        console.log((j + 1) + ' ' + (i + 1))
        return
      }
      j++
    }
  }

  console.log('-1 -1')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const input = readline().split(' ').map(Number)
  const [length, distinct] = input
  const nums = readline().split(' ').map(Number)
  helper(nums, length, distinct)
}

function helper(nums, length, distinct) {
  let cnt = new Map()
  let unique = 0
  let j = 0

  for (let i = 0; i < length; i++) {
    const num = nums[i]
    if (!cnt.has(num))
      unique++
    cnt.set(num, (cnt.get(num) || 0) + 1)
    while (unique === distinct) {
      cnt.set(num, cnt.get(num)-1);
      if (cnt.get(num) === 0) {
        console.log(i + ' ' + j)
        return
      }
      j++
    }
  }

  console.log('-1 -1')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    // const nk = parseInt(readLine(), 10);
    const nk = readLine().split(' ').map(Number);
    const arr = `0 ${readLine()}`.split(' ').map(Number);
    const n = nk[0];
    const k = nk[1];
    // console.log(n, k, arr)

    const result = countSegment(n, k, arr);
    // printResult(result);
}

const countSegment = (n, k, ar) => {
    // const counts = new Array(100010).fill(0);
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            counts[ar[i]] = i;
            if (ar[i] === ar[start]) {
                while (counts[ar[start]] !== start) {
                    start++;
                }
            }
            continue;
        }
        counts[ar[i]] = i;
        sum++;
        if (sum === k) {
            end = i;
            break;
        }
    }

    return end ? `${start} ${end}` : `-1 -1`;
};

const countSegment2 = (n, k, ar) => {
    const counts = new Array(100010);
    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    let start = 1;
    let end = 0;
    let sum = 0;
    let f;
    for (let i = 1; i <= n; i++) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            end = i;
            f = 1;
            break;
        }
    }

    for (let i = 0; i <= 100010; i++) {
        counts[i] = 0;
    }
    sum = 0;
    for (let i = end; i >= 1; i--) {
        if (counts[ar[i]]) {
            continue;
        }
        counts[ar[i]] = 1;
        sum++;
        if (sum === k) {
            start = i;
            break;
        }
    }
    return f ? `${start} ${end}` : `-1 -1`;
};

function printResult(x) {
    process.stdout.write(x);
}

function giaiBai(inp1, inp2) {
    inp1 = inp1.split(' ').map(e => parseInt(e))
    inp2 = inp2.split(' ').map(e => parseInt(e))
    inp2.unshift(0)

    let n = inp1[0],
        k = inp1[1],
        a = inp2,
        c = new Array(10e5).fill(0),
        count = 0,
        j = 0

    for(var i = 1; i <= n; i++) {
        c[a[i]]++
        if (c[a[i]] === 1) {
            count++
        }
        while (count === k) {
            j++
            c[a[j]]--
            if(c[a[j]] === 0) {
                console.log(j, i)
                break
            }
        }
        if(count === k) {
            break
        }
    }
    if (count === k) {
        return
    }
    console.log('-1 -1')
}

// var readline = require('readline');
// Get process.stdin as the standard input object.
// var standard_input = readline.createInterface({
//   input: process.stdin,
//   output: process.stdout,
//   terminal: false
// });
var standard_input = process.stdin;
// Set input character encoding.
// standard_input.setEncoding('utf-8');

// Prompt user to input data in console.
// console.log("Please input text in command line.");

// When user input data and click enter key.
standard_input.on('line', function (inp1) {
//     console.log(inp1);
    standard_input.on('line', function (inp2) {
        // Print user input in console.
        inp1 = inp1.trim()
        inp2 = inp2.trim()
        giaiBai(inp1, inp2)
        process.exit();
    });
});

function giaiBai(inp1, inp2) {
    inp1 = inp1.split(' ').map(e => parseInt(e))
    inp2 = inp2.split(' ').map(e => parseInt(e))
    inp2.unshift(0)

    let n = inp1[0],
        k = inp1[1],
        a = inp2,
        c = new Array(10e5).fill(0),
        count = 0,
        j = 0

    for(var i = 1; i <= n; i++) {
        c[a[i]]++
        if (c[a[i]] === 1) {
            count++
        }
        while (count === k) {
            j++
            c[a[j]]--
            if(c[a[j]] === 0) {
                console.log(j, i)
                break
            }
        }
        if(count === k) {
            break
        }
    }
    if (count === k) {
        return
    }
    console.log('-1 -1')
}

var readline = require('readline');
// Get process.stdin as the standard input object.
var standard_input = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
// Set input character encoding.
// standard_input.setEncoding('utf-8');

// Prompt user to input data in console.
// console.log("Please input text in command line.");

// When user input data and click enter key.
standard_input.on('data1', function (inp1) {
    standard_input.on('data2', function (inp2) {
        // Print user input in console.
        inp1 = inp1.trim()
        inp2 = inp2.trim()
        giaiBai(inp1, inp2)
        process.exit();
    });
});


You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow.  The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print the answer — the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ if it's possible to do that or -1 if it's impossible to obtain $$$1$$$ from $$$n$$$.

NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $$$15116544$$$:  Divide by $$$6$$$ and get $$$2519424$$$;  divide by $$$6$$$ and get $$$419904$$$;  divide by $$$6$$$ and get $$$69984$$$;  divide by $$$6$$$ and get $$$11664$$$;  multiply by $$$2$$$ and get $$$23328$$$;  divide by $$$6$$$ and get $$$3888$$$;  divide by $$$6$$$ and get $$$648$$$;  divide by $$$6$$$ and get $$$108$$$;  multiply by $$$2$$$ and get $$$216$$$;  divide by $$$6$$$ and get $$$36$$$;  divide by $$$6$$$ and get $$$6$$$;  divide by $$$6$$$ and get $$$1$$$.

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

    while (n > 1 && n < Number.MAX_SAFE_INTEGER) {
      if (n % 6 === 0) {
        while (n % 6 === 0) {
          n /= 6;
          count++;
        }
      } else {
        n *= 2;
        count++;
      }
    }
    if (n === 1) console.log(count);
    else console.log(-1);
  }
}

//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var n = nextInt();
		if(n == 1){
			output[i] = 0;
			continue;
		}
		var two = 0;
		var three = 0;
		while(n % 3 == 0){
			n /= 3;
			three++;
		}
		while(n % 2 == 0){
			n /= 2;
			two++;
		}
		if(n != 1){
			output[i] = -1;
		}else{
			if(three >= two){
				output[i] = two + (three - two) * 2;
			}else{
				output[i] = -1;
			}
		}
	}
	myout(myconv(output,9));
}
function getPrimeFactorization(val){
  var primeMap = {};
  var div = 2;
  while(val != 1){
    if(val % div == 0){
      var count = 2;
      while(val % Math.pow(div, count) == 0){
         count++;
      }
      (primeMap[div] == null)  ? primeMap[div] = (count - 1) : primeMap[div] += (count - 1);
      val /= Math.pow(div, count - 1);
      if(isPrime(val)){
        (primeMap[val] == null)  ? primeMap[val] = 1 : primeMap[val]++;
        break;
      }
    }
    div = (div == 2) ? div + 1 : div + 2;
  }
  return primeMap;
}
function isPrime(val){
  if(val == null || val <= 1 || (val != 2 && val % 2 == 0)){
    return false;
  }else if(val == 2){
    return true;
  }
  var root = Math.floor(Math.sqrt(val));
  for(var i = 3; i <= root; i += 2){
    if(val % i == 0){
      return false;
    }
  }
  return true;
}

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

let stdinInput = '';

process.stdin.on('data', input => {
  stdinInput += input;
});

process.stdin.on('end', () => {
  main(stdinInput);
});

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 1;
    let i = 1;
    while (i <= testCases) {
      let n = +data[i];
      let check = false;
      let count = 0;
      while (true) {
        const mod = n % 6;
        if (n === 1) {
          console.log(count);
          break;
        } else if (mod && check) {
          console.log(-1);
          break;
        } else if (!mod) {
          n /= 6;
          check = false;
        }
        else {
          n *= 2;
          check = true;
        }
        count += 1;
      }
      i += 1;
    }
  }

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

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

  let n = BigInt(d);

  if (n === 1n) {
    ans += '0\n';
  }
  else {
    let test = 0;
    for (let i = 0; i < 50; i++) {
      if (n % 6n === 0n) {
        n = n / 6n;
      }
      else {
        n = n * 2n;
      }

      if (n === 1n) {
        test = i + 1;
        break;
      }
    }

    if (test) {
      ans += `${test}\n`;
    }
    else {
      ans += `-1\n`;
    }
  }

  c++;
});

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

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    function solve(x, moves) {
        if (x === 1) { return moves; }
        else if (x%2 === 1) { return solve(2*x, moves+1); }
        else if (x%6 === 0) { return solve(Math.floor(x/6), moves+1); }
        else { return -1; }
    }
    const testCases = parseInt(readline());
    for (var i=0; i<testCases; i++) {
        const x = parseInt(readline());
        console.log(solve(x, 0));
    }
}

const readline = require('readline');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if (lineCount >= testCount) {
        outputStr += compute(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input) + '\n'
    }
    lineCount++
});

function compute(str) {
    var n = parseInt(str)
    var temp = n
    var timesOfTwo = 0
    var timesOfThree = 0
    while(temp%2==0){
        temp = temp / 2
        timesOfTwo+=1
    }
    while(temp%3==0){
        temp = temp / 3
        timesOfThree+=1
    }
    // console.log(timesOfTwo, timesOfThree)
    if(temp==1&&timesOfTwo<=timesOfThree){
        return timesOfThree*2 - timesOfTwo
    }
    else return -1
}

var n = readline();
var map = [];
for (var i = 0; i<n;i++){
    var tmp = readline();
    var tmp2 = tmp;
    var iter = 0;
    while (true){
        if (tmp2 == 1){
            map.push(iter);
            break;
        }
        if (tmp2 % 2 === 0 && tmp2 % 6 !== 0){
            map.push(-1);
            break;
        }
        if (tmp2%6 === 0){
            tmp2 /= 6;
        }else{
            tmp2 *= 2;
        }
        iter++;

    }
}
for (var i = 0; i<n;i++) {
    write(map[i]+"\n");
}

var testCase = Number(readline());
while(testCase--)
{
	var number = Number(readline());
	var loopAssumed = 200;
	var answer = 0;
	var flag = 0;
	while(loopAssumed--)
	{
		if(number==1)
		{
			print(answer);
			flag=1;
			break;
		}
		if(number%6 == 0)
		{
			number = number/6;
		}
		else
		{
			number = number*2;
		}
		if(number>1e18)
		{
			break;
		}
		answer++;
	}
	if(flag==0)
	{
		print(-1);
	}
}

function solve() {
   var n = Number(read());
   var c2 = 0;
   var c3 = 0;
   while (n % 2 === 0) {
      n /= 2;
      c2++;
   }
   while (n % 3 === 0) {
      n /= 3;
      c3++;
   }
   if (n !== 1) {
      write(-1);
      return;
   }
   if (c2 > c3) {
      write(-1);
   } else {
      write(c3 * 2 - c2);
   }
}

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

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    function solve(x, moves) {
        console.log(x);
        if (x === 1) { return moves; }
        else if (x%2 === 1) { return solve(2*x, moves+1); }
        else if (x%6 === 0) { return solve(Math.floor(x/6), moves+1); }
        else { return -1; }
    }
    const testCases = parseInt(readline());
    for (var i=0; i<testCases; i++) {
        const x = parseInt(readline());
        console.log(solve(x, 0));
    }
}


There is a frog staying to the left of the string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ characters (to be more precise, the frog initially stays at the cell $$$0$$$). Each character of $$$s$$$ is either 'L' or 'R'. It means that if the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $$$0$$$.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the $$$n+1$$$-th cell. The frog chooses some positive integer value $$$d$$$ before the first jump (and cannot change it later) and jumps by no more than $$$d$$$ cells at once. I.e. if the $$$i$$$-th character is 'L' then the frog can jump to any cell in a range $$$[max(0, i - d); i - 1]$$$, and if the $$$i$$$-th character is 'R' then the frog can jump to any cell in a range $$$[i + 1; min(n + 1; i + d)]$$$.The frog doesn't want to jump far, so your task is to find the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it can jump by no more than $$$d$$$ cells at once. It is guaranteed that it is always possible to reach $$$n+1$$$ from $$$0$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case is described as a string $$$s$$$ consisting of at least $$$1$$$ and at most $$$2 \cdot 10^5$$$ characters 'L' and 'R'. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum |s| \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it jumps by no more than $$$d$$$ at once.

NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the third test case of the example, the frog can choose $$$d=3$$$, jump to the cell $$$3$$$ from the cell $$$0$$$ and then to the cell $$$4$$$ from the cell $$$3$$$.In the fourth test case of the example, the frog can choose $$$d=1$$$ and jump $$$5$$$ times to the right.In the fifth test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the sixth test case of the example, the frog can choose $$$d=1$$$ and jump $$$2$$$ times to the right.

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]
const D = (...args) => { // D({name})
  [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))
}

main()
function main() {
  let t = getInt()
  while (t --> 0) {
    const s = 'R' + getLine() + 'R'
    const n = s.length
    let last = 0
    let ans = 0
    for (let i = 1; i < n; ++i) {
      if (s[i] === 'R') {
        ans = Math.max(ans, i - last)
        last = i
      }
    }
    print(ans)
  }
}

var t = Number(readline());
for (var k=0;k<t;k++){
 var s = readline();
 var n = s.length;
 var m = 0;
 var r = 1;
 for(var i=0;i<n;i++){
  if(s[i]=='R'){
   if(r>m){m=r;}
   r=1;
  }
  else{
   r++;
  }
 }
 print((r>m)?r:m);
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var s = nextCharArray();
        var len = s.length;
        var max = 0;//renzokuLnoMax + 1
        var count = 0;
        for(var j = 0; j < len; j++){
            if(s[j] == "L"){
                count++;
            }else{
                max = Math.max(max,count + 1);
                count = 0;
            }
        }
      	max = Math.max(max,count + 1);
        output[i] = max;
    }
    myout(myconv(output,9));
}

var t = parseInt(readline());

for (var i = 0; i < t; i++) {
  var s = readline();

  var ara = [];
  ara.push(0);
  for (var j = 0; j < s.length; j++) {
    if (s[j] == "R") ara.push(j + 1);
  }
  ara.push(s.length + 1);

  var max = ara[1] - ara[0];
  for (var j = 0; j < ara.length - 1; j++) {
    var diff = ara[j + 1] - ara[j];
    if (diff > max) max = diff;
  }

  print(max);
}

// Problem Link: https://codeforces.com/contest/1324/problem/C
// Solution Link:

'use strict';

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

let inputString = '';
let currentLine = 0;
const INF = Math.pow(10, 12);

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

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

    main();
});

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

let results = [];

const getInput = () => {
    const lineInput = readline();
    const testCase = parseInt(lineInput);

    for(let i = 0; i < testCase; i++){
        const lineInput = readline() + "R";
        results.push(calculateJumpRange(lineInput));
    }

};

const isPossible = (moveSequence, jumpRange) => {
    let currentPos = -1
    while(currentPos < moveSequence.length - 1){
        let nextPos = -1;
        for(let i = currentPos + 1; i < Math.min(currentPos + jumpRange + 1, moveSequence.length); i++){
            if(moveSequence[i] === "R"){
                nextPos = i;
                break;
            }
        }

        if(nextPos === -1)
            return false;
        currentPos = nextPos;
    }

    return true;
}

const calculateJumpRange = (moveSequence) => {

    let low = 1, high = moveSequence.length + 1;
    let len = high;
    while(low <= high) {
        let mid = Math.floor((low + high) / 2);

        if(isPossible(moveSequence, mid))
            len = mid, high = mid - 1;
        else
            low = mid + 1;
    }

    return len;
}

function main() {
    getInput();
    for(let r of results)
        console.log(r);
}

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

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

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

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a) {
  return parseInt(a[ptr++])
}

function readString(a) {
  return a[ptr++]
}

function readStrings(a) {
  return a[ptr++].split(' ')
}

function readInts(a) {
  return a[ptr++].split(' ').map(a => parseInt(a))
}

function main(input) {
  let t = readInt(input)
  while(t--) {
    let s = readString(input) + 'R'
    let min = -Infinity
    let count = 0
    const length = s.length
    for(let i = 0; i < length; i++) {
      // console.log(i, count, min)
      if(s[i] === 'L') count++
      else {
        min = min < count + 1 ? count + 1 : min
        count = 0
      }
    }
    wr(min)
  }
}

const readline = require('readline')
const rl = readline.createInterface(process.stdin, process.stdout)

const input = []

rl.on('line', line => input.push(line.toString()))

rl.on('close', () => {
  solve()
})

const solve = () => {
  const t = Number(input[0])

  for (let testCase = 1; testCase <= t; testCase++) {
    const s = 'R' + input[testCase] + 'R'

    const arr = s
      .split('')
      .map((char, index) => (char === 'R' ? index : -1))
      .filter(num => ~num)

    d = 0

    for (let i = 1; i < arr.length; i++) {
      d = Math.max(d, arr[i] - arr[i - 1])
    }

    console.log(d)
  }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8')
let inputString = '';
let currentLine = 0;
process.stdin.on('data', input => { inputString += input })
process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(str => str.trim()); main() })
const readline = () => { return inputString[currentLine++] }

function main(){
	let tests = parseInt(readline());
	while(tests--){
		let path = readline();
		let cntL = 0;
		let mx = 0;
		for(let i = 0; i < path.length; i++){
			let char = path[i];
			if(char == 'R'){
				cntL = 0;
			}
			else{
				cntL++;
				mx = Math.max(mx, cntL);
			}
		}
		console.log(mx + 1);
	}
}

process.stdin.resume();
process.stdin.setEncoding('utf-8')
let inputString = '';
let currentLine = 0;
process.stdin.on('data', input => { inputString += input })
process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(str => str.trim()); main() })
const readline = () => { return inputString[currentLine++] }

function main(){
	let tests = parseInt(readline());
	while(tests--){
		let path = readline();
		let cntL = 0;
		let mx = 0;
		[...path].forEach(char => {
			if(char == 'R'){
				cntL = 0;
			}
			else{
				cntL++;
				mx = Math.max(mx, cntL);
			}
		});
		console.log(mx + 1);
	}
}

var t = parseInt(readline());

for (var i = 0; i < t; i++) {
  var s = readline();

  var ara = [];
  ara.push(0);
  for (var i = 0; i < s.length; i++) {
    if (s[i] == "R") ara.push(i + 1);
  }
  ara.push(s.length + 1);

  var max = ara[1] - ara[0];
  for (var j = 0; j < ara.length - 1; j++) {
    var diff = ara[j + 1] - ara[j];
    if (diff > max) max = diff;
  }

  print(max);
}

var t = parseInt(readline());

for (var i = 0; i < t; i++) {
  var s = readline();

  var ara = [];
  ara.push(0);
  for (var i = 0; i < s.length; i++) {
    if (s[i] == "R") ara.push(i + 1);
  }
  ara.push(s.length + 1);

  var max = ara[1] - ara[0];
  for (var i = 0; i < ara.length - 1; i++) {
    var diff = ara[i + 1] - ara[i];
    if (diff > max) max = diff;
  }

  print(max);
}

const readline = require('readline')
const rl = readline.createInterface(process.stdin, process.stdout)

const input = []

rl.on('line', line => input.push(line.toString()))

rl.on('close', () => {
  solve()
})

const binarySearch = s => {
  const isFeasible = maxStep => {
    let visited = Array(s.length + 1).fill(false)

    const dfs = u => {
      visited[u] = true

      if (s[u] === 'R') {
        for (let step = 1; step <= maxStep; step++) {
          const v = u + step

          if (v < s.length && v >= 0 && !visited[v]) {
            dfs(v)
          }
        }
      }
    }

    dfs(0)
    return visited[s.length]
  }

  let low = 0
  let high = s.length
  let d = -1

  while (low <= high) {
    const mid = Math.floor((low + high) / 2)

    if (isFeasible(mid)) {
      d = mid
      high = mid - 1
    } else {
      low = mid + 1
    }
  }

  return d
}

const solve = () => {
  const t = Number(input[0])

  for (let testCase = 1; testCase <= t; testCase++) {
    const s = input[testCase]
    const d = binarySearch('R' + s)
    console.log(d)
  }
}


The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).

The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.

Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).

NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.

function intersection (a, b) {
	for (var i = 0, _i = a.length; i < _i; i++)
		if (b.indexOf(a[i]) !== -1) return true;
	return false;
}

function merge (a, b) {
	for (var i = 0, _i = a.length; i < _i; i++)
		if (b.indexOf(a[i]) === -1) b.push(a[i]);
	return b;
}

;(function () {

	print((function (n, m) {

		for (var i = 0, a = []; i <= m; i++) a[i] = [];

		for (var i = 0; i < n; i++) {
			var s = readline();
			if (s[0] == '0') a[0].push(i);
			else for (var j = 1, s = s.split(' '), _j = s.length; j < _j; j++) a[+s[j]].push(i);
		}

		var sub = a[0].length;
		a.shift(0);

		a = a.filter(function (e) { return e.length; });

		var flag = true;
		while (flag) {
			flag = false;
			for (var i = 0, _i = a.length; i < _i; i++) {
				for (var j = 0; j < _i; j++)
					if (i !== j && intersection(a[i], a[j])) {
						a[i] = merge(a[i], a[j]);
						a.splice(j, 1);
						flag = true;
						break;
					}
				if (flag) break;
			}
		}

		return sub + a.length - !!a.length;

	}).apply(this, readline().split(' ').map(Number)));

}).call(this);

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

const rl = readline.createInterface({
    input: process.stdin,
    // input: fs.createReadStream('src/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 n = lines[0][0];
    const graph = {};

    let noOneKnow = true;
    // cover edge case, no one know any language
    for (let i = 1; i <= n; i++) {
        if (lines[i][0] > 0) {
            noOneKnow = false;
        }
    }
    if (noOneKnow) {
        console.log(n);
        return;
    }

    for (let i = 1; i < lines.length; i++) {
        lines[i].shift();
        graph[`${i}E`] = (graph[`${i}E`] || []).concat(lines[i]);
        for (let j = 0; j < lines[i].length; j++) {
            graph[lines[i][j]] = (graph[lines[i][j]] || []).concat(`${i}E`);
        }
    }

    const visited = {};
    for (let v in graph) {
        visited[v] = false;
    }

    const bfs = (s, graph) => {
        const queue = [s];

        while (queue.length > 0) {
            const u = queue.shift();
            for (let i = 0; i < graph[u].length; i++) {
                const v = graph[u][i];
                if (!visited[v]) {
                    visited[v] = true;
                    queue.push(v);
                }
            }
        }
    };

    let count = 0;
    for (let i = 1; i <= n; i++) {
        if (!visited[`${i}E`]) {
            count++;
            bfs(`${i}E`, graph);
        }
    }

    console.log(count - 1);
});

function intersection (a, b) {
	for (var i = 0, _i = a.length; i < _i; i++)
		if (b.indexOf(a[i]) !== -1) return true;
	return false;
}

function merge (a, b) {
	for (var i = 0, _i = a.length; i < _i; i++)
		if (b.indexOf(a[i]) === -1) b.push(a[i]);
	return b;
}

;(function () {

	print((function (n, m) {

		for (var i = 0, a = []; i <= m; i++) a[i] = [];

		for (var i = 0; i < n; i++) {
			var s = readline().split(' ');
			if (s[0] === '0') a[0].push(i);
			else for (var j = 1, _j = s.length; j < _j; j++) a[+s[j]].push(i);
		}

		var sub = a[0].length;
		a[0] = false;

		var flag = true;
		while (flag) {
			flag = false;
			for (var i = 1, _i = a.length; i < _i; i++) {
				if (intersection(a[i - 1], a[i])) {
					a[i] = merge(a[i], a[i - 1]);
					a[i - 1] = false;
					flag = true;
					a = a.filter(function (e) { return e !== false; });
					break;
				}
			}
		}

		a = a.filter(function (e) { return e.length; });

		return sub + a.length - 1;

	}).apply(this, readline().split(' ').map(Number)));

}).call(this);

function intersection (a, b) {
	for (var i = 0, _i = a.length; i < _i; i++)
		if (b.indexOf(a[i]) !== -1) return true;
	return false;
}

function merge (a, b) {
	for (var i = 0, _i = a.length; i < _i; i++)
		if (b.indexOf(a[i]) === -1) b.push(a[i]);
	return b;
}

;(function () {

	print((function (n, m) {

		for (var i = 0, a = []; i <= m; i++) a[i] = [];

		for (var i = 0; i < n; i++) {
			var s = readline().split(' ');
			if (s[0] === '0') a[0].push(i);
			else for (var j = 1, _j = s.length; j < _j; j++) a[+s[j]].push(i);
		}

		var sub = a[0].length;
		a[0] = false;

		var flag = true;
		while (flag) {
			flag = false;
			for (var i = 1, _i = a.length; i < _i; i++) {
				if (intersection(a[i - 1], a[i])) {
					a[i] = merge(a[i], a[i - 1]);
					a[i - 1] = false;
					flag = true;
					a = a.filter(function (e) { return e !== false; });
					break;
				}
			}
		}

		a = a.filter(function (e) { return e.length; });

		return sub + a.length - !!a.length;

	}).apply(this, readline().split(' ').map(Number)));

}).call(this);

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

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

let lines = [];

const calculate = (arr) => {
    const sortedArr = arr.map((value, idx) => ({ value, idx: idx + 1 })).sort((a, b) => a.value - b.value);

    const result = [];
    const originalSorted = [sortedArr[0].idx];

    for (let i = 0; i < sortedArr.length - 1; i++) {
        originalSorted.push(sortedArr[i + 1].idx);
        if (sortedArr[i].value === sortedArr[i + 1].value) {
            const newArr = [];
            // clone a new arr
            for (let j = 0; j < sortedArr.length; j++) {
                if (j !== i) {
                    newArr.push(sortedArr[j].idx);
                } else {
                    newArr.push(sortedArr[j + 1].idx);
                    newArr.push(sortedArr[j].idx);
                    j++;
                }
            }
            result.push(newArr);
        }
    }

    result.push(originalSorted);
    return result;
};

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

    if (arr.length < 3) {
        console.log('NO');
    }

    const result = calculate(arr);

    if (result && result.length >= 3) {
        console.log('YES');
        result.forEach((item) => console.log(item.join(' ')));
    } else {
        console.log('NO');
    }
});


Polycarp has $$$x$$$ of red and $$$y$$$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $$$a$$$ red candies and $$$b$$$ blue candies, or $$$a$$$ blue candies and $$$b$$$ red candies. Any candy can belong to at most one gift set.Help Polycarp to find the largest number of gift sets he can create.For example, if $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$, and $$$b = 2$$$, then Polycarp can make three gift sets:   In the first set there will be $$$5$$$ red candies and $$$2$$$ blue candies;  In the second set there will be $$$5$$$ blue candies and $$$2$$$ red candies;  In the third set will be $$$5$$$ blue candies and $$$2$$$ red candies. Note that in this example there is one red candy that Polycarp does not use in any gift set.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single string containing four integers $$$x$$$, $$$y$$$, $$$a$$$, and $$$b$$$ ($$$1 \le x, y, a, b \le 10^9$$$).

For each test case, output one number — the maximum number of gift sets that Polycarp can make.

const predicate = (x, y, a, b, n) => {
    try {
        let l = -1; let h = n + 1;

        while (h - l > 1) {
            const mid = Math.ceil((l + h) / 2);

            // p+ q = n
            const p = mid;
            const q = n - mid;
            const t1 = p * a + q * b;
            const t2 = p * b + q * a;

            if (t1 <= x && t2 <= y) {
                return true;
            }

            if (t1 > x) {
                if (a > b) {
                    h = mid;
                } else {
                    l = mid;
                }
            } else if (a > b) {
                l = mid;
            } else {
                h = mid;
            }
        }
        return false;
    } catch (ex) {
        console.log('predicate ex:', ex);
    }
};

const giftSet = ([x, y, a, b]) => {
    try {
        let low = -1; let high = 1000000001;
        let ans = 0;

        while (high - low > 1) {
            const mid = Math.ceil((low + high) / 2);

            if (predicate(x, y, a, b, mid)) {
                ans = mid;
                low = mid;
            } else {
                high = mid;
            }
        }
        // console.log('ans:', ans);
        return ans;
    } catch (ex) {
        console.log('ex:', ex);
    }
};

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        console.log(giftSet(lines[l++].split(' ').map(Number)));
    }
});


You are given two integers $$$n$$$ and $$$m$$$ and an array $$$a$$$ of $$$n$$$ integers. For each $$$1 \le i \le n$$$ it holds that $$$1 \le a_i \le m$$$.Your task is to count the number of different arrays $$$b$$$ of length $$$n$$$ such that:   $$$1 \le b_i \le m$$$ for each $$$1 \le i \le n$$$, and  $$$\gcd(b_1,b_2,b_3,...,b_i) = a_i$$$ for each $$$1 \le i \le n$$$. Here $$$\gcd(a_1,a_2,\dots,a_i)$$$ denotes the greatest common divisor (GCD) of integers $$$a_1,a_2,\ldots,a_i$$$.Since this number can be too large, print it modulo $$$998\,244\,353$$$.

Each test consist of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the length of the array $$$a$$$ and the maximum possible value of the element. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the number of different arrays satisfying the conditions above. Since this number can be large, print it modulo $$$998\,244\,353$$$.

NoteIn the first test case, the possible arrays $$$b$$$ are:   $$$[4,2,1]$$$;  $$$[4,2,3]$$$;  $$$[4,2,5]$$$. In the second test case, the only array satisfying the demands is $$$[1,1]$$$.In the third test case, it can be proven no such array exists.

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, m] = rns(),
        a = rns();
  let res = 1;
  for (let i = 1; i < n; i++) {
    if (a[i - 1] % a[i] !== 0) return 0;
    if (a[i - 1] === 1) {
      res = mul(res, m);
    } else {
      let b = Math.floor(m / a[i]),
          c = calc(b, a[i - 1] / a[i]);
      res = mul(res, c);
    }
  }
  return res;
}
function calc(a, b) {
  if (b === 1) return a;
  const p = [];
  for (let i = 2; i <= b / i; i++) {
    if (b % i === 0) {
      p.push(i);
      while (b % i === 0) {
        b /= i;
      }
    }
  }
  if (b > 1) p.push(b);
  let res = 0;
  for (let i = 1; i < 1 << p.length; i++) {
    let cnt = 0,
        ans = 1;
    for (let j = 0; j < p.length; j++) {
      if (i & 1 << j) {
        cnt++;
        ans *= p[j];
      }
    }
    if (cnt & 1) {
      res += Math.floor(a / ans);
    } else {
      res -= Math.floor(a / ans);
    }
  }
  return a - res;
}
const MOD = 998244353;
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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


You are given four integer values $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$.Check if there exists a string that contains:   $$$a$$$ letters 'A';  $$$b$$$ letters 'B';  $$$c$$$ letters 'C';  no other letters;  exactly $$$m$$$ pairs of adjacent equal letters (exactly $$$m$$$ such positions $$$i$$$ that the $$$i$$$-th letter is equal to the $$$(i+1)$$$-th one).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Each of the next $$$t$$$ lines contains the description of the testcase — four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$ ($$$1 \le a, b, c \le 10^8$$$; $$$0 \le m \le 10^8$$$).

For each testcase print "YES" if there exists a string that satisfies all the requirements. Print "NO" if there are no such strings. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first testcase strings "ABCAB" or "BCABA" satisfy the requirements. There exist other possible strings.In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice.In the third testcase string "CABBCC" satisfies the requirements. There exist other possible strings.

/* Common Template Starts */
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

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

  main();
});

function readline() {
  return inputString[currentLine++];
}
/* Common Template Ends */
function main() {
  let Q = +(readline()); // Read Input

  for (let i = 0; i < Q; i++) {
    const N = readline();

    const [a, b, c, m] = N.split(" ").map((n) => parseInt(n));
    const sorted = [a, b, c].sort((a, b) => a - b);

    const max = (a-1) + (b-1) + (c-1);
    const min = (sorted[2] - 1) - (sorted[0] + sorted[1]);
    //console.log("min max", min, max);

    if (m >= min && m <= max) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [a, b, c, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let max = a + b + c - 3;
    let arr = [a, b, c];
    let min;
    arr.sort((a, b) => b - a);
    let n = a + b + c;
    if (2 * (arr[1] + arr[2]) >= n) min = 0;
    else min = n - 2 * (arr[1] + arr[2]) - 1;
    if (m >= min && m <= max) console.log("YES");
    else console.log("NO");
  }
};
solve();

function readStringArray() {
    return readline().split(" ");
  }
  function readNumArray() {
    return readStringArray().map(Number);
  }

  function main() {
    var testCasesNum = +readline();
    for (var i = 0; i < testCasesNum; i++) {
      var abcm = readNumArray();
      var a = abcm[0];
      var b = abcm[1];
      var c = abcm[2];
      var m = abcm[3];
      var max = Math.max(a, b, c);
      var minPairs = max - (a + b + c - max) - 1;
      if (m > a - 1 + b - 1 + c - 1 || m < minPairs) {
        print('NO');
        continue;
      }

      print('YES');
    }
  }

  main();

/* Common Template Starts */
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

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

  main();
});

function readline() {
  return inputString[currentLine++];
}
/* Common Template Ends */
function main() {
  let Q = +(readline()); // Read Input

  for (let i = 0; i < Q; i++) {
    const N = readline();

    const [a, b, c, m] = N.split(" ").map((n) => parseInt(n));
    const sorted = [a, b, c].sort();

    const max = (a-1) + (b-1) + (c-1);
    const min = (sorted[2] - 1) - (sorted[0] + sorted[1]);
    //console.log("min max", min, max);

    if (m >= min && m <= max) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
}


Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends. Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.

Print the maximum number of people that may come to Famil Door's party.

NoteIn the first sample, friends 3 and 4 can come on any day in range [117, 128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.

var n = +readline();
var arr = [];
for(var i=0;i<n;i++)
arr.push(readline());
print(main(n, arr));
function main(n, arr) {
	var ms = {}, fs = {};
	arr.forEach(function(p){
		var p = p.split(' ');
		for (var i = +p[1]; i<=+p[2]; i++)
		{
			if (p[0]=='M')
				ms[i] = (ms[i]|0)+1;
			else
				fs[i] = (fs[i]|0)+1;
		}
	});
	var ans = 0;
	for(var i = 1; i<=366; i++){
		ans = Math.max(ans, Math.min(ms[i]|0, fs[i]|0));
	}
	return ans*2;
}

var n = Number(readline()); //number of friends

var avail = [];
var days = [];

var isInArray = function(value, array) {
  return array.indexOf(value) > -1;
}

for (var i = 0; i < n; i++) {
	avail[i] = readline().split(' ');

	if (isInArray(avail[i][1], days) === false) {
		days.push(avail[i][1]);
	}
	if (isInArray(avail[i][2], days) === false) {
		days.push(avail[i][2]);
	}
}

//sorting the days
days.sort(function(a, b) {return a - b});

var count_M = 0;
var count_F = 0;
var guests = 0;
var max_guests = 0;

// each iteration in this loop is a new day
for (var i = 0; i < days.length; i++) {

	// setting counters back to 0 each new day
	count_M = 0;
	count_F = 0;

	// each iteration in this loop is a new person --> checking every person on each day
	for (var j = 0; j < n; j++) {
		// checking availability of each person
		if (Number(days[i]) >= Number(avail[j][1]) && Number(days[i]) <= Number(avail[j][2])) {
			//for each person available that day check if male or female and add counter
			if (avail[j][0] == 'M') {
				count_M += 1;
			} else {
				count_F += 1;
			}
		}
	}
	// determining number of Female + Male pairs (*2 to get # of people)
	guests = Math.min(count_M, count_F) * 2;
	if (guests > max_guests) {
		max_guests = guests;
	}
}

print(max_guests);

'use strict';

const n = Number(readline());
let dates = Array(400).fill(0);

for (let i = 0; i < n; i++) {
  const line = readline().split(' ')

  for (let j = Number(line[1]); j < Number(line[2])+1; j++) {
    dates[j] += line[0] === 'M' ? 1 : 10000;
  }
}

let _dates = [...new Set(dates)]

let result = 0;
while (_dates.length !== 0) {
  let _result = _dates.pop();
  result = Math.max(result, Math.min(_result/10000|0, _result%10000));
}

print(result * 2);

var n = Number(readline());
var sex = new Array(n);
var l = new Array(n);
var r = new Array(n);
for (var i = 0; i < n; ++i) {
    var str = readline().split(" ", 3);
    sex[i] = str[0];
    l[i] = Number(str[1]);
    r[i] = Number(str[2]);
}

var ans = 0;
for (var i = 1; i <= 366; ++i) {
    var a = 0, b = 0;
    for (var j = 0; j < n; ++j) {
        if (l[j] <= i && r[j] >= i) {
            if (sex[j] == "M") {
                ++a;
            } else {
                ++b;
            }
        }
    }
    ans = Math.max(ans, Math.min(a, b) * 2);
}
print(ans);

var readInt = () => parseInt(readline())
var readIntArray = () => readline().split(' ').forEach(item => parseInt(item))
Array.prototype.fill = function(value) {
    for (var i = 0; i < this.length; i++)
        this[i] = value
    return this
}

var N = readInt()
var boys = (new Array(366)).fill(0)
var girls = new Array(366).fill(0)

for (var  i = 0; i < N; i++) {
    var f = readline().split(' ')
    var a = (f[0] === 'M' ? boys : girls)

    for (var n = parseInt(f[2]), j = parseInt(f[1])-1; j < n; j++) {
        a[j] += 1
    }
}
var ans = 0
for (var i = 0; i < 366; i++) {
    ans = Math.max(ans, 2*Math.min(boys[i], girls[i]))
}
print(ans)

var n = +readline();
var arr = [];
for(var i=0;i<n;i++)
arr.push(readline());
print(main(n, arr));
function main(n, arr) {
	var ms = {}, fs = {};
	arr.forEach(function(p){
		var p = p.split(' ');
		for (var i = +p[1]; i<=+p[2]; i++)
		{
			if (p[0]=='M')
				ms[i] = (ms[i]|0)+1;
			else
				fs[i] = (fs[i]|0)+1;
		}
	});
	var ans = 0;
	for(var i = 1; i<366; i++){
		ans = Math.max(ans, Math.min(ms[i]|0, fs[i]|0));
	}
	return ans*2;
}

'use strict';

const n = Number(readline());
let dates = Array(400).fill(0);

for (let i = 0; i < n; i++) {
  const line = readline().split(' ')

  for (let j = Number(line[1]); j < Number(line[2])+1; j++) {
    dates[j] += line[0] === 'M' ? 1 : 10000;
  }
}

let _dates = [...new Set(dates)]
_dates.sort()

let result = 0;
while (_dates) {
  let _result = _dates.pop();
  if (_result % 10001 === 0) {
    result = 2 * _result/10001;
    break;
  }
}

print(result);

var n = Number(readline());
var sex = new Array(n);
var l = new Array(n);
var r = new Array(n);
for (var i = 0; i < n; ++i) {
    var str = readline().split(" ", 3);
    sex[i] = str[0];
    l[i] = Number(str[1]);
    r[i] = Number(str[2]);
}

var ans = 0;
for (var i = 1; i <= 366; ++i) {
    var a = 0, b = 0;
    for (var j = 0; j < n; ++j) {
        if (l[j] <= i && r[j] >= i) {
            if (sex[j] == "M") {
                ++a;
            } else {
                ++b;
            }
        }
    }
    ans = Math.max(ans, Math.min(a, b));
}
print(ans);