/**
 *  CodeForces/312 C. Replace To Make Regular Bracket Sequence
 *
 *  @author Brooks Mershon
 *
 */

// return Impossible or the least amount of exchanges to fix bracket sequence
function replace(x) {
  var N = x.length,
      count = 0,
      invalid = "Impossible";

  var open  = ['<', '{', '[', '('],
      close = ['>', '}', ']', ')'];

  // scan to check whether the sequence is balanced
  var d = 0;
  for(var i = 0; i < N; i++) {
    d += (open.indexOf(x.charAt(i)) > -1) ? 1 : -1;
    if (d < 0) return invalid;
  }

  if (d !== 0) return invalid;

  var q = [];
  // greedy search for matching parenthesis
  var k = -1;
  while(k < x.length - 1) {
    while(open.indexOf(x.charAt(++k)) > -1) { // iterate to next closing bracket
      q.push(x.charAt(k));
    }
    var opener = q.pop();
    if (open.indexOf(opener) !== close.indexOf(x.charAt(k))) count++;
  }

  return count;
}

// Codeforces I/O
print(replace(readline()));

//module.exports = replace;

// 'use strict';

// var s = '[][][{([)})]';
var s = readline();

var impossible = false;

function get_opp(par) {
    if (par == '[') return ']';
    if (par == '<') return '>';
    if (par == '{') return '}';
    if (par == '(') return ')';
    if (par == ']') return '[';
    if (par == ')') return '(';
    if (par == '>') return '<';
    if (par == '}') return '{';
};

function is_op(par) {
    return par == '[' || par == '<' || par == '{' || par == '(';
};

function is_cl(par) {
    return par == ']' || par == '>' || par == '}' || par == ')';
};

var cl = [];
var op = [];

// function find_last_op() {
//     var max = -1;
//     for (var i in queues) {
//         if (is_op(i)) {
//             if (queues[i][queues[i].length - 1] > max) {
//                 max = queues[i][queues[i].length - 1];
//             }
//         }
//     }
//     return max;
// };

// function find_last_cl() {
//     var max = s.length;
//     for (var i in queues) {
//         if (is_cl(i)) {
//             if (queues[i][queues[i].length - 1] < max) {
//                 max = queues[i][queues[i].length - 1];
//             }
//         }
//     }
//     return max;
// };

function check_if_clear() {
    return !(op.length > 0 || cl.length > 0);
};

var cor_l = 0;

for (var i = 0; i < s.length && !impossible; i++) {
    if (is_cl(s[i])) {
        var last_op = op.pop();

        if (last_op === false) {
            impossible = false;
            break;
        }

        if (s[last_op] != get_opp(s[i])) {
            cor_l++;
        }
    } else {
        op.push(i)
    }
}
var cor_r = 0;
impossible = !check_if_clear() || impossible;

for (var i = s.length - 1; i >= 0 && !impossible; i--) {
    if (is_op(s[i])) {
        var last_cl = cl.pop();

        if (last_cl === false) {
            impossible = true;
            break;
        }
        if (s[last_cl] != get_opp(s[i])) {
            cor_r++;
        }
    } else {
        cl.push(i);
    }
}
impossible = !check_if_clear() || impossible;

// console.log(impossible ? 'Impossible' : Math.min(cor_r, cor_l));
print(impossible ? 'Impossible' : Math.min(cor_r, cor_l));

// console.log(cor_l);
// console.log(cor_r);

var input = readline();
var stack = new Array();

var library = {
    ROUND: { value: '()' },
    BOX: { value: '[]' },
    ANGLE: { value: '<>' },
    CURLY: { value: '{}' }
};

function GetNumberOfReplaces(input) {
    var counter = 0;
    for (var i = 0; i <= input.length; i++) {
        switch (input[i]) {
            case '[': { stack.push(library.BOX); break; }
            case '(': { stack.push(library.ROUND); break; }
            case '{': { stack.push(library.CURLY); break; }
            case '<': { stack.push(library.ANGLE); break; }
            case ']': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.BOX) { counter++ };
                }
                break;
            }
            case ')': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ROUND) { counter++ };
                }
                break;
            }
            case '}': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.CURLY) { counter++ };
                }
                break;
            }
            case '>': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ANGLE) { counter++ };
                }
                break;
            }
        }
    }
    if(stack.length != 0) { return -1; }
    return counter;
}

var replaces = GetNumberOfReplaces(input);
var result = '';
if (replaces >= 0) {
    result = replaces + '';
} else {
    result = 'Impossible';
}

print(result);

var s = readline().split("");
var pairs = { "<": ">", "{": "}", "[": "]", "(": ")" };
var isOpen = b => pairs.hasOwnProperty(b);
var stack = [];
var result = s.reduce((substitutions, b, i) => {
    if ( isOpen(b) ) {
        stack.push(b);
        return substitutions;
    } else {
        var previousB = stack.pop();
        if (previousB) {
            if (pairs[previousB] === b) {
                return substitutions;
            } else {
                return substitutions + 1;
            }
        }
    }
}, 0);

if ( typeof result === "undefined" || stack.length ) {
    result = "Impossible";
}
print(result);

// O(n) time complexity, O(n) additional space, where n is input string length.
var s = [...readline()];
var pairs = { "<": ">", "{": "}", "[": "]", "(": ")" };
var isOpen = b => pairs.hasOwnProperty(b);
var stack = [];
var answer = 0;

for (var b of s) {
    if ( isOpen(b) ) {
        stack.push(b);
    } else {
        var previousB = stack.pop();
        if (previousB) {
            if (pairs[previousB] != b) {
                ++answer;
            }
        } else {
            // Stack is empty - to many close braces.
            answer = undefined;
            break;
        }
    }
}
if ( typeof answer === "undefined" || stack.length ) {
    // If stack is not empty - too many open braces.
    answer = "Impossible";
}
print(answer);

var input = readline();
var stack = new Array();

var library = {
    ROUND: { value: '()' },
    BOX: { value: '[]' },
    ANGLE: { value: '<>' },
    CURLY: { value: '{}' }
};

function GetNumberOfReplaces(input) {
    var counter = 0;
    for (var i = 0; i <= input.length; i++) {
        switch (input[i]) {
            case '[': { stack.push(library.BOX); break; }
            case '(': { stack.push(library.ROUND); break; }
            case '{': { stack.push(library.CURLY); break; }
            case '<': { stack.push(library.ANGLE); break; }
            case ']': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.BOX) { counter++ };
                }
                break;
            }
            case ')': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ROUND) { counter++ };
                }
                break;
            }
            case '}': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.CURLY) { counter++ };
                }
                break;
            }
            case '>': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ANGLE) { counter++ };
                }
                break;
            }
        }
    }
    return counter;
}

var replaces = GetNumberOfReplaces(input);
var result = '';
if (replaces >= 0) {
    result = replaces + '';
} else {
    result = 'Impossible';
}

print(result);

var input = readline();
var stack = new Array();

var library = {
    ROUND: { value: '()' },
    BOX: { value: '[]' },
    ANGLE: { value: '<>' },
    CURLY: { value: '{}' }
};

function GetNumberOfReplaces(input) {
    var counter = 0;
    for (var i = 0; i <= input.length; i++) {
        switch (input[i]) {
            case '[': { stack.push(library.BOX); break; }
            case '(': { stack.push(library.ROUND); break; }
            case '{': { stack.push(library.CURLY); break; }
            case '<': { stack.push(library.ANGLE); break; }
            case ']': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.BOX) { counter++ };
                }
                break;
            }
            case ')': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ROUND) { counter++ };
                }
                break;
            }
            case '}': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.CURLY) { counter++ };
                }
                break;
            }
            case '>': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ANGLE) { counter++ };
                }
                break;
            }
        }
    }
    return counter;
}

var replaces = GetNumberOfReplaces(input);
var result = '';
if (replaces > 0) {
    result = replaces + '';
} else {
    result = 'Impossible';
}

print(result);

var input = readline();
var stack = new Array();

var library = {
    ROUND: { value: '()' },
    BOX: { value: '[]' },
    ANGLE: { value: '<>' },
    CURLY: { value: '{}' }
};

function GetNumberOfReplaces(input) {
    var counter = 0;
    for (var i = 0; i <= input.length; i++) {
        switch (input[i]) {
            case '[': { stack.push(library.BOX); break; }
            case '(': { stack.push(library.ROUND); break; }
            case '{': { stack.push(library.CURLY); break; }
            case '<': { stack.push(library.ANGLE); break; }
            case ']': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.BOX) { counter++ };
                }
                break;
            }
            case ')': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ROUND) { counter++ };
                }
                break;
            }
            case '}': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.CURLY) { counter++ };
                }
                break;
            }
            case '>': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ANGLE) { counter++ };
                }
                break;
            }
        }
    }
    if (counter !== 0) return -1;
    return counter;
}

var replaces = GetNumberOfReplaces(input);
var result = '';
if (replaces > 0) {
    result = replaces + '';
} else {
    result = 'Impossible';
}

print(result);

var input = readline();
var stack = new Array();

var library = {
    ROUND: { value: '()' },
    BOX: { value: '[]' },
    ANGLE: { value: '<>' },
    CURLY: { value: '{}' }
};

