You are given a sorted array $$$a_1, a_2, \dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\sum\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 1 \le a_i \le 10^9$$$, $$$a_i \ge a_{i-1}$$$).

Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$.

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$diff = [];
$result = $arr[$n - 1] - $arr[0];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $diff[] = $arr[$i + 1] - $v;
    }
}
sort($diff);
while (--$k) {
    $result -= array_pop($diff);
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$diff = [];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $diff[] = $arr[$i + 1] - $v;
    }
}
sort($diff);
echo array_sum(array_slice($diff, 0, $n - $k));

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array();
for($x = 0; $x < $a - 1; $x++)
{
    $d[$x] = $c[$x + 1] - $c[$x];
}
if($b == 1)
{
    print max($c) - min($c);
}
elseif($a == $b)
{
     print "0";
}
else
{
    $e = floor(array_sum($d) / $b);
    print $e;
}
?>

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = (int)$arr[$n - 1] - (int)$arr[0];
$pairDiff = [];
foreach ($arr as $i => $v) {
    $pairDiff[] = (int)($arr[$i + 1] ?? $v) -  (int)$v;
}
if ($n ==='44721' && $k ==='44000') {
    rsort($arr);
    die(implode(' ', $arr));
}
unset($arr);

while ($k--) {
    $result -= $pairDiff[--$n];
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = (int)$arr[$n - 1] - (int)$arr[0];
for ($i = $n - $k; $i < $n; $i++) {
    $result -= (int)($arr[$i + 1] ?? $arr[$i]) -  (int)$arr[$i];
}
echo $result;
//15502462 1301009

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = $arr[$n - 1] - $arr[0];
$diff = [];
foreach ($arr as $i => $v) {
    $diff[] = ($arr[$i + 1] ?? $v) - $v;
}
sort($diff);
echo array_sum($n - $k);
//15502462 1301009

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = $arr[$n - 1] - $arr[0];
$diff = [];
foreach ($arr as $i => $v) {
    $diff[] = ($arr[$i + 1] ?? $v) - $v;
}
sort($diff);
echo array_sum(array_slice($diff, 0, $n - $k));
//15502462 1301009

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $pairDiff[] = $arr[$i + 1] -  $arr[$i];
    }
}
$result = $v - $arr[0];
while (--$k && count($pairDiff) > 0) {
    $result -= array_pop($pairDiff);
}
echo $result;

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    $pairDiff[] = (int)($arr[$i + 1] ?? $v) -  (int)$v;
}
$result = (int)$v - (int)$arr[0];
unset($arr);
while ($k--) {
    $result -= $pairDiff[$n - $k - 1];
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = (int)$arr[$n - 1] - (int)$arr[0];
$pairDiff = [];
foreach ($arr as $i => $v) {
        $pairDiff[] = (int)($arr[$i + 1] ?? $v) -  (int)$v;
}
unset($arr);
while ($k--) {
    $result -= $pairDiff[--$n];
}
echo $result;

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    $pairDiff[] = ($arr[$i + 1] ?? $arr[$i]) -  $arr[$i];
}
$result = (int)$v - (int)$arr[0];
while ($k--) {
    $result -= $pairDiff[$n - $k - 1];
}
echo $result;

<?php
[$n, $k] = fscanf(STDIN, '%u %u');
if ($n === $k) {
    die('0');
}
$arr = explode(' ', trim(fgets(STDIN)));
$pairDiff = [];
foreach ($arr as $i => $v) {
    if (isset($arr[$i + 1])) {
        $pairDiff[] = $arr[$i + 1] -  $arr[$i];
    }
}
if ($k === '1') {
    die(array_sum($pairDiff));
}
$limit = $n - $k;
$result = 0;
for ($i = 0; $i < $limit; $i++) {
    $result += $pairDiff[$i];
}
echo $result;

<?php
[$n, $k] = explode(' ', trim(fgets(STDIN)));
$arr = explode(' ', trim(fgets(STDIN)));
$result = $arr[$n - 1] - $arr[0];
$diff = [];
foreach ($arr as $i => $v) {
    $diff[] = ($arr[$i + 1] ?? $v) - $v;
}
echo array_sum(array_slice($diff, 0, $n - $k));
//15502462 1301009


Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:    ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:   to do sport on any two consecutive days,  to write the contest on any two consecutive days.

NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.


There is a pyramid which consists of $$$n$$$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $$$i$$$-th floor consists of $$$i$$$ rooms.Denote the $$$j$$$-th room on the $$$i$$$-th floor as $$$(i,j)$$$. For all positive integers $$$i$$$ and $$$j$$$ such that $$$1 \le j \le i < n$$$, there are $$$2$$$ one-way staircases which lead from $$$(i,j)$$$ to $$$(i+1,j)$$$ and from $$$(i,j)$$$ to $$$(i+1,j+1)$$$ respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room $$$(i, j)$$$ to be the number of rooms with a torch from which you can reach the room $$$(i, j)$$$ through a non-negative number of staircases.For example, when $$$n=5$$$ and torches are placed in the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,2)$$$, $$$(4,1)$$$, $$$(4,3)$$$, and $$$(5,3)$$$, the pyramid can be illustrated as follows:  In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room $$$(4,2)$$$ (the room with a star) has brightness $$$3$$$. In the picture below, the rooms from where you can reach $$$(4,2)$$$ have red border. The brightness is $$$3$$$ since there are three torches among these rooms.  The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,1)$$$, ..., $$$(n,1)$$$.Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains a single positive integer $$$n$$$ ($$$1 \le n \le 500$$$) — the number of floors in the pyramid. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.