function GetNumberOfReplaces(input) {
    var counter = 0;
    for (var i = 0; i <= input.length; i++) {
        switch (input[i]) {
            case '[': { stack.push(library.BOX); break; }
            case '(': { stack.push(library.ROUND); break; }
            case '{': { stack.push(library.CURLY); break; }
            case '<': { stack.push(library.ANGLE); break; }
            case ']': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.BOX) { counter++ };
                }
                break;
            }
            case ')': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ROUND) { counter++ };
                }
                break;
            }
            case '}': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.CURLY) { counter++ };
                }
                break;
            }
            case '>': {
                if (stack.length == 0) { return -1; } else {
                    if (stack.pop() !== library.ANGLE) { counter++ };
                }
                break;
            }
        }
    }
    if (counter === 0) return -1;
    return counter;
}

var replaces = GetNumberOfReplaces(input);
var result = '';
if (replaces > 0) {
    result = replaces + '';
} else {
    result = 'Impossible';
}

print(result);

var input = readline();
var stack = new Array();

var library = {
    ROUND: { value: '()' },
    BOX: { value: '[]' },
    ANGLE: { value: '<>' },
    CURLY: { value: '{}' }
};

function GetNumberOfReplaces(input) {
    var counter = 0;
    for (var i = 0; i <= input.length; i++) {
        if (input[i] == '[') { stack.push(library.BOX); break; }
        if (input[i] == '(') { stack.push(library.ROUND); break; }
        if (input[i] == '{') { stack.push(library.CURLY); break; }
        if (input[i] == '<') { stack.push(library.ANGLE); break; }
        if (input[i] == ']') {
            if (stack.length == 0) { return -1; } else {
                if (stack.pop() === library.BOX) counter++;
            }
            break;
        }
        if (input[i] == ')') {
            if (stack.length == 0) { return -1; } else {
                if (stack.pop() === library.ROUND) counter++;
            }
            break;
        }
        if (input[i] == '}') {
            if (stack.length == 0) { return -1; } else {
                if (stack.pop() === library.CURLY) counter++;
            }
            break;
        }
        if (input[i] == '>') {
            if (stack.length == 0) { return -1; } else {
                if (stack.pop() === library.ANGLE) counter++;
            }
            break;
        }
    }

    if(counter === 0) return -1;

    return counter;
}

var replaces = GetNumberOfReplaces(input);
var result = '';
if(replaces > 0) {
    result = replaces + '';
} else {
    result = 'Impossible';
}

print(result);

// O(n) time complexity, O(n) additional space, where n is input string length.
var s = [...readline()];
var pairs = { "<": ">", "{": "}", "[": "]", "(": ")" };
var isOpen = b => pairs.hasOwnProperty(b);
var stack = [];
var answer = 0;

for (var b of s) {
    if ( isOpen(b) ) {
        stack.push(b);
    } else {
        var previousB = stack.pop();
        if (previousB) {
            if (pairs[previousB] != b) {
                ++answer;
            }
        } else {
            // Stack is empty - to many close braces.
            answer = undefined;
            break;
        }
    }
}
if ( typeof answer === "undefined" || stack.length ) {
    // If stack is not empty - too many open braces.
    result = "Impossible";
}
print(answer);


var bsearch = function(A, x) {
    var l = 0;
    var r = A.length - 1;
    while (l <= r) {
        var m = Math.floor((r+l) / 2);
        if (A[m] == x) {
            return m;
        }
        else if (A[m] < x) {
            l = m + 1;
        }
        else {
            r = m - 1;
        }
    }
    return -1;
}

var main = function(n, k) {
    if (k == 1) {
        return n;
    }
    A = readline().split(' ').map(Number);
    A.sort(function(a, b) {
        return a - b;});

    var F = Array.apply(null,
            new Array(n)).map(Number.prototype.valueOf, 0);

    var cnt = 0;
    for (var i = n-1; i >= 0; i--) {
        var m = bsearch(A, A[i] * k);
        if (m >= 0 && F[m] == 0) {
            F[i] = 1;
        }
        else {
            cnt += 1;
        }
    }
    return cnt;
}

print(main.apply(null, readline().split(' ').map(Number)));

var inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur.trim());});
var n = inp[0], k = inp[1];
var a = {}, len = new Array(n);
inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur.trim());});
inp.sort(function(a,b){return a - b;});

for(var i = 0; i < n; i++) {
    a[inp[i]] = i;
    if(inp[i] % k == 0 && a[inp[i] / k] != undefined){
        var t = a[inp[i] / k];
        len[i] = len[t] + 1;
        len[t] = 0;
    }
    else len[i] = 1;
}
var ans = 0;
for(var i = 0; i < n; i++)
    ans += Math.floor((len[i] + 1) / 2);
print((k == 1)? n : ans);

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  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, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

/*/====================
var fs = require('fs');

fs.readFile('input.txt', 'utf8', function(err, arr) {
    main(arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, '')))
})
//====================*/
function max(a,b){
    if (a>b)
        return a
        return b
}
function main(input) {
    a=input[0].split(' ')
    n=+a[0]
    k=+a[1]
    a=input[1].split(' ').map(x => +x)
    E=new Object()
    for (i=0;i<n;i++){
        x=0
        if (k>1)
        while(a[i]%k==0){
            a[i]/=k
            ++x
        }
        if (E[a[i]]==undefined){
            E[a[i]]=new Array()
        }
        E[a[i]].push(x)
    }
    ans=0
    function solve(arr,key){
        sort(arr)
        dp=new Array(32)
        for (i=0;i<32;i++)
            dp[i]=0
        K=new Object()
        for (i=0;i<32;i++){
            K[i]=0
        }
        for (i=0;i<arr.length;i++)
        {
            ++K[arr[i]]
        }
        x=0
        for (i=0;i<32;i++)
        {
            dp[i]=K[i]
            if (i==2){
                dp[i]+=dp[i-2]
            } else if (i>2){
                dp[i]+=max(dp[i-2],dp[i-3])
            }
            if (dp[i]>x)
                x=dp[i]
        }
        ans+=x
    }

    for (key in E){
        solve(E[key],key)
    }
    wr(ans)
}

var bsearch = function(A, x) {
    var l = 0;
    var r = A.length - 1;
    while (l <= r) {
        var m = Math.floor((r+l) / 2);
        if (A[m] == x) {
            return m;
        }
        else if (A[m] < x) {
            l = m + 1;
        }
        else {
            r = m - 1;
        }
    }
    return -1;
}

var main = function(n, k) {
    if (k == 1) {
        return n;
    }
    A = readline().split(' ').map(Number);
    A.sort(function(a, b) {
        return a - b;});

    var F = Array.apply(null, {length: n}).map(function(x) {return 0});

    var cnt = 0;
    for (var i = n-1; i >= 0; i--) {
        var m = bsearch(A, A[i] * k);
        if (m >= 0 && F[m] == 0) {
            F[i] = 1;
        }
        else {
            cnt += 1;
        }
    }
    return cnt;
}

print(main.apply(null, readline().split(' ').map(Number)));

function sort(ar, n, f) {
    var p = Math.ceil(Math.random() * n);
    var i = 0, j = n - 1;
    while(i < j) {
        while(f(ar[i], ar[p]) <= 0) i++;
        while(f(ar[j], ar[p]) > 0) j--;
        if(i < j) {
            var c = ar[i];
            ar[i] = ar[j], ar[j] = c;
        }
        i++; j--;
    }
}

var inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur.trim());});
var n = inp[0], k = inp[1];
var a = {}, len = new Array(n);
inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur.trim());});
sort(inp, n, function(a,b){return a - b;});

for(var i = 0; i < n; i++) {
    a[inp[i]] = i;
    if(inp[i] % k == 0 && a[inp[i] / k] != undefined){
        var t = a[inp[i] / k];
        len[i] = len[t] + 1;
        len[t] = 0;
    }
    else len[i] = 1;
}
var ans = 0;
for(var i = 0; i < n; i++)
    ans += Math.floor((len[i] + 1) / 2);
print((k == 1)? n : ans);

var inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur.trim());});
var n = inp[0], k = inp[1];
var a = {}, len = new Array(n);
inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur.trim());});
inp.sort(function(a,b){return a - b;});

for(var i = 0; i < n; i++) {
    a[inp[i]] = i;
    if(inp[i] % k == 0 && a[inp[i] / k] != undefined){
        var t = a[inp[i] / k];
        len[i] = len[t] + 1;
        len[t] = 0;
    }
    else len[i] = 1;
}
var ans = 0;
for(var i = 0; i < n; i++)
    ans += Math.floor((len[i] + 1) / 2);
print(ans);

var inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur.trim());});
var n = inp[0], k = inp[1];
var a = {}, c = -1, len = new Array(n);
inp = readline().split(' ').map(function(cur,i,ar){return parseInt(cur);});
inp.sort(function(a,b){return a - b;});

for(var i = 0; i < n; i++) {
    a[inp[i]] = ++c;
    //print(inp[i] + ' ' + c);
    if(inp[i] % k == 0 && a[inp[i] / k] != undefined){
        len[c] = len[a[inp[i] / k]] + 1;
        len[a[inp[i] / k]] = 0;
    }
    else len[c] = 1;
}
var ans = 0;
for(var i = 0; i < n; i++)
    ans += Math.floor((len[i] + 1) / 2);
print(ans);

var bsearch = function(A, x) {
    var l = 0;
    var r = A.length - 1;
    while (l <= r) {
        var m = Math.floor((r+l) / 2);
        if (A[m] == x) {
            return true;
        }
        else if (A[m] < x) {
            l = m + 1;
        }
        else {
            r = m - 1;
        }
    }
    return false;
}