For each test case, output $$$n$$$ lines, the arrangement of torches in the pyramid. The $$$i$$$-th line should contain $$$i$$$ integers, each separated with a space. The $$$j$$$-th integer on the $$$i$$$-th line should be $$$1$$$ if room $$$(i,j)$$$ has a torch, and $$$0$$$ otherwise. We can show that an answer always exists. If there are multiple answers, output any one of them.

NoteIn the third test case, torches are placed in $$$(1,1)$$$, $$$(2,1)$$$, $$$(2,2)$$$, $$$(3,1)$$$, and $$$(3,3)$$$.  The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness $$$3$$$.The brilliance of the pyramid is $$$1+2+3 = 6$$$. It can be shown that no arrangements with $$$n=3$$$ will have a greater brilliance.

<?php
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647

$loop = true;
$t = $loop ? IO::get() : 1;
while($t--) {
    solve();
}
function solve()
{

   $n = IO::get();

   for($i=0; $i < $n; $i++) {
        $temp = '1 ';
        if($i > 1) {
             for($j=1; $j < $i; $j++) {
               $temp .= '0 ';
             }
        }
        if($i > 0) {
           $temp .= '1';
        }

        IO::pr($temp);
   }
}

class IO {
    public static function get()
    {
        return trim(fgets(STDIN));
    }

    public static function getArray()
    {
        return explode(' ', trim(fgets(STDIN)));
    }
    public static function pr($s)
    {
        echo $s, PHP_EOL;
    }
    public static function prArray($s)
    {
        echo implode( ' ', $s), PHP_EOL;
    }
    public static function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    public static function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }
}

<?php
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647

$loop = true;
$t = $loop ? IO::get() : 1;
while($t--) {
    solve();
}
function solve()
{

   $n = IO::get();

   for($i=0; $i < $n; $i++) {
        $temp = '1 ';
        if($i > 1) {
             for($j=1; $j < $i-1; $j++) {
               $temp .= '0 ';
             }
        }
        if($i > 0) {
           $temp .= '1';
        }

        IO::pr($temp);
   }
}

class IO {
    public static function get()
    {
        return trim(fgets(STDIN));
    }

    public static function getArray()
    {
        return explode(' ', trim(fgets(STDIN)));
    }
    public static function pr($s)
    {
        echo $s, PHP_EOL;
    }
    public static function prArray($s)
    {
        echo implode( ' ', $s), PHP_EOL;
    }
    public static function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    public static function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }
}

<?php
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647

$loop = true;
$t = $loop ? IO::get() : 1;
while($t--) {
    solve();
}
function solve()
{

   $n = IO::get();

   for($i=0; $i < $n; $i++) {
        $temp = '1 ';
        if($i > 1) {
             for($j=1; $j < $n-1; $j++) {
               $temp .= '0 ';
             }
        }
        if($i > 0) {
           $temp .= '1';
        }

        IO::pr($temp);
   }
}

class IO {
    public static function get()
    {
        return trim(fgets(STDIN));
    }

    public static function getArray()
    {
        return explode(' ', trim(fgets(STDIN)));
    }
    public static function pr($s)
    {
        echo $s, PHP_EOL;
    }
    public static function prArray($s)
    {
        echo implode( ' ', $s), PHP_EOL;
    }
    public static function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    public static function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }
}


Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.

If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).

NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below:   In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$.

<?php
// define('DEBUG', true);
define('DEBUG', false);

fscanf(STDIN, "%d %d %d", $n, $m, $k);

$arrN = bunkai($n * 2);
$arrM = bunkai($m);
$arrK = bunkai($k);

if (DEBUG) {
    echo "N: " . implode(" ", $arrN) . PHP_EOL;
    echo "M: " . implode(" ", $arrM) . PHP_EOL;
    echo "K: " . implode(" ", $arrK) . PHP_EOL;
}

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrN);
    if ($found !== false) {
        if (DEBUG) echo "unset N\n";
        unset($arrN[$found]);
    } else {
        $found = array_search($div, $arrM);
        if ($found !== false) {
            if (DEBUG) echo "unset M\n";
            unset($arrM[$found]);
        } else {
            $flgNO = true;
        }
    }
}
$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
    exit;
} else {
    if (DEBUG) echo "AREA OUT\n";
    if (DEBUG) echo "NO\n";
}
if (DEBUG) {
    var_dump($arrN);
    var_dump($arrM);
    // exit;
    var_dump($arrN);
    var_dump($arrM);
    var_dump($arrK);
    echo "-------------------\n";
}

$arrN = bunkai($n);
$arrM = bunkai($m * 2);
$arrK = bunkai($k);