var main = function(n, k) {
    if (k == 1) {
        return n;
    }
    A = readline().split(' ').map(Number);
    A.sort(function(a, b) {
        return a - b;});

    var cnt = 0;
    for (i in A) {
        if (bsearch(A, A[i] * k)) {
            //
        }
        else {
            cnt += 1;
        }
    }
    return cnt;
}

print(main.apply(null, readline().split(' ').map(Number)));

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  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, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

/*/====================
var fs = require('fs');

fs.readFile('input.txt', 'utf8', function(err, arr) {
    main(arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, '')))
})
//====================*/
function max(a,b){
    if (a>b)
        return a
        return b
}
function main(input) {
    a=input[0].split(' ')
    n=+a[0]
    k=+a[1]
    a=input[1].split(' ').map(x => +x)
    E=new Object()
    for (i=0;i<n;i++){
        x=0
        if (k>1)
        while(a[i]%k==0){
            a[i]/=k
            ++x
        }
        if (E[a[i]]==undefined){
            E[a[i]]=new Array()
        }
        E[a[i]].push(x)
    }
    ans=0
    function solve(arr,key){
        sort(arr)
        dp=new Array(32)
        for (i=0;i<32;i++)
            dp[i]=0
        K=new Object()
        for (i=0;i<32;i++){
            K[i]=0
        }
        for (i=0;i<arr.length;i++)
        {
            ++K[arr[i]]
        }
        x=0
        for (i=0;i<32;i++)
        {
            dp[i]=K[i]
            if (i==2){
                dp[i]+=dp[i-2]
            } else if (i>2){
                dp[i]+=max(dp[i-2],dp[i-1])
            }
            if (dp[i]>x)
                x=dp[i]
        }
        wr(key,arr,x)
        ans+=x
    }

    for (key in E){
        solve(E[key],key)
    }
    wr(ans)
}

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  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, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

/*/====================
var fs = require('fs');

fs.readFile('input.txt', 'utf8', function(err, arr) {
    main(arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, '')))
})
//====================*/
function max(a,b){
    if (a>b)
        return a
        return b
}
function main(input) {
    a=input[0].split(' ')
    n=+a[0]
    k=+a[1]
    a=input[1].split(' ').map(x => +x)
    E=new Object()
    for (i=0;i<n;i++){
        x=0
        while(a[i]%k==0){
            a[i]/=k
            ++x
        }
        if (E[a[i]]==undefined){
            E[a[i]]=new Array()
        }
        E[a[i]].push(x)
    }
    ans=0
    function solve(arr){
        sort(arr)
        dp=new Array(32)
        for (i=0;i<32;i++)
            dp[i]=0
        K=new Object()
        for (i=0;i<32;i++){
            K[i]=0
        }
        for (i=0;i<arr.length;i++)
        {
            ++K[arr[i]]
        }
        x=0
        for (i=0;i<32;i++)
        {
            dp[i]=K[i]
            if (i==2){
                dp[i]+=dp[i-2]
            } else if (i>2){
                dp[i]+=max(dp[i-2],dp[i-1])
            }
            if (dp[i]>x)
                x=dp[i]
        }
        ans+=x
    }

    for (key in E){
        solve(E[key])
    }
    wr(ans)
}

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  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, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

/*/====================
var fs = require('fs');

fs.readFile('input.txt', 'utf8', function(err, arr) {
    main(arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, '')))
})
//====================*/
function max(a,b){
    if (a>b)
        return a
        return b
}
function main(input) {
    a=input[0].split(' ')
    n=+a[0]
    k=+a[1]
    a=input[1].split(' ').map(x => +x)
    E=new Object()
    for (i=0;i<n;i++){
        x=0
        if (k>1)
        while(a[i]%k==0){
            a[i]/=k
            ++x
        }
        if (E[a[i]]==undefined){
            E[a[i]]=new Array()
        }
        E[a[i]].push(x)
    }
    ans=0
    function solve(arr,key){
        sort(arr)
        dp=new Array(32)
        for (i=0;i<32;i++)
            dp[i]=0
        K=new Object()
        for (i=0;i<32;i++){
            K[i]=0
        }
        for (i=0;i<arr.length;i++)
        {
            ++K[arr[i]]
        }
        x=0
        for (i=0;i<32;i++)
        {
            dp[i]=K[i]
            if (i==2){
                dp[i]+=dp[i-2]
            } else if (i>2){
                dp[i]+=max(dp[i-2],dp[i-1])
            }
            if (dp[i]>x)
                x=dp[i]
        }
        ans+=x
    }

    for (key in E){
        solve(E[key],key)
    }
    wr(ans)
}

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  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, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

/*/====================
var fs = require('fs');

fs.readFile('input.txt', 'utf8', function(err, arr) {
    main(arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, '')))
})
//====================*/
function max(a,b){
    if (a>b)
        return a
        return b
}
function main(input) {
    a=input[0].split(' ')
    n=+a[0]
    k=+a[1]
    a=input[1].split(' ').map(x => +x)
    E=new Object()
    for (i=0;i<n;i++){
        x=0
        if (k>1)
        while(a[i]%k==0){
            a[i]/=k
            ++x
        }
        if (E[a[i]]==undefined){
            E[a[i]]=new Array()
        }
        E[a[i]].push(x)
    }
    ans=0
    function solve(arr,key){
        sort(arr)
        dp=new Array(32)
        for (i=0;i<32;i++)
            dp[i]=0
        K=new Object()
        for (i=0;i<32;i++){
            K[i]=0
        }
        for (i=0;i<arr.length;i++)
        {
            ++K[arr[i]]
        }
        x=0
        for (i=0;i<32;i++)
        {
            dp[i]=K[i]
            if (i==2){
                dp[i]+=dp[i-2]
            } else if (i>2){
                dp[i]+=max(dp[i-2],dp[i-1])
            }
            if (dp[i]>x)
                x=dp[i]
        }
        wr(key,arr,x)
        ans+=x
    }

    for (key in E){
        solve(E[key],key)
    }
}


var t = +readline()
while (t--) {
    var str = readline()
    min = 9

    var tmp = []

    for (var i = str.length - 1; i >= 0; i--) {
        if (str[i] <= min) {
            min = str[i]
            tmp.push(min)
        } else {
            tmp.push(Math.min(Number(str[i]) + 1, 9))
        }
    }

    var ans = tmp.sort(function (a, b) { return a - b }).join("")
    print(ans)
}

'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 _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(read) {
  const nums = read().split('').map((s, i) => [Number(s), i]),
        n = nums.length;
  const a = new Heap((a, b) => {
    if (a[0] !== b[0]) return a[0] - b[0];
    return a[1] - b[1];
  });
  for (let i = 0; i < n; i++) a.push(nums[i]);
  const b = new Heap((a, b) => a - b);
  const res = [];
  for (let i = 0; i < n; i++) {
    while (a.size() && a.top()[1] < i) a.pop();
    if (!a.size()) break;
    while (b.size() && b.top() <= a.top()[0]) {
      res.push(b.pop());
    }
    if (a.top()[0] === nums[i][0]) {
      res.push(nums[i][0]);
      a.pop();
    } else {
      b.push(Math.min(nums[i][0] + 1, 9));
    }
  }
  while (b.size()) {
    res.push(b.pop());
  }
  return res.join('');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

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

"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 arr = readline().trim().split("").map(cur=>parseInt(cur));
          for(let i=0;i<arr.length;i++) arr[i] = [arr[i],i];
          arr.sort((a,b)=>{
               if(a[0]===b[0]) return a[1]-b[1];
               else return a[0]-b[0];
               });
          let max = arr[0][1];
          for(let i=0;i<arr.length;i++){
               if(arr[i][1]<max) arr[i][0] = Math.min(arr[i][0]+1,9);
               max = Math.max(max,arr[i][1]);
          }
          arr.sort((a,b)=>a[0]-b[0]);
          let res = [];
          for(let i=0;i<arr.length;i++) res.push(arr[i][0]);
          console.log(res.join(""));
     }
};
solve();

var t = +readline()
while (t--) {
    var str = readline()
    min = 9

    var tmp = []
    var tmp2 = []

    for (var i = str.length - 1; i >= 0; i--) {
        if (str[i] <= min) {
            min = str[i]
            tmp2.push(min)
        } else {
            tmp.push(Math.min(Number(str[i]) + 1, 9))
        }
    }

    var ans = tmp.concat(tmp2).sort(function (a, b) { return a - b }).join("")
    print(ans)
}

'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 _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(read) {
  const nums = read().split('').map((s, i) => [Number(s), i]),
        n = nums.length;
  const a = new Heap((a, b) => {
    if (a[0] !== b[0]) return a[0] - b[0];
    return a[1] - b[1];
  });
  for (let i = 0; i < n; i++) a.push(nums[i]);
  const b = new Heap((a, b) => a - b);
  const res = [];
  for (let i = 0; i < n; i++) {
    while (a.size() && a.top()[1] < i) a.pop();
    if (!a.size()) break;
    while (b.size() && b.top() === a.top()[0]) {
      res.push(b.pop());
    }
    if (a.top()[0] === nums[i][0]) {
      res.push(nums[i][0]);
      a.pop();
    } else {
      b.push(Math.min(nums[i][0] + 1, 9));
    }
  }
  while (b.size()) {
    res.push(b.pop());
  }
  return res.join('');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

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

"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 arr = readline().trim().split("").map(cur=>parseInt(cur));
          for(let i=0;i<arr.length;i++) arr[i] = [arr[i],i];
          arr.sort((a,b)=>{
               if(a[0]===b[0]) return a[1]-b[1];
               else return a[0]-b[0];
               });
          let max = arr[0][1];
          for(let i=0;i<arr.length;i++){
               if(arr[i][1]<max) arr[i][0] = Math.min(arr[i][0]+1,9);
               max = Math.max(max,arr[i][1]);
          }
          let res = [];
          for(let i=0;i<arr.length;i++) res.push(arr[i][0]);
          console.log(res.join(""));
     }
};
solve();

"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 arr = readline().trim().split("").map(cur=>parseInt(cur));
          for(let i=0;i<arr.length;i++) arr[i] = [arr[i],i];
          arr.sort((a,b)=>{
               if(a[0]===b[0]) return a[1]-b[1];
               else return a[0]-b[0];
               });
          let flag = 0;
          for(let i=1;i<arr.length;i++){
               if(flag===1){
                    arr[i][0] = Math.min(arr[i][0]+1,9);
                    continue;
               }
               if(arr[i-1][1]>arr[i][1]){
                    flag = 1;
                    arr[i][0] = Math.min(arr[i][0]+1,9);
               }
          }
          let res = [];
          for(let i=0;i<arr.length;i++) res.push(arr[i][0]);
          console.log(res.join(""));
     }
};
solve();


'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(readLine());

    while(testCases--) {

        const n = parseInt(readLine());

        const s = readLine();

        b(n,s);

    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function b(n,s){
    let t = [];
    let m = [];
    let cnt = 0;
        for(let i= 0 ; i < n; i++) s[i] === 'T' ? t.push(i) : m.push(i);
        if(t.length/m.length !== 2) return console.log('NO');
        for(let i = 0; i < m.length; i++)
            if(m[i] < t[i] || m[i] > t[i + m.length]) return console.log('NO');
    return console.log('YES');
}

module.exports = b

"use strict";
//////////// LIBS
Object.defineProperty(exports, "__esModule", { value: true });
class IO {
    constructor() {
        this.lines = [];
        this.tokens = [];
        this.lines = require('fs').readFileSync(0, 'utf8').split('\n');
    }
    getTokens() {
        if (!this.tokens.length) {
            this.tokens = this.nextLine().split(' ');
        }
        return this.tokens;
    }
    nextLine() {
        return this.lines.shift().trim();
    }
    nextNum() {
        return Number(this.getTokens().shift());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
}
function solve(n, str) {
    let m = [];
    let t = [];
    str.split('').forEach((c, i) => {
        if (c === 'T') {
            t.push(i);
        }
        else {
            m.push(i);
        }
    });
    if (m.length * 2 !== t.length) {
        console.log('NO');
        return;
    }
    for (let i = 0; i < m.length; i++) {
        if (t[i] > m[i] || t[i + m.length] < m[i]) {
            console.log('NO');
            return;
        }
    }
    console.log('YES');
}
function main() {
    const io = new IO();
    let t = io.nextNum();
    while (t--) {
        let n = io.nextNum();
        let str = io.nextLine();
        solve(n, str);
    }
}
main();

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

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

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var s = next();
		var T = [];
		var M = [];
		for(var j = 0; j < N; j++){
			if(s[j] == "T"){
				T.push(j);
			}else{
				M.push(j);
			}
		}
		if(T.length == M.length * 2){
			var isOK = true;
			for(var j = 0; j < M.length; j++){
				if(M[j] < T[j] || M[j] > T[j + M.length]){
					isOK = false;
					break;
				}
			}
			myout((isOK) ? "YES" : "NO");
		}else{
			myout("NO");
		}
	}
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1);

	for (let i=1; i<lines.length; i+=2) {
		const str = lines[i].trim();

		let tCounter = 0;
		let mCounter = 0;
		let tCounter2 = 0;
		let mCounter2 = 0;

		let flag = true;

		for (let j=0; j<str.length; j++) {
			if (str[str.length-1-j] === 'M') {
				mCounter2++;

				if (mCounter2 > tCounter2) {
					flag = false;
					break;
				}
			}

			if (str[str.length-1-j] === 'T') {
				tCounter2++;
			}

			if (str[j] === 'M') {
				mCounter++;

				if (mCounter > tCounter) {
					flag = false;
					break;
				}
			}

			if (str[j] === 'T') {
				tCounter++;
			}
		}

		if (flag && (mCounter * 2 === tCounter)) {
			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 n = parseInt(readline());
    let str = readline().trim().split("");
    let tc = 0,
      mc = 0,
      ans = true;
    for (let i = 0; i < n; i++) {
      if (str[i] === "T") tc++;
      else mc++;
      if (mc > tc) {
        ans = false;
        break;
      }
    }
    if (ans === false) {
      console.log("NO");
      continue;
    }
    (tc = 0), (mc = 0);
    for (let i = n - 1; i >= 0; i--) {
      if (str[i] === "T") tc++;
      else mc++;
      if (mc > tc) {
        ans = false;
        break;
      }
    }
    if (ans === false) console.log("NO");
    else {
      if (tc / 2 === mc) console.log("YES");
      else console.log("NO");
    }
  }
};
solve();

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

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

let count = -1
let inputArr = []

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

function solve(n, str) {
    str = str.split('')
    let tc = 0, mc = 0, cc = 0
    for (let i = 0; i < n; i++) {
        if (str[i] === 'T') {
            tc++
            if (cc < 0) cc++
        } else {
            mc++
            cc--
        }
        if (mc > tc) return false
    }
    mc *= 2
    return !(cc !== 0 || mc !== tc)
}

function main() {
    for (let i = 0; i < inputArr.length; i += 2) {
        let res = solve(inputArr[i], inputArr[i + 1]);
        (res) ? console.log('YES') : console.log('NO')
    }
}

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = BigInt(1e9 + 7)

// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const xx = readline();
  Array(Number(xx)).fill(1).map((t, i) => {
    var n = parseInt(readline());
    // var [n, k] = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
    // })
    var a = readline().split('').map((x, iii) => {
      return x
    });
    var count1 = 0
    var count2 = 0

    for (let j = 0; j < n; j++) {
      if (a[j] === 'T') count1++
      if (a[j] === 'M') count2++
      if (a[j] === 'M' && count1 < count2) return console.log('NO')
    }
    count1 = 0
    count2 = 0

    for (let j = n - 1; j >= 0; j--) {
      if (a[j] === 'T') count1++
      if (a[j] === 'M') count2++
      if (a[j] === 'M' && count1 < count2) return console.log('NO')
    }
    if (count1 !== count2 * 2) return console.log('NO')
    console.log('YES')
  })
}

/**
 * 04/16/21 morning
 * https://codeforces.com/contest/1509/problem/B
 */

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
///////////////////////////////////////////////////////////////////////////////////

const solve = (n, s) => {
    let t = [];
    let m = [];
    for (let i = 0; i < n; i++) {
        s[i] == 'T' ? t.push(i) : m.push(i);
    }
    // pr(t, m)
    let tn = t.length;
    let mn = m.length;
    if (2 * mn != tn) return pr("NO");
    let res = [];
    while (1) {
        if (t.length == 0 || m.length == 0) break;
        let t1 = t.shift();
        let t2 = t.pop();
        let m1 = m.shift();
        // pr([t1, m1, t2]);
        if (m1 < t1 || m1 > t2) return pr("NO");
        res.push([t1, m1, t2]);
    }
    // pr(res);
    if (res.length * 3 != n) return pr("NO");
    pr("YES");
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line);
    });
    rl.on('close', () => {
        let t = Number(input[0]);
        let i = 1;
        while (t--) {
            solve(input[i], input[i + 1]);
            i += 2;
        }
    });
};

main()

/**
 * 04/16/21 morning
 * https://codeforces.com/contest/1509/problem/B
 */

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
///////////////////////////////////////////////////////////////////////////////////

const solve = (n, s) => {
    let t = [];
    let m = [];
    for (let i = 0; i < n; i++) {
        s[i] == 'T' ? t.push(i) : m.push(i);
    }
    // pr(t, m)
    let tn = t.length;
    let mn = m.length;
    if (2 * mn != tn) return pr("NO");
    let res = [];
    while (1) {
        if (t.length == 0 || m.length == 0) break;
        let t1 = t.shift();
        let t2 = t.pop();
        let m1 = m.shift();
        // pr([t1, m1, t2]);
        if (m1 < t1 || m1 > t2) return pr("NO");
        res.push([t1, m1, t2]);
    }
    // pr(res);
    pr("YES");
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line);
    });
    rl.on('close', () => {
        let t = Number(input[0]);
        let i = 1;
        while (t--) {
            solve(input[i], input[i + 1]);
            i += 2;
        }
    });
};

main()