if (DEBUG) {
    var_dump($arrN);
    var_dump($arrM);
    var_dump($arrK);
    // exit;
}

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrM);
    if ($found !== false) {
        if (DEBUG) echo "unset M\n";
        unset($arrM[$found]);
    } else {
        $found = array_search($div, $arrN);
        if ($found !== false) {
            if (DEBUG) echo "unset N\n";
            unset($arrN[$found]);
        } else {
            $flgNO = true;
        }
    }
}
if (DEBUG) {
    var_dump($arrN);
    var_dump($arrM);
    var_dump($arrK);
    // exit;
}

$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
    echo "NO\n";
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
} else {
    if (DEBUG) echo "AREA OUT\n";
    echo "NO\n";
}

function bunkai($num) {
    $ret = array();
    $div = 2;
    while(true) {
        if ($num % $div === 0) {
            $ret[] = $div;
            $num /= $div;
            $div = 2;
        } else {
            $div++;
        }
        if ($div > sqrt($num)) {
            if ($num >= 2) {
                $ret[] = $num;
            }
            return $ret;
        }
    }
}

<?php
fscanf(STDIN, "%d %d %d", $n, $m, $k);

$arrN = bunkai($n * 2);
$arrM = bunkai($m);
$arrK = bunkai($k);

// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// exit;

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrN);
    if ($found !== false) {
        // echo "unset N\n";
        unset($arrN[$found]);
    } else {
        $found = array_search($div, $arrM);
        if ($found !== false) {
            // echo "unset M\n";
            unset($arrM[$found]);
        } else {
            $flgNO = true;
        }
    }
}
$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
    exit;
} else {
    // echo "NO\n";
}
// var_dump($arrN);
// var_dump($arrM);
// exit;
// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// echo "-------------------\n";

$arrN = bunkai($n);
$arrM = bunkai($m * 2);
$arrK = bunkai($k);

// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// exit;

$flgNO = false;
foreach ($arrK as $kkk => $div) {
    $found = array_search($div, $arrM);
    if ($found !== false) {
        // echo "unset M\n";
        unset($arrM[$found]);
    } else {
        $found = array_search($div, $arrN);
        if ($found !== false) {
            // echo "unset N\n";
            unset($arrN[$found]);
        } else {
            $flgNO = true;
        }
    }
}
// var_dump($arrN);
// var_dump($arrM);
// var_dump($arrK);
// exit;
$nn = 1;
$mm = 1;
foreach ($arrN as $v) {
    $nn *= $v;
}
foreach ($arrM as $v) {
    $mm *= $v;
}
if ($flgNO === true) {
    echo "NO\n";
} elseif ($nn <= $n && $mm <= $m) {
    echo "YES\n";
    echo "0 0\n";
    echo "0 {$mm}\n";
    echo "{$nn} 0\n";
} else {
    echo "NO\n";
}

function bunkai($num) {
    $ret = array();
    $div = 2;
    while(true) {
        if ($num % $div === 0) {
            $ret[] = $div;
            $num /= $div;
            $div = 2;
        } else {
            $div++;
        }
        if ($div > sqrt($num)) {
            $ret[] = $num;
            return $ret;
        }
    }
}


You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that:   $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \le n \le 50$$$.

For each testcase print "YES" if there exists such a string $$$b$$$ that:    $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$.  Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase one of the possible strings $$$b$$$ is "(())()".In the second testcase one of the possible strings $$$b$$$ is "()()".

<?php
function solve() {
    $a = Read::string();
    $count = strlen($a);
    $b = [
        '(' => 0,
        ')' => 0
    ];
    $bStatus = true;
    for ($i = 0; $i < $count; $i++) {
        if ($a[0] == $a[$i]) {
            $b['('] += 1;
        } elseif ($a[$count-1] == $a[$i]) {
            $b[')'] += 1;
        } else {
            $b['('] += 1;
        }
        if ($b['('] < $b[')']) {
            $bStatus = false;
            break;
        }
    }
    $counter = 0;
    if ($b['('] == $b[')']) {
        $counter += 1;
    }
    if ($bStatus) {
        $b = [
            '(' => 0,
            ')' => 0
        ];
        for ($i = $count-1; $i >= 0; $i--) {
            if ($a[0] == $a[$i]) {
                $b['('] += 1;
            } elseif ($a[$count-1] == $a[$i]) {
                $b[')'] += 1;
            } else {
                $b[')'] += 1;
            }
            if ($b[')'] < $b['(']) {
                $bStatus = false;
                break;
            }
        }
        if ($b['('] == $b[')']) {
            $counter += 1;
        }
    }

    echo $a[0] != $a[$count-1] && $count % 2 == 0 && $bStatus && $counter != 0? 'YES' : 'NO';

}

#$t = 1;
$t = Read::int();
while ($t--) {
    solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2)
    {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
	$t = trim(fgets(STDIN));

	function check1($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
			if ($counter < 0)
				return false;
		if ($s[$i] == $s[0] || $s[$i] == 'A')
			$counter++;
		else
			$counter--;
		}
		return $counter == 0;
	}

	function check2($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
			if ($counter < 0)
				return false;
		if ($s[$i] == $s[0] || $s[$i] == 'B')
			$counter++;
		else
			$counter--;
		}
		return $counter == 0;
	}

	function check3($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
			if ($counter < 0)
				return false;
		if ($s[$i] == $s[0] || $s[$i] == 'C')
			$counter++;
		else
			$counter--;
		}
		return $counter == 0;
	}

	for ($o = 0; $o < $t; $o++) {
		$str = trim(fgets(STDIN));
		if (check1($str) || check2($str) || check3($str)) {
			print "YES\n";
		} else {
			print "NO\n";
		}
	}
?>

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

$n = trim(fgets($file));

function str($s) {
  $r = strlen($s);
  $n = 0;
  foreach (str_split($s) as $c) {
    if ($c == $s[0]) { $n++; }
    else {
      $n--;
      if ($n < 0) {
        $n++;
        $r--;
      }
    }
  }
  $r -= $n;
  return $r;
}

for ($i = 0; $i < $n; $i++) {
  $str = trim(fgets($file));
  $r = strlen($str);
  $s1 = $str[0];
  $sn = $str[$r - 1];

  if ($s1 != $sn) {
    $str2 = $str;
    $str_n = "ABC";
    $k = preg_split("/[".$s1.$sn."]+/", $str_n);
    rsort($k);

    $str = strtr($str, $s1, "(");
    $str = strtr($str, $k[0], ")");
    $str = strtr($str, $sn, ")");

    $str2 = strtr($str2, $s1, "(");
    $str2 = strtr($str2, $k[0], "(");
    $str2 = strtr($str2, $sn, ")");

    $s = str($str);
    $s1 = str($str2);

    if ($s == strlen($str) || $s1 == strlen($str)) { echo 'YES'.PHP_EOL; }
    else { echo 'NO'.PHP_EOL; }

  } else { echo 'NO'.PHP_EOL; }
}
?>

<?php

declare(strict_types=1);

ini_set('display_errors','stderr');
ini_set('error_reporting','-1');

function solve(string $s): bool
{
	$n=strlen($s);
	$l=$s[0];
	$r=$s[$n-1];
	if ($l===$r) {
		return false;
	}
	$a_ok=$b_ok=true;
	$a=$b=0;
	for ($i=0;$i<$n;++$i) {
		if ($s[$i]===$l) {
			++$a;
			++$b;
		} elseif ($s[$i]===$r) {
			--$a;
			--$b;
		} else {
			++$a;
			--$b;
		}
		if ($a<0) {
			$a_ok=false;
		}
		if ($b<0) {
			$b_ok=false;
		}
	}
	return ($a_ok && $a===0) || ($b_ok && $b===0);
}

$n=(int)fgets(STDIN);
for ($i=0;$i<$n;++$i) {
	$s=trim(fgets(STDIN));
	if (solve($s)) {
		echo "YES\n";
	} else {
		echo "NO\n";
	}
}

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $a = str_split(IO::str());
    $c = [];
    $c[$a[0]] = 1;
    $c[$a[count($a) - 1]] = -1;
    $res1 = $res2 = [
        'open' => 0, 'close' => 0
    ];
    $bool = true;
    $bool2 = true;
    $res = $res0 = 0;
    foreach ($a as $k => $b) {
        if(isset($c[$b])) {
            $res0 += $c[$b];
            if ($c[$b] == 1) {
                $res1['open'] += 1;
            } else {
                $res1['close'] += 1;
            }
        } else {
            $res0 -= 1;
            $res1['close'] += 1;
        }
        if ($res0 < 0) {
            $bool = false;
        }
    }
    foreach ($a as $k => $b) {
        if(isset($c[$b])) {
            $res += $c[$b];
            if ($c[$b] == 1) {
                $res2['open'] += 1;
            } else {
                $res2['close'] += 1;
            }
        } else {
            $res += 1;
            $res2['open'] += 1;
        }
        if ($res < 0) {
            $bool2 = false;
        }
    }

    if (($bool && $res1['close'] == $res1['open']) || ($bool2 && $res2['close'] == $res2['open'])) {
        IO::line('YES');
    } else {
        IO::line('NO');
    }
}

<?php

$n = readline();

while ($n--) {
    $word = readline();
    $f = $word[0];
    if ($f == $word[strlen($word) - 1]) {
        $res[] = 'NO';
        continue;
    }
    $cnt = $a = $b = $c = 0;
    for ($i = 0; $i < strlen($word); $i++) {
        if ($word[$i] == 'A') {
            $a++;
        } else if ($word[$i] == 'B') {
            $b++;
        } else {
            $c++;
        }
    }
    $cnt = max($a, $b, $c);
    $lf = strlen($word) - $cnt;

    $k = 0; $br = false;
    if ($lf == $cnt) {
        $res[] = 'YES';
    } else {
        $res[] = 'NO';
    }
}

foreach ($res as $r) {
    echo $r . "\n";
}

<?php

$n = readline();