'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(readLine());

    while(testCases--) {

        const n = parseInt(readLine());

        const s = readLine();

        let t = 0;
        let m = 0;
        let cnt = 0;
        for(let i= 0 ; i < n; i++){
            if(s[i] === 'T')
            {
                t++;
                if(cnt < 0) cnt++;
            }
            else
            {
                m++;
                cnt--;
            }
            if(m > t)
            {
                console.log('NO');
                break;
            }
        }
        cnt != 0 || m*2 != t ?  console.log('NO') : console.log('YES');
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(readLine());

    while(testCases--) {

        const n = parseInt(readLine());

        const s = readLine();

        let t = 0;
        let m = 0;
        let end = false;
        for(let i= 0 ; i < n; i++){
            if(s[i] === 'T') t++;
            else m++;
            if(m > t){
                console.log('NO');
                end = true;
                break;
            }
        }
        if(!end) m*2 === t ?  console.log('YES') : console.log('NO');

    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

"use strict";
//////////// LIBS
Object.defineProperty(exports, "__esModule", { value: true });
class IO {
    constructor() {
        this.lines = [];
        this.tokens = [];
        this.lines = require('fs').readFileSync(0, 'utf8').split('\n');
    }
    getTokens() {
        if (!this.tokens.length) {
            this.tokens = this.nextLine().split(' ');
        }
        return this.tokens;
    }
    nextLine() {
        return this.lines.shift();
    }
    nextNum() {
        return Number(this.getTokens().shift());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
}
function solve(n, str) {
    let m = [];
    let t = [];
    str.split('').forEach((c, i) => {
        if (c === 'T') {
            t.push(i);
        }
        else {
            m.push(i);
        }
    });
    if (m.length * 2 !== t.length) {
        console.log('NO');
        return;
    }
    for (let i = 0; i < m.length; i++) {
        if (t[i] > m[i] || t[i + m.length] < m[i]) {
            console.log('NO');
            return;
        }
    }
    console.log('YES');
}
function main() {
    const io = new IO();
    let t = io.nextNum();
    while (t--) {
        let n = io.nextNum();
        let str = io.nextLine();
        solve(n, str);
    }
}
main();

"use strict";
//////////// LIBS
Object.defineProperty(exports, "__esModule", { value: true });
class IO {
    constructor() {
        this.lines = [];
        this.tokens = [];
        this.lines = require('fs').readFileSync(0, 'utf8').split('\n');
    }
    getTokens() {
        if (!this.tokens.length) {
            this.tokens = this.nextLine().split(' ');
        }
        return this.tokens;
    }
    nextLine() {
        return this.lines.shift();
    }
    nextNum() {
        return Number(this.getTokens().shift());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
}
function solve(n, str) {
    let l = 0;
    let r = n - 1;
    let count = 0;
    for (let i = 0; i < n; i++) {
        if (str[i] === 'M') {
            count++;
        }
    }
    if (n / 3 !== count) {
        console.log('NO');
        return;
    }
    for (let i = 0; i < n; i++) {
        // console.log(str[i], { l, r });
        if (str[i] === 'M') {
            if (str[l] === 'M' || str[r] === 'M') {
                console.log('NO');
                return;
            }
            l++;
            r--;
            if (l == i) {
                l++;
            }
        }
    }
    console.log('YES');
}
function main() {
    const io = new IO();
    let t = io.nextNum();
    while (t--) {
        let n = io.nextNum();
        let str = io.nextLine();
        solve(n, str);
    }
}
main();

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

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

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var s = nextCharArray();
		var T = [];
		var M = [];
		for(var j = 0; j < N; j++){
			if(s[j] == "T"){
				T.push(j);
			}else{
				M.push(j);
			}
		}
		var isOK = true;
		for(var j = 0; j < M.length; j++){
			var index = M[j];
			var L = T[0];
			var R = T[T.length - 1];
			if(L < index && index < R){
				T.shift();
				T.pop();
			}else{
				isOK = false;
			}
		}
		if(isOK && T.length == 0){
			myout("YES");
		}else{
			myout("NO");
		}
	}
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1);

	for (let i=1; i<lines.length; i+=2) {
		const str = lines[i].trim();

		let tCounter = 0;
		let mCounter = 0;
		let flag = true;

		for (let j=0; j<str.length; j++) {
			if (str[j] === 'M') {
				mCounter++;

				if (mCounter > tCounter) {
					flag = false;
					break;
				}
			}

			if (str[j] === 'T') {
				tCounter++;
			}
		}

		if (flag && (mCounter * 2 === tCounter)) {
			console.log('YES')
		} else {
			console.log('NO')
		}
	}

})

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1);

	for (let i=1; i<lines.length; i+=2) {
		const str = lines[i].trim();

		let tCounter = 0;
		let mCounter = 0;
		for (let j=0; j<str.length; j++) {
			if (str[j] === 'M') {
				mCounter++;
			}

			if (str[j] === 'T') {
				tCounter++;
			}
		}

		if (
			mCounter*2 === tCounter &&
			str[0] !== 'M' &&
			str[str.length-1] !== 'M'
		) {
			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 n = parseInt(readline());
    let str = readline().trim().split("");
    let tc = 0,
      mc = 0,
      ans = true;
    for (let i = 0; i < n; i++) {
      if (str[i] === "T") tc++;
      else mc++;
      if (mc > tc) {
        ans = false;
        break;
      }
    }
    if (ans === false) console.log("NO");
    else {
      if (tc / 2 === mc) console.log("YES");
      else console.log("NO");
    }
  }
};
solve();


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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const mxN = 2e5+5;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const smex = [];
		let cnt = Array(mxN).fill(0);
		for (let i = n-1, cmex = 0; i >= 0; i--) {
			cnt[a[i]]++;
			while (cnt[cmex]) cmex++;
			smex[i] = cmex;
		}

		const ans = [];
		cnt = Array(mxN).fill(0);
		for (let i = 0, cmex = 0, L = 0; i < n; i++) {
			if (!cnt[a[i]]) cnt[a[i]] = 0;
			cnt[a[i]]++;
			while (cnt[cmex]) cmex++;
			if (cmex == smex[L])  {
				ans.push(cmex);
				cmex = 0;
				cnt = [];
				L = i + 1;
			}
		}

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

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const mxN = 2e5+5;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const smex = [];
		let cnt = [];
		for (let i = n-1, cmex = 0; i >= 0; i--) {
			cnt[a[i]] = cnt[a[i]] + 1 || 1;
			while (cnt[cmex]) cmex++;
			smex[i] = cmex;
		}

		const ans = [];
		cnt = [];
		for (let i = 0, cmex = 0, L = 0; i < n; i++) {
			cnt[a[i]] = cnt[a[i]] + 1 || 1;
			while (cnt[cmex]) cmex++;
			if (cmex == smex[L]) {
				ans.push(cmex);
				cmex = 0;
				cnt = [];
				L = i + 1;
			}
		}

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

// https://codeforces.com/problemset/problem/1628/A