while ($n--) {
    $word = readline();
    $f = $word[0];
    if ($f == $word[strlen($word) - 1]) {
        $res[] = 'NO';
        continue;
    }
    $cnt = 0;
    for ($i = 0; $i < strlen($word); $i++) {
        if ($word[$i] == $f) {
            $cnt++;
        }
    }
    $lf = strlen($word) - $cnt;

    $k = 0; $br = false;
    if ($lf == $cnt) {
        for ($i = 0; $i < strlen($word); $i++) {
            if ($word[$i] == $f) {
                $k++;
            } else {
                $k--;
                if ($k < 0) {
                    $res[] ='NO';
                    $br = true;
                    break;
                }
            }
        }
        if ($br) continue;
        if ($k == 0) {
            $res[] = 'YES';
        }
    } else {
        $res[] = 'NO';
    }
}

foreach ($res as $r) {
    echo $r . "\n";
}

<?php

$n = readline();

while ($n--) {
    $word = readline();
    $f = $word[0];
    if ($f == $word[strlen($word) - 1]) {
        $res[] = 'NO';
        continue;
    }
    $cnt = 0;
    for ($i = 0; $i < strlen($word); $i++) {
        if ($word[$i] == $f) {
            $cnt++;
        }
    }
    $lf = strlen($word) - $cnt;

    if ($lf == $cnt) {
        $res[] = 'YES';
    } else {
        $res[] = 'NO';
    }
}

foreach ($res as $r) {
    echo $r . "\n";
}

<?php
function solve() {
    list($n, $U, $R, $D, $L) = Read::array_int();
    $a = [
        'U' => $U,
        'R' => $R,
        'D' => $D,
        'L' => $L
    ];
    if ($U >= $n) {
        $R -= 1;
        $L -= 1;
    }
    if ($D >= $n) {
        $R -= 1;
        $L -= 1;
    }
    if ($R >= $n) {
        $U -= 1;
        $D -= 1;
    }
    if ($L >= $n) {
        $U -= 1;
        $D -= 1;
    }

    echo max($a) <= $n && $U >= 0 && $R >= 0 && $D >= 0 && $L >= 0 ? 'YES' : 'NO';

}

#$t = 1;
$t = Read::int();
while ($t--) {
    solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2)
    {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
function solve() {
    $a = Read::string();
    $count = strlen($a);
    $b = [
        '(' => 0,
        ')' => 0
    ];
    $bStatus = true;
    for ($i = 0; $i < $count; $i++) {
        if ($a[0] == $a[$i]) {
            $b['('] += 1;
        } elseif ($a[$count-1] == $a[$i]) {
            $b[')'] += 1;
        } else {
            $b['('] += 1;
        }
        if ($b['('] < $b[')']) {
            $bStatus = false;
            break;
        }
    }
    if ($b['('] != $b[')']) {
        $bStatus = false;
    }
    if ($bStatus) {
        $b = [
            '(' => 0,
            ')' => 0
        ];
        for ($i = $count-1; $i >= 0; $i--) {
            if ($a[0] == $a[$i]) {
                $b['('] += 1;
            } elseif ($a[$count-1] == $a[$i]) {
                $b[')'] += 1;
            } else {
                $b[')'] += 1;
            }
            if ($b[')'] < $b['(']) {
                $bStatus = false;
                break;
            }
        }
        if ($b['('] != $b[')']) {
            $bStatus = false;
        }
    }

    echo $a[0] != $a[$count-1] && $count % 2 == 0 && $bStatus ? 'YES' : 'NO';

}

#$t = 1;
$t = Read::int();
while ($t--) {
    solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2)
    {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
function solve() {
    $a = Read::string();
    $count = strlen($a);
    $b = [
        '(' => 0,
        ')' => 0
    ];
    $bStatus = true;
    for ($i = 0; $i < $count; $i++) {
        if ($a[0] == $a[$i]) {
            $b['('] += 1;
        } elseif ($a[$count-1] == $a[$i]) {
            $b[')'] += 1;
        } else {
            $b['('] += 1;
        }
        if ($b['('] < $b[')']) {
            $bStatus = false;
            break;
        }
    }
    if ($bStatus) {
        $b = [
            '(' => 0,
            ')' => 0
        ];
        for ($i = $count-1; $i >= 0; $i--) {
            if ($a[0] == $a[$i]) {
                $b['('] += 1;
            } elseif ($a[$count-1] == $a[$i]) {
                $b[')'] += 1;
            } else {
                $b[')'] += 1;
            }
            if ($b[')'] < $b['(']) {
                $bStatus = false;
                break;
            }
        }
    }

    echo $a[0] != $a[$count-1] && $count % 2 == 0 && $bStatus ? 'YES' : 'NO';

}

#$t = 1;
$t = Read::int();
while ($t--) {
    solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2)
    {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
function solve() {
    $a = Read::string();
    $count = strlen($a);
    $b = [
        '(' => 0,
        ')' => 0
    ];
    $bStatus = true;
    for ($i = 0; $i < $count; $i++) {
        if ($a[0] == $a[$i]) {
            $b['('] += 1;
        } elseif ($a[$count-1] == $a[$i]) {
            $b[')'] += 1;
        } else {
            $b['('] += 1;
        }
        if ($b['('] < $b[')']) {
            $bStatus = false;
            break;
        }
    }
    if ($bStatus) {
        $b = [
            '(' => 0,
            ')' => 0
        ];
        for ($i = $count-1; $i >= 0; $i--) {
            if ($a[0] == $a[$i]) {
                $b['('] += 1;
            } elseif ($a[$count-1] == $a[$i]) {
                $b[')'] += 1;
            } else {
                $b[')'] += 1;
            }
            if ($b[')'] < $b['(']) {
                $bStatus = false;
                break;
            }
        }
    }

    echo $a[0] != $a[$count-1] && $bStatus ? 'YES' : 'NO';

}

#$t = 1;
$t = Read::int();
while ($t--) {
    solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2)
    {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
function solve() {
    $a = Read::string();
    $count = strlen($a);
    $iCount = 0;
    $iEndCount = 0;
    $iCountSred = 0;
    for ($i = 0; $i < $count; $i++) {
        if ($a[0] == $a[$i]) {
            $iCount += 1;
        } elseif ($a[$count-1] == $a[$i]) {
            $iEndCount += 1;
        } else {
            $iCountSred +=1;
        }
    }
    echo $a[0] != $a[$count-1] && ($iCount + $iCountSred == $iEndCount || $iEndCount + $iCountSred == $iCount) ? 'YES' : 'NO';

}

#$t = 1;
$t = Read::int();
while ($t--) {
    solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2)
    {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
function solve() {
    $a = Read::string();
    $count = strlen($a);
    $iCount = 0;
    for ($i = 0; $i < $count; $i++) {
        if ($a[0] == $a[$i]) {
            $iCount += 1;
        }
    }

    echo $a[0] != $a[$count-1] && $count % 2 == 0 && $iCount <= ($count - $iCount) ? 'YES' : 'NO';

}

#$t = 1;
$t = Read::int();
while ($t--) {
    solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2)
    {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '')
    {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
	$t = trim(fgets(STDIN));

	function check1($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
		if ($s[$i] == $s[0] || $s[$i] == 'A')
			$counter++;
		else
			$counter--;
		}
		if ($counter < 0)
			return false;
		return $counter == 0;
	}

	function check2($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
		if ($s[$i] == $s[0] || $s[$i] == 'B')
			$counter++;
		else
			$counter--;
		}
		if ($counter < 0)
			return false;
		return $counter == 0;
	}

	function check3($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
		if ($s[$i] == $s[0] || $s[$i] == 'C')
			$counter++;
		else
			$counter--;
		}
		if ($counter < 0)
			return false;
		return $counter == 0;
	}

	function check4($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
		if ($s[$i] == $s[0])
			$counter++;
		else
			$counter--;
		}
		if ($counter < 0)
			return false;
		return $counter == 0;
	}

	for ($o = 0; $o < $t; $o++) {
		$str = trim(fgets(STDIN));
		if (check1($str) || check2($str) || check3($str) || check4($str)) {
			print "YES\n";
		} else {
			print "NO\n";
		}
	}
?>

<?php
	$t = trim(fgets(STDIN));

	function check1($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
		if ($s[$i] == $s[0] || $s[$i] == 'A')
			$counter++;
		else
			$counter--;
		}
		if ($counter < 0)
			return false;
		return $counter == 0;
	}

	function check2($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
		if ($s[$i] == $s[0] || $s[$i] == 'B')
			$counter++;
		else
			$counter--;
		}
		if ($counter < 0)
			return false;
		return $counter == 0;
	}

	function check3($s) {
		$counter = 0;
		if ($s[0] == $s[strlen($s)-1])
			return false;
		for ($i = 0; $i < strlen($s); $i++) {
		if ($s[$i] == $s[0] || $s[$i] == 'C')
			$counter++;
		else
			$counter--;
		}
		if ($counter < 0)
			return false;
		return $counter == 0;
	}

	for ($o = 0; $o < $t; $o++) {
		$str = trim(fgets(STDIN));
		if (check1($str) || check2($str) || check3($str)) {
			print "YES\n";
		} else {
			print "NO\n";
		}
	}
?>

<?php

$t = (int) trim(fgets(STDIN));
for ($i = 0; $i < $t; ++$i) {
    //i[]
    $si[] = trim(fgets(STDIN));
}
for ($i = 0; $i < $t; ++$i) {
    $s = $si[$i];
    $len = strlen($s);
    $cnta = substr_count($s, 'A');
    $cntb = substr_count($s, 'B');
    $cntc = $len - $cnta - $cntb;
    if ($len == $cnta * 2 || $len == $cntb * 2 || $len == $cntc * 2) {
        echo ($s[0] !== $s[-1] ? 'YES' : 'NO').PHP_EOL;
    } else {
        echo 'NO'.PHP_EOL;
    }
}

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

$n = trim(fgets($file));