/* 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() {
    //take input according to the format;
    const t = +(readline());
    for(let i =0; i<t; ++i){
        const n = +(readline());
        const arr = readline().split(' ').map(el=>parseInt(el));
        const sol = findMeximum(arr);
        console.log(sol.length)
        for(let el of sol){
            process.stdout.write(`${el} `)
        }
        console.log()
    }
}

findMeximum = (arr)=>{
    let lowerBound = (arr, target)=>{
        if(arr.length == 0 )
            return undefined;
        let start = 0, end = arr.length;
        while(start !== end){
            const middle = Math.floor((start + end) / 2);

            if(arr[middle] < target){
                start = middle + 1;
            }
            else{
                end = middle;
            }
        }
        if(arr[start] >= target){
            return arr[start]
        }
        else{
            return undefined;
        }
    }
    // find pos array

    let max = arr.length;
    // for(let el of arr){
    //     max = Math.max(max,el)
    // }
    let pos = new Array(max+1);

    for(let i =0; i<= max; ++i){
        pos[i] = [];
    }

    for(let i=0; i<arr.length; ++i){

        try{
            pos[arr[i]].push(i);
        }
        catch(e){
            console.log(e, i, arr[i], pos.length)
            break;
        }
    }
    let l = 0, r = 0;
    let sol = [];
    while(l < arr.length){
        let mex = 0;
        r = l;

        for(;mex<=max; ++mex){
            const elPos = lowerBound(pos[mex], l);
            if(elPos!= undefined){
                r = Math.max(elPos, r);
            }
            else{// mex is not present
                break;
            }

        }

        l = r + 1
        sol.push(mex);
    }
    return sol;

}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const freq = Array(n+1).fill(0);
		const delP = Array(n+1).fill(-1);

		for (let i = 0; i < n; i++) freq[a[i]]++;

		let mexC = 0;
		while (mexC < n && freq[mexC]) mexC++;

		const ans = [];
		let cnt = 0, lftP = 0, mexN = mexC;
		for (let i = 0; i < n; i++) {
			if (a[i] < mexC && delP[a[i]] < lftP) cnt++;

			freq[a[i]]--;
			if (freq[a[i]] == 0) mexN = Math.min(mexN, a[i]);

			delP[a[i]] = i;

			if (cnt == mexC) {
				ans.push(mexC);
				mexC = mexN;
				lftP = i + 1;
				cnt = 0;
			}
		}

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

// https://codeforces.com/problemset/problem/1628/A

/* 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() {
    //take input according to the format;
    const t = +(readline());
    for(let i =0; i<t; ++i){
        const n = +(readline());
        const arr = readline().split(' ').map(el=>parseInt(el));
        const sol = findMeximum(arr);
        console.log(sol.length)
        for(let el of sol){
            process.stdout.write(`${el} `)
        }
        console.log()
    }
}
findMeximum = (arr)=>{
    // find pos array

    let max = 0;
    for(let el of arr){
        max = Math.max(max,el)
    }
    console.log(max)
    let pos = new Array(max+1);

    for(let i =0; i<= max; ++i){
        pos[i] = [];
    }

    for(let i=0; i<arr.length; ++i){

        try{
            pos[arr[i]].push(i);
        }
        catch(e){
            console.log(e, i, arr[i], pos.length)
            break;
        }
    }
    let l = 0, r = 0;
    let sol = [];
    while(l < arr.length){
        let mex = 0;
        r = l;

        for(;mex<=max; ++mex){
            const elPos = pos[mex].find(el=>el >=l)
            if(elPos!= undefined){
                r = Math.max(elPos, r);
            }
            else{// mex is not present
                break;
            }

        }

        l = r + 1
        sol.push(mex);
    }
    return [...sol];

}


var n = +readline(), d = readline().split(" ").map(Number), input = readline().split(" "),
s = +input[0], t = +input[1];
var cnt1 = 0, cnt2 = 0, check = true;

if(s == t){
	write(0);
	check = false;
}
else{
	for(var i = s-1; ;){
		cnt1 += d[i];
		i = (i == n-1) ? 0 : i+1;
		if(i == t-1){
			break;
		}
	}
	for(var i = ((s-2 < 0) ? n-1 : s-2); ;){
		cnt2 += d[i];
		i = (i == 0) ? n-1 : i-1;
		if(i == ((t-2 < 0) ? n-1 : t-2)){
			break;
		}
	}
}

if(check){
	write(Math.min(cnt1, cnt2));
}

var n=+readline();
var d=readline().split(' ').map(function(v){return+v});
var l=readline().split(' ');
var s=+l[0]-1;
var t=+l[1]-1;
var a=d.splice(Math.min(s, t), Math.abs(t-s) ).reduce(function(sum, v){return sum+v},0);
var b=d.reduce(function(sum, v){return sum+v},0);
print(Math.min(a,b));

;(function () {

	var n = +readline();
	var s = readline().split(' ').map(function (i) { return +i; });
	var p = readline().split(' ').map(function (i) { return +i; }).sort(function (a, b) { return a - b; });

	if (p[0] == p[1]) {
		print( 0 );
		return;
	} else {
		p[0]--;
		p[1]--;
	}

	var a = s.slice(p[0], p[1]).reduce(function (p, c, i, a) { return p + c; }, 0);
	var b = s.reduce(function (p, c, i, a) { return p + c; }, 0);

	print( Math.min(a, b-a) );

}).call(this);

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

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

  if (c === 1) {
    arr = d.split(' ').map(Number);
    c++;
    return;
  }

  let [start, end] = d.split(' ').map(Number);
  let left = 0;
  let right = 0;
  start--;
  end--;

  let x = start;
  let y = end;

  while(x !== y) {
    left += arr[x];
    x = (x + 1) % arr.length;
  }

  x = start;
  y = end;

  while (x !== y) {
    let r = (x - 1) % arr.length;
    if (r < 0) {
      r = r + arr.length;
    }
    x = r;
    right += arr[x];
  }

  const ans = Math.min(left, right);

  console.log(ans);

  c++;
});

;(function () {

	var n = +readline();
	var s = readline().split(' ').map(function (i) { return +i; });
	var p = readline().split(' ').map(function (i) { return +i; }).sort(function (a, b) { return a - b; });

	if (p[0] == p[1]) {
		print( 0 );
		return;
	} else {
		p[0]--;
		p[1]--;
	}

	var a = s.slice(p[0], p[1] - p[0]).reduce(function (p, c, i, a) { return p + c; }, 0);
	var b = s.reduce(function (p, c, i, a) { return p + c; }, 0);

	print( Math.min(a, b-a) );

}).call(this);


print(function(n){
	var high = 1e9+5;
	var low = -1e9-5;
	for(var i=0; i<n; i++){
		var l = readline().split(' ');

		if(l[0] === '>='){
			if(l[2] === 'Y'){
				low = Math.max(+l[1], low);
			}else{
				high = Math.min(+l[1]-1, high);
			}
		}else if(l[0] === '<='){
			if(l[2] === 'Y'){
				high = Math.min(+l[1], high);
			}else{
				low = Math.max(+l[1]+1, low);
			}
		}else if(l[0] === '>'){
			if(l[2] === 'Y'){
				low = Math.max(+l[1]+1, low);
			}else{
				high = Math.min(+l[1], high);
			}
		}else if(l[0] === '<'){
			if(l[2] === 'Y'){
				high = Math.min(+l[1]-1, high);
			}else{
				low = Math.max(+l[1], low);
			}
		}
	}
	if( high >= low ){
		return low;
	}
	return 'Impossible';

}(+readline()));

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else if (v==">")
    r = "<=";
  return r;
}
var min_ = -2000000000;
var max_ = 2000000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = l[2];
  if(yn=="N")
    sign = f(sign);

  if(sign==">=")
    min_ = Math.max(num,min_);
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num - 1,max_);
  else if (sign==">")
    min_ = Math.max(num + 1,min_ );
}
if(min_ <= max_)
  print(min_);
else
  print("Impossible");

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else if (v==">")
    r = "<=";
  return r;
}
var min_ = -2000000000;
var max_ = 2000000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = l[2];
  if(yn=="N")
    sign = f(sign);//equivoque de variablr

  if(sign==">=")
    min_ = Math.max(num,min_);//libreria
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num - 1,max_);
  else if (sign==">")
    min_ = Math.max(num + 1,min_ );
}
if(min_ <= max_)
  print(min_);
else
  print("Impossible");

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

function tokenize(s) {
    return trim(s).split(/\s+/);
}
function main() {
    minValue=-2*1000*1000*1000;
    maxValue=2*1000*1000*1000;
    var n = trim(readline());
    for(var i=0; i<n; ++i) {
        var tokens=trim(readline()).split(/\s+/);
        var r=tokens[0];
        var x=parseInt(tokens[1]);
        var a=tokens[2];
        if("Y"==a) {
            if(">="==r) minValue=Math.max(minValue, x);
            if(">"==r) minValue=Math.max(minValue, x+1);
            if("<="==r) maxValue=Math.min(maxValue, x);
            if("<"==r) maxValue=Math.min(maxValue, x-1);
        } else {
            if("<"==r) minValue=Math.max(minValue, x);
            if("<="==r) minValue=Math.max(minValue, x+1);

            if(">"==r) maxValue=Math.min(maxValue, x);
            if(">="==r) maxValue=Math.min(maxValue, x-1);
        }
    }
    if(minValue<=maxValue) print(minValue);
    else print("Impossible");
}
main();

function main(n) {
    var eq, YN, num, minn = -2 * 1e9,
        maxn = 2 * 1e9;
    // var test = [">= 1 Y",
    //     "< 3 N",
    //     "<= -3 N",
    //     "> 55 N"
    // ];
    for (var i = 0; i < n; i++) {
        var li = readline().split(" ");
        eq = li[0], num = +li[1], YN = li[2];
        if (eq === ">=") {
            if (YN === "Y") {
                minn = Math.max(minn, num);
            } else {
                maxn = Math.min(maxn, num - 1);
            }
        } else if (eq === "<=") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num);
            } else {
                minn = Math.max(minn, num + 1);
            }
        } else if (eq === "<") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num - 1);
            } else {
                minn = Math.max(minn, num);
            }
        } else if (eq === ">") {
            if (YN === "Y") {
                minn = Math.max(minn, num + 1);
            } else {
                maxn = Math.min(maxn, num);
            }
        }
    }
    if (maxn < minn) {
        print("Impossible");
    } else {
        print(maxn + "");
    }
}
main(+readline())

print(function(n) {
    var eq, YN, num, minn = -2 * 1e9,
        maxn = 2 * 1e9;
    for (var i = 0; i < n; i++) {
        var li = readline().split(" ");
        eq = li[0], num = +li[1], YN = li[2];
        if (eq === ">=") {
            if (YN === "Y") {
                minn = Math.max(minn, num);
            } else {
                maxn = Math.min(maxn, num - 1);
            }
        } else if (eq === "<=") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num);
            } else {
                minn = Math.max(minn, num + 1);
            }
        } else if (eq === "<") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num - 1);
            } else {
                minn = Math.max(minn, num);
            }
        } else if (eq === ">") {
            if (YN === "Y") {
                minn = Math.max(minn, num + 1);
            } else {
                maxn = Math.min(maxn, num);
            }
        }
    }
    if (maxn < minn) {
        return "Impossible";
    } else {
        return maxn;
    }
}(+readline()))

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

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

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

function main() {
	var numConstraints = trim(readline()),
		minValue = -2*Math.pow(10, 9),
		maxValue = -minValue,
		inverse = { '<': '>=', '<=': '>', '>': '<=', '>=': '<' };
	for (var i = 0; i < numConstraints; ++i) {
		var tokens = trim(readline()).split(/\s+/),
			condition = tokens[0],
			limit = tokens[1],
			answer = tokens[2];
		if (answer == 'N') {
			condition = inverse[condition];
		}
		if (condition.charAt(0) == '>') {
			if (condition.length == 1) {
				++limit;
			}
			if (limit > maxValue) {
				print("Impossible");
				return;
			}
			minValue = Math.max(minValue, limit);
		} else {
			if (condition.length == 1) {
				--limit;
			}
			if (limit < minValue) {
				print("Impossible");
				return;
			}
			maxValue = Math.min(maxValue, limit);
		}
	}
	print(minValue);
}

main();

print(function(n){
	var high = 1e9;
	var low = -1e9;
	for(var i=0; i<n; i++){
		var l = readline().split(' ');

		if(l[0] === '>='){
			if(l[2] === 'Y'){
				low = Math.max(+l[1], low);
			}else{
				high = Math.min(l[1]-1, high);
			}
		}else if(l[0] === '<='){
			if(l[2] === 'Y'){
				high = Math.min(+l[1], high);
			}else{
				low = Math.max(l[1]+1, low);
			}
		}else if(l[0] === '>'){
			if(l[2] === 'Y'){
				low = Math.max(l[1]+1, low);
			}else{
				high = Math.min(+l[1], high);
			}
		}else if(l[0] === '<'){
			if(l[2] === 'Y'){
				high = Math.min(l[1]-1, high);
			}else{
				low = Math.max(+l[1], low);
			}
		}
	}
	if( high >= low ){
		return low;
	}
	return 'Impossible';

}(+readline()));

print(function(n){
	var high = 1e9;
	var low = -1e9;
	for(var i=0; i<n; i++){
		var l = readline().split(' ');

		if(l[0] === '>='){
			if(l[2] === 'Y'){
				low = Math.max(+l[1], low);
			}else{
				high = Math.min(+l[1]-1, high);
			}
		}else if(l[0] === '<='){
			if(l[2] === 'Y'){
				high = Math.min(+l[1], high);
			}else{
				low = Math.max(+l[1]+1, low);
			}
		}else if(l[0] === '>'){
			if(l[2] === 'Y'){
				low = Math.max(+l[1]+1, low);
			}else{
				high = Math.min(+l[1], high);
			}
		}else if(l[0] === '<'){
			if(l[2] === 'Y'){
				high = Math.min(+l[1]-1, high);
			}else{
				low = Math.max(+l[1], low);
			}
		}
	}
	if( high >= low ){
		return low;
	}
	return 'Impossible';

}(+readline()));

print(function(n){
    var high = 1e9+5;
    var low = -1e9-5;
    for(var i=0; i<n; i++){
        var l = readline().split(' ');

        if(l[0] === '>='){
            if(l[2] === 'Y'){
                low = Math.max(+l[1], low);
            }else{
                high = Math.min(+l[1]-1, high);
            }
        }else if(l[0] === '<='){
            if(l[2] === 'Y'){
                high = Math.min(+l[1], high);
            }else{
                low = Math.max(+l[1]+1, low);
            }
        }else if(l[0] === '>'){
            if(l[2] === 'Y'){
                low = Math.max(+l[1]+1, low);
            }else{
                high = Math.min(+l[1], high);
            }
        }else if(l[0] === '<'){
            if(l[2] === 'Y'){
                high = Math.min(+l[1]-1, high);
            }else{
                low = Math.max(+l[1], low);
            }
        }
    }
    if( high >= low ){
        return low;
    }
    return 'Impossible';

} );

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

function tokenize(s) {
    return trim(s).split(/\s+/);
}
function main() {
    minValue=-2*1000*1000*1000;
    maxValue=2*1000*1000*1000;
    var n = trim(readline());
    for(var i=0; i<n; ++i) {
        var tokens=trim(readline()).split(/\s+/);
        var r=tokens[0];
        var x=tokens[1];
        var a=tokens[2];
        if("Y"==a) {
            if(">="==r) minValue=Math.max(minValue, x);
            if(">"==r) minValue=Math.max(minValue, x+1);
            if(x==-6) print("aaaaaaaaaaaaaaa")
            if("<="==r) maxValue=Math.min(maxValue, x);
            if("<"==r) maxValue=Math.min(maxValue, x-1);
        } else {
            if("<"==r) minValue=Math.max(minValue, x);
            if("<="==r) minValue=Math.max(minValue, x+1);

            if(">"==r) maxValue=Math.min(maxValue, x);
            if(">="==r) maxValue=Math.min(maxValue, x-1);
        }
    }
    if(minValue<=maxValue) print(minValue);
    else print("Impossible");
}
main();

function trim(s) {
    return s.replace(/^\s+|\s+$/gm, '');
}
function tokenize(s) {
    return trim(s).split();
}
function integers(s) {
    var tokens = tokenize(s);
    for(var i=0; i<tokens.length; ++i) tokens[i]=parseInt(tokens[i]);
    return tokens;
}
function main() {
    minValue=-2*1000*1000*1000;
    maxValue=2*1000*1000*1000;
    var n = trim(readline());
    for(var i=0; i<n; ++i) {
        var tokens=trim(readline()).split(/\s+/);
        var r=tokens[0];
        var x=tokens[1];
        var a=tokens[2];
        if("Y"==a) {
            if(">="==r) minValue=Math.max(minValue, x);
            if(">"==r) minValue=Math.max(minValue, x+1);

            if("<="==r) maxValue=Math.min(maxValue, x);
            if("<"==r) maxValue=Math.min(maxValue, x-1);
        } else {
            if("<"==r) minValue=Math.max(minValue, x);
            if("<="==r) minValue=Math.max(minValue, x+1);

            if(">"==r) maxValue=Math.min(maxValue, x);
            if(">="==r) maxValue=Math.min(maxValue, x-1);
        }
    }
    if(minValue<=maxValue) print(minValue);
    else print("Impossible");
}
main();

function trim(s) {
    return s.replace(/^\s+|\s+$/gm, '');
}
function tokenize(s) {
    return trim(s).split();
}
function integers(s) {
    var tokens = tokenize(s);
    for(var i=0; i<tokens.length; ++i) tokens[i]=parseInt(tokens[i]);
    return tokens;
}
function main() {
    minValue=-2*1000*1000*1000;
    maxValue=-2*1000*1000*1000;
    var n = readline();
    for(var i=0; i<n; ++i) {
        var tokens=trim(readline()).split(/\s+/);
        var r=tokens[0];
        var x=tokens[1];
        var a=tokens[2];
        if("Y"==a) {
            if(">="==r) minValue=Math.max(minValue, x);
            if(">"==r) minValue=Math.max(minValue, x+1);

            if("<="==r) maxValue=Math.min(maxValue, x);
            if("<"==r) maxValue=Math.min(maxValue, x-1);
        } else {
            if("<"==r) minValue=Math.max(minValue, x);
            if("<="==r) minValue=Math.max(minValue, x+1);

            if(">"==r) maxValue=Math.min(maxValue, x);
            if(">="==r) maxValue=Math.min(maxValue, x-1);

        }
    }
    if(minValue<=maxValue) print(minValue);
    else print("Impossible");
}
main();

function trim(s) {
    return s.replace(/^\s+|\s+$/gm, '');
}
function tokenize(s) {
    return trim(s).split();
}
function integers(s) {
    var tokens = tokenize(s);
    for(var i=0; i<tokens.length; ++i) tokens[i]=parseInt(tokens[i]);
    return tokens;
}
function main() {
    minValue=-2*1000*1000*1000;
    maxValue=2*1000*1000*1000;
    var n = readline();
    for(var i=0; i<n; ++i) {
        var tokens=trim(readline()).split(/\s+/);
        var r=tokens[0];
        var x=tokens[1];
        var a=tokens[2];
        if("Y"==a) {
            if(">="==r) minValue=Math.max(minValue, x);
            if(">"==r) minValue=Math.max(minValue, x+1);

            if("<="==r) maxValue=Math.min(maxValue, x);
            if("<"==r) maxValue=Math.min(maxValue, x-1);
        } else {
            if("<"==r) minValue=Math.max(minValue, x);
            if("<="==r) minValue=Math.max(minValue, x+1);

            if(">"==r) maxValue=Math.min(maxValue, x);
            if(">="==r) maxValue=Math.min(maxValue, x-1);

        }
    }
    if(minValue<=maxValue) print(minValue);
    else print("Impossible");
}
main();

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

function tokenize(s) {
    return trim(s).split(/\s+/);
}
function main() {
    minValue=-2*1000*1000*1000;
    maxValue=2*1000*1000*1000;
    var n = trim(readline());
    for(var i=0; i<n; ++i) {
        var tokens=trim(readline()).split(/\s+/);
        var r=tokens[0];
        var x=tokens[1];
        var a=tokens[2];
        if("Y"==a) {
            if(">="==r) minValue=Math.max(minValue, x);
            if(">"==r) minValue=Math.max(minValue, x+1);

            if("<="==r) maxValue=Math.min(maxValue, x);
            if("<"==r) maxValue=Math.min(maxValue, x-1);
        } else {
            if("<"==r) minValue=Math.max(minValue, x);
            if("<="==r) minValue=Math.max(minValue, x+1);

            if(">"==r) maxValue=Math.min(maxValue, x);
            if(">="==r) maxValue=Math.min(maxValue, x-1);
        }
    }
    if(minValue<=maxValue) print(minValue);
    else print("Impossible");
}
main();

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

function tokenize(s) {
    return trim(s).split(/\s+/);
}
function main() {
    minValue=-2*1000*1000*1000;
    maxValue=2*1000*1000*1000;
    var n = trim(readline());
    for(var i=0; i<n; ++i) {
        var tokens=trim(readline()).split(/\s+/);
        var r=tokens[0];
        var x=tokens[1];
        var a=tokens[2];
        if("Y"==a) {
            if(">="==r) minValue=Math.max(minValue, x);
            if(">"==r) minValue=Math.max(minValue, x+1);
            if(x==-6) print("aaaaaaaaaaaaaaa" +  minValue)
            if("<="==r) maxValue=Math.min(maxValue, x);
            if("<"==r) maxValue=Math.min(maxValue, x-1);
        } else {
            if("<"==r) minValue=Math.max(minValue, x);
            if("<="==r) minValue=Math.max(minValue, x+1);

            if(">"==r) maxValue=Math.min(maxValue, x);
            if(">="==r) maxValue=Math.min(maxValue, x-1);
        }
    }
    if(minValue<=maxValue) print(minValue);
    else print("Impossible");
}
main();

function main(n) {
    var eq, YN, num, minn = -2 * 1e9,
        maxn = 2 * 1e9;
    for (var i = 0; i < n; i++) {
        var li = readline.split(" ");
        eq = li[0], num = +li[1], YN = li[2];
        if (eq === ">=") {
            if (YN === "Y") {
                minn = Math.max(minn, num);
            } else {
                maxn = Math.min(maxn, num - 1);
            }
        } else if (eq === "<=") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num);
            } else {
                minn = Math.max(minn, num + 1);
            }
        } else if (eq === "<") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num - 1);
            } else {
                minn = Math.max(minn, num);
            }
        } else if (eq === ">") {
            if (YN === "Y") {
                minn = Math.max(minn, num + 1);
            } else {
                maxn = Math.min(maxn, num);
            }
        }
    }
    if (1) {
        print("Impossible");
    } else {
        print(maxn + "");
    }
}(+readline())

function main(n) {
    var eq, YN, num, minn = -2 * 1e9,
        maxn = 2 * 1e9;
    for (var i = 0; i < n; i++) {
        var li = readline.split(" ");
        eq = li[0], num = +li[1], YN = li[2];
        if (eq === ">=") {
            if (YN === "Y") {
                minn = Math.max(minn, num);
            } else {
                maxn = Math.min(maxn, num - 1);
            }
        } else if (eq === "<=") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num);
            } else {
                minn = Math.max(minn, num + 1);
            }
        } else if (eq === "<") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num - 1);
            } else {
                minn = Math.max(minn, num);
            }
        } else if (eq === ">") {
            if (YN === "Y") {
                minn = Math.max(minn, num + 1);
            } else {
                maxn = Math.min(maxn, num);
            }
        }
    }
    if (maxn < minn) {
        print("Impossible");
    } else {
        print(maxn + "");
    }
}(+readline())

function main(n) {
    var eq, YN, num, minn = -2 * 1e9,
        maxn = 2 * 1e9;
    for (var i = 0; i < n; i++) {
        var li = readline.split(" ");
        eq = li[0], num = +li[1], YN = li[2];
        if (eq === ">=") {
            if (YN === "Y") {
                minn = Math.max(minn, num);
            } else {
                maxn = Math.min(maxn, num - 1);
            }
        } else if (eq === "<=") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num);
            } else {
                minn = Math.max(minn, num + 1);
            }
        } else if (eq === "<") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num - 1);
            } else {
                minn = Math.max(minn, num);
            }
        } else if (eq === ">") {
            if (YN === "Y") {
                minn = Math.max(minn, num + 1);
            } else {
                maxn = Math.min(maxn, num);
            }
        }
    }
    if (maxn < minn) {
        console.log("Impossible");
    } else {
        console.log(maxn);
    }
}(+readline)

function main(n) {
    var eq, YN, num, minn = -2 * 1e9,
        maxn = 2 * 1e9;
    for (var i = 0; i < n; i++) {
        var li = readline.split(" ");
        eq = li[0], num = +li[1], YN = li[2];
        if (eq === ">=") {
            if (YN === "Y") {
                minn = Math.max(minn, num);
            } else {
                maxn = Math.min(maxn, num - 1);
            }
        } else if (eq === "<=") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num);
            } else {
                minn = Math.max(minn, num + 1);
            }
        } else if (eq === "<") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num - 1);
            } else {
                minn = Math.max(minn, num);
            }
        } else if (eq === ">") {
            if (YN === "Y") {
                minn = Math.max(minn, num + 1);
            } else {
                maxn = Math.min(maxn, num);
            }
        }
    }
    if (maxn < minn) {
        print("Impossible");
    } else {
        print(maxn);
    }
}(+readline)

function main(n) {
    var eq, YN, num, minn = -2 * 1e9,
        maxn = 2 * 1e9;
    // var test = [">= 1 Y",
    //     "< 3 N",
    //     "<= -3 N",
    //     "> 55 N"
    // ];
    for (var i = 0; i < n; i++) {
        var li = readline().split(" ");
        eq = li[0], num = +li[1], YN = li[2];
        if (eq === ">=") {
            if (YN === "Y") {
                minn = Math.max(minn, num);
            } else {
                maxn = Math.min(maxn, num - 1);
            }
        } else if (eq === "<=") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num);
            } else {
                minn = Math.max(minn, num + 1);
            }
        } else if (eq === "<") {
            if (YN === "Y") {
                maxn = Math.min(maxn, num - 1);
            } else {
                minn = Math.max(minn, num);
            }
        } else if (eq === ">") {
            if (YN === "Y") {
                minn = Math.max(minn, num + 1);
            } else {
                maxn = Math.min(maxn, num);
            }
        }
    }
    if (maxn < minn) {
        print("Impossible");
    } else {
        print(maxn + "");
    }
}(+readline())

function main()
{
    var n = parseInt(readline());
    var up = 1<<30;
    var low = -up;
    while ( n-- )
    {
        var tmp = readline().split(" ");
        tmp[1] = parseInt(tmp[1]);
        if ( tmp[2] == "N" )
        {
            if ( tmp[0] == ">=" )
                tmp[0] = "<=";
            else if ( tmp[0] == "<=" )
                tmp[0] = ">=";
            else if ( tmp[0] == ">" )
                tmp[0] = "<";
            else if ( tmp[0] == "<" )
                tmp[0] = ">";
        }
        if ( tmp[0] == ">" )
        {
            if ( tmp[1]+1 > low )
                low = tmp[1]+1;
        }
        else if ( tmp[0] == ">=" )
        {
            if ( tmp[1] > low )
                low = tmp[1];
        }
        else if ( tmp[0] == "<" )
        {
            if ( tmp[1]-1 < up )
                up = tmp[1]-1;
        }
        else if ( tmp[0] == "<=" )
        {
            if ( tmp[1] < up )
                up = tmp[1];
        }
    }
    if ( up < low )
        print("Impossible");
    else
        print(low);
}

main();

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else
    r = "<=";
  return r;
}
var min_ = -200000000;
var max_ = 200000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = +l[2];
  if(yn=="N")
    sign = f(yn);

  if(sign==">=")
    min_ = Math.max(num,min_);
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num,max_- 1);
  else
    min_ = Math.max(num,min_ + 1);
}
if(min_ <= min_)
  print(min_);
else
  print("Impossible");

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else if (v==">")
    r = "<=";
  return r;
}
var min_ = -200000000;
var max_ = 200000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = l[2];
  if(yn=="N")
    sign = f(sign);

  if(sign==">=")
    min_ = Math.max(num,min_);
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num,max_- 1);
  else if (sign==">")
    min_ = Math.max(num,min_ + 1);
}
if(min_ <= max_)
  print(min_);
else
  print("Impossible");

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else if (v==">")
    r = "<=";
  return r;
}
var min_ = -200000000;
var max_ = 200000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = l[2];
  if(yn=="N")
    sign = f(yn);

  if(sign==">=")
    min_ = Math.max(num,min_);
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num,max_- 1);
  else if (sign==">")
    min_ = Math.max(num,min_ + 1);
}
if(min_ <= max_)
  print(min_);
else
  print("Impossible");

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else if (v==">")
    r = "<=";
  return r;
}
var min_ = -200000000;
var max_ = 200000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = +l[2];
  if(yn=="N")
    sign = f(yn);

  if(sign==">=")
    min_ = Math.max(num,min_);
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num,max_- 1);
  else if (sign==">")
    min_ = Math.max(num,min_ + 1);
}
if(min_ <= max_)
  print(min_);
else
  print("Impossible");

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else
    r = "<=";
  return r;
}
var min_ = -200000000;
var max_ = 200000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = +l[2];
  if(yn=="N")
    sign = f(yn);

  if(sign==">=")
    min_ = Math.max(num,min_);
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num,max_- 1);
  else
    min_ = Math.max(num,min_ + 1);
}
if(min_ <= max_)
  print(min_);
else
  print("Impossible");

function f(v){
  var r = "";
  if(v==">=")
    r = "<";
  else if (v=="<=")
    r = ">";
  else if (v=="<")
    r = ">=";
  else if (v==">")
    r = "<=";
  return r;
}
var min_ = -200000000;
var max_ = 200000000;
var n = readline();
var sign;
var num;
var yn;
for(var i = 0; i < n; i++)//error poner var
{
  var l = readline().split(' ');
  sign = l[0];
  num = +l[1];
  yn = l[2];
  if(yn=="N")
    sign = f(sign);

  if(sign==">=")
    min_ = Math.max(num,min_);
  else if (sign=="<=")
    max_ = Math.min(num,max_);
  else if (sign=="<")
    max_ = Math.min(num - 1,max_);
  else if (sign==">")
    min_ = Math.max(num + 1,min_ );
}
if(min_ <= max_)
  print(min_);
else
  print("Impossible");