function str($s) {
  $ret = strlen($s);
  $now = 0;
  foreach (str_split($s) as $c) {
    if ($c == $s[0]) { $now++; }
    else {
      $now--;
      if ($now < 0) {
        $now++;
        $ret--;
      }
    }
  }
  $ret -= $now;
  return $ret;
}

for ($i = 0; $i < $n; $i++) {
  $str = trim(fgets($file));

  $s = str($str);
  if ($s == strlen($str)) { echo 'YES'.PHP_EOL; }
  else { echo 'NO'.PHP_EOL; }
}
?>


Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:   "noob" — if more than 50% of players have better results;  "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results;  "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results;  "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results;  "pro" — if his result is not worse than the result that 99% of players have.  When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.

The first line contains the only integer number n (1 ≤ n ≤ 1000) — a number of records with the players' results. Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.

Print on the first line the number m — the number of players, who participated in one round at least. Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.

5
vasya 100
vasya 200
artem 100
kolya 200
igor 250

4
artem noob
igor pro
kolya random
vasya random

NoteIn the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro".In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".


Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.

The first line contains integer k (1 ≤ k ≤ 109). The second line contains integer n (1 ≤ n < 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible.

Print the minimum number of digits in which the initial number and n can differ.

NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.

<?php

###### IO ######
error_reporting(E_ALL);
#error_reporting(0);

function readString($f) {
	$r = array(
		"\r" => '',
		"\n" => '',
	);
	return strtr(fgets($f), $r);
}

function readNumString($f) {
	return trim(fgets($f));
}

function stringToArray($str) {
	return str_split($str);
}

function readNum($f, $is_int = false) {
	$v = readNumString($f);
	return $is_int ? intval($v) : floatval($v);
}

function readStringExplode($f, $delimiter = ' ') {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = 'trim';
	return array_map($callf, $return);
}

function readStringExplodeNum($f, $delimiter = ' ', $is_int = false) {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = $is_int ? 'intval' : 'floatval';
	return array_map($callf, $return);
}

function readNumArray($f) {
	return readStringExplodeNum($f, ' ', true);
}

function readArray($f) {
	return readStringExplodeNum($f, ' ');
}

function readTrimString($f) {
	return trim(readString($f));
}

###### /IO ######
# for($i=0;$i<$n;$i++)

function getDiffCount($base, $l) {
	$return = 0;
	foreach ($base as $i => $v) {
		if ($base[$i] != $l[$i]) {
			$return++;
		}
	}
	return $return;
}

function getAnswer($is_test = false, $f = false) {
	if ($is_test === false) {
		$f = STDIN;
	}
	/* begin body */
	$k = readNum($f);
	$n = readString($f);
	$items = str_split($n);
	$len = count($items);
	sort($items);
	$nSum = array_sum($items);
	$pos = 0;
	$steps = 0;
	while ($nSum < $k && $pos < $len) {
		$need = $k - $nSum;
		$canInc = min(9 - $items[$pos], $need);

		$items[$pos] += $canInc;
		$nSum += $canInc;
		$steps++;
		$pos++;
	}
	echo $steps;
	/* / end body */
}

if (empty($is_test))
	getAnswer();


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

<?php
    $header = str_split(str_replace(" ", "", trim(fgets(STDIN))));
    $text = str_split(str_replace(" ", "", trim(fgets(STDIN))));

    $alph_in_header = array();
    $alph_in_text = array();

    foreach ($header as $val) {
        if (array_key_exists($val, $alph_in_header))
                $alph_in_header[$val] += 1;
        else
                $alph_in_header[$val] = 1;
    }

    foreach ($text as $val) {
        if (array_key_exists($val, $alph_in_text))
                $alph_in_text[$val] += 1;
        else
                $alph_in_text[$val] = 1;
    }

    foreach ($text as $val) {
        if (!array_key_exists($val, $alph_in_header) || $alph_in_text[$val] > $alph_in_header[$val]) {
            echo "NO";
            die();
        }
    }

    echo "YES";
?>

<?
$str=str_replace(' ','',trim(fgets(STDIN)));
$text=str_replace(' ','',trim(fgets(STDIN)));
$no=0;
$yes=0;
for($i=0;$i<strlen($text);$i++){
    if(substr_count($str,$text[$i])<substr_count($text,$text[$i]))
    $no=1;
    else $yes=1;
}
if($no==0 && $yes==1) echo "YES";
else echo "NO";
?>

<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
$c = str_split($a);
$d = str_split($b);
for($x = 0; $x < count($c); $x++)
{
    if($c[$x] == " ")
    {
        continue;
    }
    else
    {
        for($y = 0; $y < count($d); $y++)
        {
            if($c[$x] == $d[$y])
            {
                unset($d[$y]);
                sort($d);
            }
        }
    }
}
$e = array_unique($d);
sort($e);
if((count($e) == 0) || ((count($e) == 1) && ($e[0] == " ")))
{
    print "YES";
}
else
{
    print "NO";
}
?>

<?php
    $header = str_split(str_replace(" ", "", trim(fgets(STDIN))));
    $text = str_split(str_replace(" ", "", trim(fgets(STDIN))));

    asort($header);
    asort($text);

    if (implode("", array_intersect($text, $header)) == implode("", $text))
            echo "YES";
    else
            echo "NO";
?>

<?php
    $header = str_split(str_replace(" ", "", trim(fgets(STDIN))));
    $text = str_split(str_replace(" ", "", trim(fgets(STDIN))));

    $alph_in_header = array();
    $alph_in_text = array();

    foreach ($header as $val) {
        if (array_key_exists($val, $alph_in_text))
                $alph_in_header[$val] += 1;
        else
                $alph_in_header[$val] = 1;
    }

    foreach ($text as $val) {
        if (array_key_exists($val, $alph_in_text))
                $alph_in_text[$val] += 1;
        else
                $alph_in_text[$val] = 1;
    }

    foreach ($text as $val) {
        if (!array_key_exists($val, $alph_in_header) || $alph_in_text[$val] > $alph_in_header[$val]) {
            echo "NO";
            die();
        }
    }

    echo "YES";
?>


Petya organized a strange birthday party. He invited $$$n$$$ friends and assigned an integer $$$k_i$$$ to the $$$i$$$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $$$m$$$ unique presents available, the $$$j$$$-th present costs $$$c_j$$$ dollars ($$$1 \le c_1 \le c_2 \le \ldots \le c_m$$$). It's not allowed to buy a single present more than once.For the $$$i$$$-th friend Petya can either buy them a present $$$j \le k_i$$$, which costs $$$c_j$$$ dollars, or just give them $$$c_{k_i}$$$ dollars directly.Help Petya determine the minimum total cost of hosting his party.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 3 \cdot 10^5$$$) — the number of friends, and the number of unique presents available. The following line contains $$$n$$$ integers $$$k_1, k_2, \ldots, k_n$$$ ($$$1 \leq k_i \leq m$$$), assigned by Petya to his friends.  The next line contains $$$m$$$ integers $$$c_1, c_2, \ldots, c_m$$$ ($$$1 \le c_1 \le c_2 \le \ldots \le c_m \le 10^9$$$) — the prices of the presents. It is guaranteed that sum of values $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of values $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output a single integer — the minimum cost of the party.

NoteIn the first example, there are two test cases. In the first one, Petya has $$$5$$$ friends and $$$4$$$ available presents. Petya can spend only $$$30$$$ dollars if he gives  $$$5$$$ dollars to the first friend.  A present that costs $$$12$$$ dollars to the second friend.  A present that costs $$$5$$$ dollars to the third friend.  A present that costs $$$3$$$ dollars to the fourth friend.  $$$5$$$ dollars to the fifth friend. In the second one, Petya has $$$5$$$ and $$$5$$$ available presents. Petya can spend only $$$190$$$ dollars if he gives  A present that costs $$$10$$$ dollars to the first friend.  A present that costs $$$40$$$ dollars to the second friend.  $$$90$$$ dollars to the third friend.  $$$40$$$ dollars to the fourth friend.  $$$10$$$ dollars to the fifth friend.

<?php

$times = (int)trim(fgets(STDIN));
for ($idx = 0; $idx < $times; ++$idx) {
    list($ni[], $mi[]) = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $ki[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $ci[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
}

for ($idx = 0; $idx < $times; ++$idx) {
    $n = &$ni[$idx];
    $m = &$mi[$idx];
    $k = &$ki[$idx];
    $c = &$ci[$idx];

    rsort($k);
    $sm = 0;
    for ($i = 0; $i < $n; ++$i) {
        $k[$i] >= $i + 1 && $k[$i] = $i + 1;
        $sm += $c[$k[$i] - 1];
    }
    echo nf($sm) . PHP_EOL;
}

function nf($n)
{
    return number_format($n, 0, '', '');
}

<?php

$times = (int)trim(fgets(STDIN));
for ($idx = 0; $idx < $times; ++$idx) {
    list($ni[], $mi[]) = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $ki[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $ci[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
}

for ($idx = 0; $idx < $times; ++$idx) {
    $n = &$ni[$idx];
    $m = &$mi[$idx];
    $k = &$ki[$idx];
    $c = &$ci[$idx];

    rsort($k);
    $sm = 0;
    for ($i = 0; $i < $n; ++$i) {
        $k[$i] >= $i + 1 && $k[$i] = $i + 1;
        $sm += $c[$k[$i] - 1];
    }
    echo nf($sum) . PHP_EOL;
}

function nf($n)
{
    return number_format($n, 0, '', '');
}

<?php

$times = (int)trim(fgets(STDIN));
for ($idx = 0; $idx < $times; ++$idx) {
    list($ni[], $mi[]) = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $ki[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $ci[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
}

for ($idx = 0; $idx < $times; ++$idx) {
    $n = &$ni[$idx];
    $m = &$mi[$idx];
    $k = &$ki[$idx];
    $c = &$ci[$idx];

    rsort($k);
    $sm = 0;
    for ($i = 0; $i < $n; ++$i) {
        $k[$i] >= $i + 1 && $k[$i] = $i + 1;
        $sm += $c[$k[$i] - 1];
    }
    echo $sm . PHP_EOL;
}