William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $$$n$$$ cells, with each cell either being alive or dead.Evolution of the array in William's cellular automaton occurs iteratively in the following way:  If the element is dead and it has exactly $$$1$$$ alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index $$$i$$$ the neighbors would be elements with indices $$$i - 1$$$ and $$$i + 1$$$. If there is no element at that index, it is considered to be a dead neighbor.  William is a humane person so all alive elements stay alive. Check the note section for examples of the evolution.You are given some initial state of all elements and you need to help William find the state of the array after $$$m$$$ iterations of evolution.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^3, 1 \le m \le 10^9$$$), which are the total number of cells in the array and the number of iterations. The second line of each test case contains a string of length $$$n$$$ made up of characters "0" and "1" and defines the initial state of the array. "1" means a cell is alive and "0" means it is dead. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

In each test case output a string of length $$$n$$$, made up of characters "0" and "1"  — the state of the array after $$$m$$$ iterations of evolution.

NoteSequence of iterations of evolution for the first test case   01000000001  — initial state  11100000011  — first iteration of evolution  11110000111  — second iteration of evolution  11111001111  — third iteration of evolution Sequence of iterations of evolution for the second test case   0110100101  — initial state  1110111101  — first iteration of evolution  1110111101  — second iteration of evolution


While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $$$a_1, a_2, \ldots, a_n$$$ to $$$-a_1, -a_2, \ldots, -a_n$$$. For some unknown reason, the number of service variables is always an even number.William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed $$$5\,000$$$ and after every operation no variable can have an absolute value greater than $$$10^{18}$$$. William can perform actions of two types for two chosen variables with indices $$$i$$$ and $$$j$$$, where $$$i < j$$$:  Perform assignment $$$a_i = a_i + a_j$$$  Perform assignment $$$a_j = a_j - a_i$$$  William wants you to develop a strategy that will get all the internal variables to the desired values.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \le n \le 10^3$$$), which is the number of internal variables. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, which are initial values of internal variables.

For each test case print the answer in the following format: The first line of output must contain the total number of actions $$$k$$$, which the strategy will perform. Note that you do not have to minimize $$$k$$$. The inequality $$$k \le 5\,000$$$ must be satisfied.  Each of the next $$$k$$$ lines must contain actions formatted as "type i j", where "type" is equal to "1" if the strategy needs to perform an assignment of the first type and "2" if the strategy needs to perform an assignment of the second type. Note that $$$i < j$$$ should hold. We can show that an answer always exists.

NoteFor the first sample test case one possible sequence of operations is as follows:  "2 1 2". Values of variables after performing the operation: [1, 0, 1, 1]  "2 1 2". Values of variables after performing the operation: [1, -1, 1, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, 0, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, -1, 1]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, 0]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [0, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [-1, -1, -1, -1] For the second sample test case one possible sequence of operations is as follows:  "2 1 4". Values of variables after performing the operation: [4, 3, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, 1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -3, 1, -2]  "1 3 4". Values of variables after performing the operation: [4, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [1, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [-2, -3, -1, -2]  "1 1 4". Values of variables after performing the operation: [-4, -3, -1, -2]


William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \,\cdots\, \,.\,a_k$$$ and can be one of two types:   Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, a_k \,.\, 1$$$ (starting a list of a deeper level), or  Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, (a_k + 1)$$$ (continuing the current level).  Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the "Notes" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the "Ctrl-S" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.William wants you to help him restore a fitting original nested list.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$), which is the number of lines in the list. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$1 \le a_i \le n$$$), which is what remains of William's nested list. It is guaranteed that in each test case at least one fitting list exists. It is guaranteed that the sum of values $$$n$$$ across all test cases does not exceed $$$10^3$$$.

For each test case output $$$n$$$ lines which represent a valid nested list, which could become the data provided to you by William. If there are multiple answers, print any.

NoteIn the second example test case one example of a fitting list is:11.1 1.1.11.1.21.21.2.122.12.2This list can be produced by using the sequence of operations shown below:    Original list with a single item $$$1$$$.  Insert item $$$2$$$ by using the insertion operation of the second type after item $$$1$$$.  Insert item $$$1.1$$$ by using the insertion operation of the first type after item $$$1$$$.  Insert item $$$1.2$$$ by using the insertion operation of the second type after item $$$1.1$$$.  Insert item $$$1.1.1$$$ by using the insertion operation of the first type after item $$$1.1$$$.  Insert item $$$1.1.2$$$ by using the insertion operation of the second type after item $$$1.1.1$$$.  Insert item $$$1.2.1$$$ by using the insertion operation of the first type after item $$$1.2$$$.  Insert item $$$2.1$$$ by using the insertion operation of the first type after item $$$2$$$.  Insert item $$$2.2$$$ by using the insertion operation of the second type after item $$$2.1$$$.


William is hosting a party for $$$n$$$ of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.For each William's friend $$$i$$$ it is known whether he likes currency $$$j$$$. There are $$$m$$$ currencies in total. It is also known that a trader may not like more than $$$p$$$ currencies.Because friends need to have some common topic for discussions they need to find the largest by cardinality (possibly empty) subset of currencies, such that there are at least $$$\lceil \frac{n}{2} \rceil$$$ friends (rounded up) who like each currency in this subset.

The first line contains three integers $$$n, m$$$ and $$$p$$$ $$$(1 \le n \le 2 \cdot 10^5, 1 \le p \le m \le 60, 1 \le p \le 15)$$$, which is the number of trader friends, the number of currencies, the maximum number of currencies each friend can like. Each of the next $$$n$$$ lines contain $$$m$$$ characters. The $$$j$$$-th character of $$$i$$$-th line is $$$1$$$ if friend $$$i$$$ likes the currency $$$j$$$ and $$$0$$$ otherwise. It is guaranteed that the number of ones in each line does not exceed $$$p$$$.

Print a string of length $$$m$$$, which defines the subset of currencies of the maximum size, which are liked by at least half of all friends. Currencies belonging to this subset must be signified by the character $$$1$$$. If there are multiple answers, print any.

NoteIn the first sample test case only the first currency is liked by at least $$$\lceil \frac{3}{2} \rceil = 2$$$ friends, therefore it's easy to demonstrate that a better answer cannot be found.In the second sample test case the answer includes $$$2$$$ currencies and will be liked by friends $$$1$$$, $$$2$$$, and $$$5$$$. For this test case there are other currencies that are liked by at least half of the friends, but using them we cannot achieve a larger subset size.


To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of $$$n$$$ lights arranged in a row. The device functions in the following way:Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any $$$k$$$ consecutive lights contain more than one turned on light, then the device finishes working.William doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The only line for each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 10^5$$$), which are the total number of lights and the length of subsegment of lights that are being checked, respectively.

For each test case print the answer, modulo $$$10^9+7$$$.  Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

NoteExplanation of the first sample test case:Let's write out all possible sequences of light toggles, which will make the device complete its operation:  $$$(1, 2)$$$  — $$$2$$$ lights are turned on  $$$(1, 3, 2)$$$  — $$$3$$$ lights are turned on  $$$(2, 1)$$$  — $$$2$$$ lights are turned on  $$$(2, 3)$$$  — $$$2$$$ lights are turned on  $$$(3, 2)$$$  — $$$2$$$ lights are turned on  $$$(3, 1, 2)$$$  — $$$3$$$ lights are turned on Then the final expected value will be equal to $$$\frac{2}{6}$$$ + $$$\frac{3}{6}$$$ + $$$\frac{2}{6}$$$ + $$$\frac{2}{6}$$$ + $$$\frac{2}{6}$$$ + $$$\frac{3}{6}$$$ = $$$\frac{14}{6}$$$ = $$$\frac{7}{3}$$$. Then the required output will be $$$333333338$$$, since $$$333333338 \cdot 3 \equiv 7 \pmod{10^9+7}$$$.


William owns a flat in central London. He decided to rent his flat out for the next $$$n$$$ days to earn some money.Since his flat is in the center of the city, he instantly got $$$m$$$ offers in the form $$$(l_i, r_i)$$$, which means that someone wants to book the flat from day $$$l_i$$$ until day $$$r_i$$$ inclusive. To avoid spending a lot of time figuring out whether it's profitable for him to accept an offer, William decided to develop an algorithm. The algorithm processes all offers as they arrive and will only accept offer $$$i$$$ if the following two conditions are satisfied:  $$$r_i - l_i + 1 \ge x$$$.  None of the days between $$$l_i$$$ and $$$r_i$$$ are occupied by a previously accepted offer  William isn't sure what value $$$x$$$ should have and he asks you for help. For all $$$x$$$ from $$$1$$$ to $$$n$$$ he wants you to calculate the total number of days for which the flat would be occupied if the corresponding value will be assigned to $$$x$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n \le 5 \cdot 10^4, 1 \le m \le 10^5)$$$, which are the number of days and the number of offers, respectively. Each of the next $$$m$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le n)$$$, which describe the $$$i$$$-th renting offer. All offers are given in chronological order.

Print $$$n$$$ integers. The number in $$$i$$$-th line must be equal to the number of days the flat would be occupied if the algorithm will use the value of $$$x$$$ equal to $$$i$$$.

NoteThe description of segments from the first sample test for each $$$x$$$:   $$$x = 1$$$  — algorithm will approve offers: $$$1$$$ (2..3), $$$3$$$ (1..1). The total number of days for which William's flat will be rented out is 3  $$$x = 2$$$  — algorithm will approve offers: $$$1$$$ (2..3). The total number of days for which William's flat will be rented out is 2  $$$x = 3$$$  — algorithm will approve offers: $$$2$$$ (3..5). The total number of days for which William's flat will be rented out is 3  $$$x = 4$$$  — algorithm will approve offers: $$$4$$$ (1..5). The total number of days for which William's flat will be rented out is 5  $$$x = 5$$$  — algorithm will approve offers: $$$4$$$ (1..5). The total number of days for which William's flat will be rented out is 5  $$$x = 6$$$  — algorithm will approve offers: $$$5$$$ (1..6). The total number of days for which William's flat will be rented out is 6


William really wants to get a pet. Since his childhood he dreamt about getting a pet grasshopper. William is being very responsible about choosing his pet, so he wants to set up a trial for the grasshopper!The trial takes place on an array $$$a$$$ of length $$$n$$$, which defines lengths of hops for each of $$$n$$$ cells. A grasshopper can hop around the sells according to the following rule: from a cell with index $$$i$$$ it can jump to any cell with indices from $$$i$$$ to $$$i+a_i$$$ inclusive.Let's call the $$$k$$$-grasshopper value of some array the smallest number of hops it would take a grasshopper to hop from the first cell to the last, but before starting you can select no more than $$$k$$$ cells and remove them from the array. When a cell is removed all other cells are renumbered but the values of $$$a_i$$$ for each cell remains the same. During this the first and the last cells may not be removed.It is required to process $$$q$$$ queries of the following format: you are given three numbers $$$l$$$, $$$r$$$, $$$k$$$. You are required to find the $$$k$$$-grasshopper value for an array, which is a subarray of the array $$$a$$$ with elements from $$$l$$$ to $$$r$$$ inclusive.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 20000$$$), the length of the array and the number of queries respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  – the elements of the array. The following $$$q$$$ lines contain queries: each line contains three integers $$$l$$$, $$$r$$$ and $$$k$$$ ($$$1 \le l \le r \le n$$$, $$$0 \le k \le min(30, r-l)$$$), which are the edges of the subarray and the number of the grasshopper value respectively.

For each query print a single number in a new line  — the response to a query.

NoteFor the second query the process occurs like this: For the third query the process occurs like this:


After William is done with work for the day, he enjoys playing his favorite video game.The game happens in a 2D world, starting at turn $$$0$$$. William can pick any cell in the game world and spawn in it. Then, each turn, William may remain at his current location or move from the current location (x, y) to one of the following locations: (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1).To accelerate movement the game has $$$n$$$ fast travel towers. $$$i$$$-th tower is located at location ($$$xa_i, ya_i$$$). To be able to instantly travel to the tower from any location in the game world it must first be activated. Activation of tower $$$i$$$ happens at the moment when the player is in cell ($$$xa_i, ya_i$$$) after this the tower remains active throughout the entire game.William also knows that the game has $$$m$$$ quests. $$$i$$$-th quest can be completed instantly by being at location ($$$xb_i, yb_i$$$) on turn $$$t_i$$$.William wants to find out the maximal number of quests he will be able to complete by optimally traversing the game world.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \le n \le 14, 1 \le m \le 100$$$), which are the number of towers and the number of quests, respectively. Each of the next $$$n$$$ lines contains two integers $$$xa_i, ya_i$$$ ($$$1 \le xa_i, ya_i \le 10^6$$$), which are the coordinates of fast travel towers. Each of the next $$$m$$$ lines contains two integers $$$xb_i$$$, $$$yb_i$$$ and $$$t_i$$$ ($$$1 \le xb_i, yb_i \le 10^6$$$, $$$1 \le t_i \le 10^9$$$), which are the coordinates of quests and the turn at which it may be completed. It is guaranteed that all locations in a test are different.

Print a single number  — the maximal number of quests William will be able to complete.

NoteIn the first sample test one of the possible sequences of William's actions is as follows:   Spawn at $$$(3, 2)$$$  On turn $$$1$$$ move to $$$(4, 2)$$$  On turn $$$2$$$ move to $$$(5, 2)$$$. By visiting this cell William activates tower number $$$3$$$.  On turn $$$3$$$ move to $$$(5, 1)$$$, where he waits for $$$1$$$ turn to complete the $$$2$$$nd quest  On turn $$$5$$$ move to $$$(5, 2)$$$  On turn $$$6$$$ move to $$$(5, 3)$$$  On turn $$$7$$$ move to $$$(5, 4)$$$  On turn $$$8$$$ move to $$$(5, 5)$$$  On turn $$$9$$$ move to $$$(4, 5)$$$  On turn $$$10$$$ move to $$$(3, 5)$$$. By moving to this location William will complete the $$$4$$$th quest  On turn $$$10$$$ instantly move to an already activated fast travel tower at $$$(5, 2)$$$  On turn $$$11$$$ move to $$$(6, 2)$$$. By moving to this location William will complete the $$$3$$$rd quest  William will not be able to complete the quest number $$$1$$$, because the tower at $$$(2, 3)$$$ was not activated


You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.

For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.

NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.


You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly $$$k\ \%$$$ magic essence and $$$(100 - k)\ \%$$$ water.In one step, you can pour either one liter of magic essence or one liter of water into the cauldron. What is the minimum number of steps to brew a potion? You don't care about the total volume of the potion, only about the ratio between magic essence and water in it.A small reminder: if you pour $$$e$$$ liters of essence and $$$w$$$ liters of water ($$$e + w > 0$$$) into the cauldron, then it contains $$$\frac{e}{e + w} \cdot 100\ \%$$$ (without rounding) magic essence and $$$\frac{w}{e + w} \cdot 100\ \%$$$ water.

The first line contains the single $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first and only line of each test case contains a single integer $$$k$$$ ($$$1 \le k \le 100$$$) — the percentage of essence in a good potion.

For each test case, print the minimum number of steps to brew a good potion. It can be proved that it's always possible to achieve it in a finite number of steps.

NoteIn the first test case, you should pour $$$3$$$ liters of magic essence and $$$97$$$ liters of water into the cauldron to get a potion with $$$3\ \%$$$ of magic essence.In the second test case, you can pour only $$$1$$$ liter of essence to get a potion with $$$100\ \%$$$ of magic essence.In the third test case, you can pour $$$1$$$ liter of magic essence and $$$3$$$ liters of water.


There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 < x_i < m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.

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 first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 < x_i < m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.

For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.

NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase:   Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.


There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.

Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.

NoteIn the first test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes;  ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.


Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.

It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.

NoteLet's look at all possible orders of cities Monuments will be build in:   $$$[1, 2, 3]$$$:   the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$;  the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$;  the third city controls all points at distance at most $$$1$$$, or point $$$1$$$.  In total, $$$4$$$ points are controlled.  $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points.  $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points.  $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points.  $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points.  $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points.  The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$


Monocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.The city consists of $$$n$$$ halls and $$$m$$$ one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. The city will be attacked by $$$k$$$ waves of goblins; during the $$$i$$$-th wave, $$$i$$$ goblins attack the city. Monocarp's goal is to pass all $$$k$$$ waves.The $$$i$$$-th wave goes as follows: firstly, $$$i$$$ goblins appear in some halls of the city and pillage them; at most one goblin appears in each hall. Then, goblins start moving along the tunnels, pillaging all the halls in their path. Goblins are very greedy and cunning, so they choose their paths so that no two goblins pass through the same hall. Among all possible attack plans, they choose a plan which allows them to pillage the maximum number of halls. After goblins are done pillaging, they leave the city.If all halls are pillaged during the wave — Monocarp loses the game. Otherwise, the city is restored. If some hall is pillaged during a wave, goblins are still interested in pillaging it during the next waves.Before each wave, Monocarp can spend some time preparing to it. Monocarp doesn't have any strict time limits on his preparations (he decides when to call each wave by himself), but the longer he prepares for a wave, the fewer points he gets for passing it. If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it (obviously, if he doesn't lose in the process).While preparing for a wave, Monocarp can block tunnels. He can spend one minute to either block all tunnels leading from some hall or block all tunnels leading to some hall. If Monocarp blocks a tunnel while preparing for a wave, it stays blocked during the next waves as well.Help Monocarp to defend against all $$$k$$$ waves of goblins and get the maximum possible amount of points!

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$; $$$0 \le m \le \frac{n(n - 1)}{2}$$$; $$$1 \le k \le n - 1$$$) — the number of halls in the city, the number of tunnels and the number of goblin waves, correspondely. Next $$$m$$$ lines describe tunnels. The $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$). It means that the tunnel goes from hall $$$u_i$$$ to hall $$$v_i$$$. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. There is at most one tunnel between each pair of halls. Next $$$k$$$ lines describe the scoring system. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le 10^9$$$; $$$1 \le y_i \le 10^9$$$). If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it.

Print the optimal Monocarp's strategy in the following format: At first, print one integer $$$a$$$ ($$$k \le a \le 2n + k$$$) — the number of actions Monocarp will perform. Next, print actions themselves in the order Monocarp performs them. The $$$i$$$-th action is described by a single integer $$$b_i$$$ ($$$-n \le b_i \le n$$$) using the following format:   if $$$b_i > 0$$$ then Monocarp blocks all tunnels going out from the hall $$$b_i$$$;  if $$$b_i < 0$$$ then Monocarp blocks all tunnels going into the hall $$$|b_i|$$$;  if $$$b_i = 0$$$ then Monocarp calls the next goblin wave.  You can't repeat the same block action $$$b_i$$$ several times. Monocarp must survive all waves he calls (goblins shouldn't be able to pillage all halls). Monocarp should call exactly $$$k$$$ waves and earn the maximum possible number of points in total. If there are several optimal strategies — print any of them.

NoteIn the first example, Monocarp, firstly, block all tunnels going in hall $$$2$$$, secondly — all tunnels going in hall $$$3$$$, and after that calls all waves. He spent two minutes to prepare to wave $$$1$$$, so he gets $$$98$$$ points for it. He didn't prepare after that, that's why he gets maximum scores for each of next waves ($$$200$$$, $$$10$$$ and $$$100$$$). In total, Monocarp earns $$$408$$$ points.In the second example, Monocarp calls for the first wave immediately and gets $$$100$$$ points. Before the second wave he blocks all tunnels going in hall $$$3$$$. He spent one minute preparing to the wave, so he gets $$$195$$$ points. Monocarp didn't prepare for the third wave, so he gets $$$10$$$ points by surviving it. Before the fourth wave he blocks all tunnels going out from hall $$$1$$$. He spent one minute, so he gets $$$99$$$ points for the fourth wave. In total, Monocarp earns $$$404$$$ points.In the third example, it doesn't matter how many minutes Monocarp will spend before the wave, since he won't get any points for it. That's why he decides to block all tunnels in the city, spending $$$5$$$ minutes. He survived the wave though without getting any points.


You are given an integer $$$x$$$. Can you make $$$x$$$ by summing up some number of $$$11, 111, 1111, 11111, \ldots$$$? (You can use any number among them any number of times).For instance,   $$$33=11+11+11$$$  $$$144=111+11+11+11$$$

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10000)$$$ — the number of testcases. The first and only line of each testcase contains a single integer $$$x$$$ $$$(1 \leq x \leq 10^9)$$$ — the number you have to make.

For each testcase, you should output a single string. If you can make $$$x$$$, output "YES" (without quotes). Otherwise, output "NO". You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteWays to make $$$33$$$ and $$$144$$$ were presented in the statement. It can be proved that we can't present $$$69$$$ this way.


You are given an array $$$a$$$ of $$$2n$$$ distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $$$2$$$ neighbours.More formally, find an array $$$b$$$, such that: $$$b$$$ is a permutation of $$$a$$$.For every $$$i$$$ from $$$1$$$ to $$$2n$$$, $$$b_i \neq \frac{b_{i-1}+b_{i+1}}{2}$$$, where $$$b_0 = b_{2n}$$$ and $$$b_{2n+1} = b_1$$$. It can be proved that under the constraints of this problem, such array $$$b$$$ always exists.

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(1 \leq n \leq 25)$$$. The second line of each testcase contains $$$2n$$$ integers $$$a_1, a_2, \ldots, a_{2n}$$$ $$$(1 \leq a_i \leq 10^9)$$$ — elements of the array. Note that there is no limit to the sum of $$$n$$$ over all testcases.

For each testcase, you should output $$$2n$$$ integers, $$$b_1, b_2, \ldots b_{2n}$$$, for which the conditions from the statement are satisfied.


This is the easy version of the problem. The only difference is that in this version $$$n \leq 2000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.

Output a single integer, the maximum number of potions you can drink without your health becoming negative.

NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point


This is the hard version of the problem. The only difference is that in this version $$$n \leq 200000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 200000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.


After rejecting $$$10^{100}$$$ data structure problems, Errorgorn is very angry at Anton and decided to kill him.Anton's DNA can be represented as a string $$$a$$$ which only contains the characters "ANTON" (there are only $$$4$$$ distinct characters). Errorgorn can change Anton's DNA into string $$$b$$$ which must be a permutation of $$$a$$$. However, Anton's body can defend against this attack. In $$$1$$$ second, his body can swap $$$2$$$ adjacent characters of his DNA to transform it back to $$$a$$$. Anton's body is smart and will use the minimum number of moves.To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string $$$B$$$. Can you help him?

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 100000)$$$ — the number of testcases. The first and only line of each testcase contains $$$1$$$ string $$$a$$$ ($$$1 \leq |a| \leq 100000$$$). $$$a$$$ consists of only the characters "A", "N", "O" and "T". It is guaranteed that the sum of $$$|a|$$$ over all testcases does not exceed $$$100000$$$.

For each testcase, print a single string, $$$b$$$. If there are multiple answers, you can output any one of them. $$$b$$$ must be a permutation of the string $$$a$$$.

NoteFor the first testcase, it takes $$$7$$$ seconds for Anton's body to transform NNOTA to ANTON: NNOTA $$$\to$$$ NNOAT $$$\to$$$ NNAOT $$$\to$$$ NANOT $$$\to$$$ NANTO $$$\to$$$ ANNTO $$$\to$$$ ANTNO $$$\to$$$ ANTON. Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.For the second testcase, it takes $$$2$$$ seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted.


Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array. More formally, given a suffix array of length $$$n$$$ and having an alphabet size $$$k$$$, count the number of strings that produce such a suffix array. Let $$$s$$$ be a string of length $$$n$$$. Then the $$$i$$$-th suffix of $$$s$$$ is the substring $$$s[i \ldots n-1]$$$. A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is $$$[3,2,4,1,0,5,6]$$$ as the array of sorted suffixes is $$$[\texttt{imry},\texttt{limry},\texttt{mry},\texttt{olimry},\texttt{oolimry},\texttt{ry},\texttt{y}]$$$. A string $$$x$$$ is lexicographically smaller than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x\neq y$$$), or there exists such $$$i$$$ that $$$x_i < y_i$$$, and for any $$$1\leq j < i$$$ , $$$x_j = y_j$$$.

The first line contain 2 integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200000,1 \leq k \leq 200000$$$) — the length of the suffix array and the alphabet size respectively. The second line contains $$$n$$$ integers $$$s_0, s_1, s_2, \ldots, s_{n-1}$$$ ($$$0 \leq s_i \leq n-1$$$) where $$$s_i$$$ is the $$$i$$$-th element of the suffix array i.e. the starting position of the $$$i$$$-th lexicographically smallest suffix. It is guaranteed that for all $$$0 \leq i< j \leq n-1$$$, $$$s_i \neq s_j$$$.

Print how many strings produce such a suffix array. Since the number can be very large, print the answer modulo $$$998244353$$$.

NoteIn the first test case, "abb" is the only possible solution. In the second test case, it can be easily shown no possible strings exist as all the letters have to be equal. In the fourth test case, one possible string is "ddbacef".Please remember to print your answers modulo $$$998244353$$$.


This is an interactive problem.There is a secret permutation $$$p$$$ ($$$1$$$-indexed) of numbers from $$$1$$$ to $$$n$$$. More formally, for $$$1 \leq i \leq n$$$, $$$1 \leq p[i] \leq n$$$ and for $$$1 \leq i < j \leq n$$$, $$$p[i] \neq p[j]$$$. It is known that $$$p[1]<p[2]$$$.In $$$1$$$ query, you give $$$3$$$ distinct integers $$$a,b,c$$$ ($$$1 \leq a,b,c \leq n$$$), and receive the median of $$$\{|p[a]-p[b]|,|p[b]-p[c]|,|p[a]-p[c]|\}$$$.In this case, the median is the $$$2$$$-nd element ($$$1$$$-indexed) of the sequence when sorted in non-decreasing order. The median of $$$\{4,6,2\}$$$ is $$$4$$$ and the median of $$$\{0,123,33\}$$$ is $$$33$$$.Can you find the secret permutation in not more than $$$2n+420$$$ queries?Note: the grader is not adaptive: the permutation is fixed before any queries are made.

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — the number of testcases. The first line of each testcase consists of a single integer $$$n$$$ $$$(20 \leq n \leq 100000)$$$ — the length of the secret permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100000$$$.


Given an integer $$$n$$$, find the maximum value of integer $$$k$$$ such that the following condition holds:  $$$n$$$ & ($$$n-1$$$) & ($$$n-2$$$) & ($$$n-3$$$) & ... ($$$k$$$) = $$$0$$$  where & denotes the bitwise AND operation.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, output a single integer — the required integer $$$k$$$.

NoteIn the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0.   $$$5 \, \& \, 4 \neq 0$$$,  $$$5 \, \& \, 4 \, \& \, 3 = 0$$$. Hence, 3 is the answer.


The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string $$$s$$$ (which is initially a palindrome in this version) of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations:   Choose any $$$i$$$ ($$$1 \le i \le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar.  Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$). The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of the characters '0' and '1'. It is guaranteed that the string $$$s$$$ is a palindrome and contains at least one '0'.  Note that there is no limit on the sum of $$$n$$$ over test cases.

For each test case print a single word in a new line:    "ALICE", if Alice will win the game,  "BOB", if Bob will win the game,  "DRAW", if the game ends in a draw.

NoteIn the first test case of the example,   in the $$$1$$$-st move Alice has to perform the $$$1$$$-st operation, since the string is currently a palindrome.  in the $$$2$$$-nd move Bob reverses the string.  in the $$$3$$$-rd move Alice again has to perform the $$$1$$$-st operation. All characters of the string are '1', game over.  Alice spends $$$2$$$ dollars while Bob spends $$$0$$$ dollars. Hence, Bob always wins.


The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string $$$s$$$ of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations:   Choose any $$$i$$$ ($$$1 \le i \le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar.  Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$). The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of the characters '0' and '1'. It is guaranteed that the string $$$s$$$ contains at least one '0'. Note that there is no limit on the sum of $$$n$$$ over test cases.

NoteIn the first test case of example,   in the $$$1$$$-st move, Alice will use the $$$2$$$-nd operation to reverse the string, since doing the $$$1$$$-st operation will result in her loss anyway. This also forces Bob to use the $$$1$$$-st operation.  in the $$$2$$$-nd move, Bob has to perform the $$$1$$$-st operation, since the $$$2$$$-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.  Alice spends $$$0$$$ dollars while Bob spends $$$1$$$ dollar. Hence, Alice wins.In the second test case of example,   in the $$$1$$$-st move Alice has to perform the $$$1$$$-st operation, since the string is currently a palindrome.  in the $$$2$$$-nd move Bob reverses the string.  in the $$$3$$$-rd move Alice again has to perform the $$$1$$$-st operation. All characters of the string are '1', game over.  Alice spends $$$2$$$ dollars while Bob spends $$$0$$$ dollars. Hence, Bob wins.


The weight of a sequence is defined as the number of unordered pairs of indexes $$$(i,j)$$$ (here $$$i \lt j$$$) with same value ($$$a_{i} = a_{j}$$$). For example, the weight of sequence $$$a = [1, 1, 2, 2, 1]$$$ is $$$4$$$. The set of unordered pairs of indexes with same value are $$$(1, 2)$$$, $$$(1, 5)$$$, $$$(2, 5)$$$, and $$$(3, 4)$$$.You are given a sequence $$$a$$$ of $$$n$$$ integers. Print the sum of the weight of all subsegments of $$$a$$$. A sequence $$$b$$$ is a subsegment of a sequence $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the sum of the weight of all subsegments of $$$a$$$.

Note  In test case $$$1$$$, all possible subsegments of sequence $$$[1, 2, 1, 1]$$$ having size more than $$$1$$$ are:   $$$[1, 2]$$$ having $$$0$$$ valid unordered pairs;  $$$[2, 1]$$$ having $$$0$$$ valid unordered pairs;  $$$[1, 1]$$$ having $$$1$$$ valid unordered pair;  $$$[1, 2, 1]$$$ having $$$1$$$ valid unordered pairs;  $$$[2, 1, 1]$$$ having $$$1$$$ valid unordered pair;  $$$[1, 2, 1, 1]$$$ having $$$3$$$ valid unordered pairs.  Answer is $$$6$$$. In test case $$$2$$$, all elements of the sequence are distinct. So, there is no valid unordered pair with the same value for any subarray. Answer is $$$0$$$.


You are given a tree with $$$n$$$ nodes, numerated from $$$0$$$ to $$$n-1$$$. For each $$$k$$$ between $$$0$$$ and $$$n$$$, inclusive, you have to count the number of unordered pairs $$$(u,v)$$$, $$$u \neq v$$$, such that the MEX of all the node labels in the shortest path from $$$u$$$ to $$$v$$$ (including end points) is $$$k$$$.The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^{5}$$$). The next $$$n-1$$$ lines of each test case describe the tree that has to be constructed. These lines contain two integers $$$u$$$ and $$$v$$$ ($$$0 \le u,v \le n-1$$$) denoting an edge between $$$u$$$ and $$$v$$$ ($$$u \neq v$$$). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^{5}$$$.

For each test case, print $$$n+1$$$ integers: the number of paths in the tree, such that the MEX of all the node labels in that path is $$$k$$$ for each $$$k$$$ from $$$0$$$ to $$$n$$$.


You are given an array $$$a$$$ of $$$n$$$ integers. Define the cost of some array $$$t$$$ as follows:$$$$$$cost(t) = \sum_{x \in set(t) } last(x) - first(x),$$$$$$ where $$$set(t)$$$ is the set of all values in $$$t$$$ without repetitions, $$$first(x)$$$, and $$$last(x)$$$ are the indices of the first and last occurrence of $$$x$$$ in $$$t$$$, respectively. In other words, we compute the distance between the first and last occurrences for each distinct element and sum them up.You need to split the array $$$a$$$ into $$$k$$$ consecutive segments such that each element of $$$a$$$ belongs to exactly one segment and the sum of the cost of individual segments is minimum.

The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 35\,000$$$, $$$1 \le k \le \min(n,100)$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$).

Output the minimum sum of the cost of individual segments.


Kavi has $$$2n$$$ points lying on the $$$OX$$$ axis, $$$i$$$-th of which is located at $$$x = i$$$.Kavi considers all ways to split these $$$2n$$$ points into $$$n$$$ pairs. Among those, he is interested in good pairings, which are defined as follows:Consider $$$n$$$ segments with ends at the points in correspondent pairs. The pairing is called good, if for every $$$2$$$ different segments $$$A$$$ and $$$B$$$ among those, at least one of the following holds:  One of the segments $$$A$$$ and $$$B$$$ lies completely inside the other.  $$$A$$$ and $$$B$$$ have the same length. Consider the following example:  $$$A$$$ is a good pairing since the red segment lies completely inside the blue segment.$$$B$$$ is a good pairing since the red and the blue segment have the same length.$$$C$$$ is not a good pairing since none of the red or blue segments lies inside the other, neither do they have the same size.Kavi is interested in the number of good pairings, so he wants you to find it for him. As the result can be large, find this number modulo $$$998244353$$$.Two pairings are called different, if some two points are in one pair in some pairing and in different pairs in another.

The single line of the input contains a single integer $$$n$$$ $$$(1\le n \le 10^6)$$$.

Print the number of good pairings modulo $$$998244353$$$.

NoteThe good pairings for the second example are:   In the third example, the good pairings are:


Parsa has a humongous tree on $$$n$$$ vertices.On each vertex $$$v$$$ he has written two integers $$$l_v$$$ and $$$r_v$$$.To make Parsa's tree look even more majestic, Nima wants to assign a number $$$a_v$$$ ($$$l_v \le a_v \le r_v$$$) to each vertex $$$v$$$ such that the beauty of Parsa's tree is maximized.Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of $$$|a_u - a_v|$$$ over all edges $$$(u, v)$$$ of the tree.Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.

The first line contains an integer $$$t$$$ $$$(1\le t\le 250)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 10^5)$$$ — the number of vertices in Parsa's tree. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ $$$(1 \le u , v \le n, u\neq v)$$$ meaning that there is an edge between the vertices $$$u$$$ and $$$v$$$ in Parsa's tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the maximum possible beauty for Parsa's tree.

NoteThe trees in the example:  In the first test case, one possible assignment is $$$a = \{1, 8\}$$$ which results in $$$|1 - 8| = 7$$$.In the second test case, one of the possible assignments is $$$a = \{1, 5, 9\}$$$ which results in a beauty of $$$|1 - 5| + |5 - 9| = 8$$$


Soroush and Keshi each have a labeled and rooted tree on $$$n$$$ vertices. Both of their trees are rooted from vertex $$$1$$$.Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on $$$n$$$ vertices.They add an edge between vertices $$$u$$$ and $$$v$$$ in the memorial graph if both of the following conditions hold:   One of $$$u$$$ or $$$v$$$ is the ancestor of the other in Soroush's tree.  Neither of $$$u$$$ or $$$v$$$ is the ancestor of the other in Keshi's tree. Here vertex $$$u$$$ is considered ancestor of vertex $$$v$$$, if $$$u$$$ lies on the path from $$$1$$$ (the root) to the $$$v$$$.Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big. Help Mashtali by finding the size of the maximum clique in the memorial graph.As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.

The first line contains an integer $$$t$$$ $$$(1\le t\le 3 \cdot 10^5)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(2\le n\le 3 \cdot 10^5)$$$. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \ldots, a_n$$$ $$$(1 \le a_i < i)$$$, $$$a_i$$$ being the parent of the vertex $$$i$$$ in Soroush's tree. The third line of each test case contains $$$n-1$$$ integers $$$b_2, \ldots, b_n$$$ $$$(1 \le b_i < i)$$$, $$$b_i$$$ being the parent of the vertex $$$i$$$ in Keshi's tree. It is guaranteed that the given graphs are trees. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case print a single integer — the size of the maximum clique in the memorial graph.

NoteIn the first and third test cases, you can pick any vertex.In the second test case, one of the maximum cliques is $$$\{2, 3, 4, 5\}$$$.In the fourth test case, one of the maximum cliques is $$$\{3, 4, 6\}$$$.


There are $$$n$$$ cities in Shaazzzland, numbered from $$$0$$$ to $$$n-1$$$. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.AaParsa has planted $$$m$$$ transport cannons in the cities of Shaazzzland. The $$$i$$$-th cannon is planted in the city $$$a_i$$$ and is initially pointing at city $$$b_i$$$.It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).AaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the $$$i$$$-th cannon is pointing towards the city $$$x$$$ at some second, it will target the city $$$(x + 1) \mod n$$$ at the next second.As their name suggests, transport cannons are for transportation, specifically for human transport. If you use the $$$i$$$-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for $$$c_i$$$ seconds before reaching your target destination.If you still don't get it, using the $$$i$$$-th cannon at the $$$s$$$-th second (using which is only possible if you are currently in the city $$$a_i$$$) will shoot you to the city $$$(b_i + s) \mod n$$$ and you'll land in there after $$$c_i$$$ seconds (so you'll be there in the $$$(s + c_i)$$$-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne. AaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second $$$0$$$. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city $$$u$$$ from city $$$v$$$ using the cannons for every pair of cities $$$(u, v)$$$.Note that AaParsa can stay in a city for as long as he wants.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 600 , n \le m \le n^2)$$$ — the number of cities and cannons correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$ and $$$c_i$$$ $$$( 0 \le a_i , b_i \le n-1 , 1 \le c_i \le 10^9)$$$, denoting the cannon in the city $$$a_i$$$, which is initially pointing to $$$b_i$$$ and travelling by which takes $$$c_i$$$ seconds. It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).

Print $$$n$$$ lines, each line should contain $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line should be equal to the minimum time required to reach city $$$j$$$ from city $$$i$$$.

NoteIn the first example one possible path for going from $$$0$$$ to $$$2$$$ would be:   Stay inside $$$0$$$ and do nothing for $$$1$$$ second.  Use the first cannon and land at $$$2$$$ after $$$1$$$ second.  Note that: we could have used the second cannon in $$$0$$$-th second but it would have taken us $$$3$$$ seconds to reach city $$$2$$$ in that case.


Today is Mashtali's birthday! He received a Hagh tree from Haj Davood as his birthday present!A directed tree is called a Hagh tree iff:   The length of the longest directed path in it is exactly $$$n$$$.  Every vertex has at most three edges attached to it independent of their orientation.  Let's call vertices $$$u$$$ and $$$v$$$ friends if one of them has a directed path to the other. For every pair of vertices $$$u$$$ and $$$v$$$ that are not friends, there should exist a vertex $$$w$$$ that is friends with both $$$u$$$ and $$$v$$$ (a mutual friend). After opening his gift, Mashtali found out that the labels on the vertices were gone.Immediately, he asked himself: how many different unlabeled Hagh trees are there? That is, how many possible trees could he have received as his birthday present?At the first glance, the number of such trees seemed to be infinite since there was no limit on the number of vertices; but then he solved the problem and proved that there's a finite number of unlabeled Hagh trees!Amazed by this fact, he shared the task with you so that you could enjoy solving it as well. Since the answer can be rather large he asked you to find the number of different unlabeled Hagh trees modulo $$$998244353$$$.Here two trees are considered different, if they are not isomorphic: if there is no way to map nodes of one tree to the second tree, so that edges are mapped to edges preserving the orientation.Some examples for $$$n = 2$$$:   Directed trees $$$D$$$ and $$$E$$$ are Hagh. $$$C$$$ is not Hagh because it has a vertex with $$$4$$$ edges attached to it. $$$A$$$ and $$$B$$$ are not Hagh because their longest directed paths are not equal to $$$n$$$. Also in $$$B$$$ the leftmost and rightmost vertices are not friends neither do they have a mutual friend.

The first line of input contains a single integer $$$n$$$ $$$(1 \le n \le 10^6)$$$.

Print a single integer, the answer to Mashtali's task modulo $$$998244353$$$.

NoteAll the five Hagh trees for $$$n = 1$$$:


To AmShZ, all arrays are equal, but some arrays are more-equal than others. Specifically, the arrays consisting of $$$n$$$ elements from $$$1$$$ to $$$n$$$ that can be turned into permutations of numbers from $$$1$$$ to $$$n$$$ by adding a non-negative integer to each element.Mashtali who wants to appear in every problem statement thinks that an array $$$b$$$ consisting of $$$k$$$ elements is compatible with a more-equal array $$$a$$$ consisting of $$$n$$$ elements if for each $$$1 \le i \le k$$$ we have $$$1 \le b_i \le n$$$ and also $$$a_{b_1} = a_{b_2} = \ldots = a_{b_k}$$$.Find the number of pairs of arrays $$$a$$$ and $$$b$$$ such that $$$a$$$ is a more-equal array consisting of $$$n$$$ elements and $$$b$$$ is an array compatible with $$$a$$$ consisting of $$$k$$$ elements modulo $$$998244353$$$.Note that the elements of $$$b$$$ are not necessarily distinct, same holds for $$$a$$$.

The first line of input contains two integers $$$n$$$ and $$$k$$$ $$$(1 \le n \le 10^9 , 1 \le k \le 10^5)$$$.

Print a single integer — the answer to the problem modulo $$$998244353$$$.


Eshag has an array $$$a$$$ consisting of $$$n$$$ integers.Eshag can perform the following operation any number of times: choose some subsequence of $$$a$$$ and delete every element from it which is strictly larger than $$$AVG$$$, where $$$AVG$$$ is the average of the numbers in the chosen subsequence.For example, if $$$a = [1 , 4 , 3 , 2 , 4]$$$ and Eshag applies the operation to the subsequence containing $$$a_1$$$, $$$a_2$$$, $$$a_4$$$ and $$$a_5$$$, then he will delete those of these $$$4$$$ elements which are larger than $$$\frac{a_1+a_2+a_4+a_5}{4} = \frac{11}{4}$$$, so after the operation, the array $$$a$$$ will become $$$a = [1 , 3 , 2]$$$.Your task is to find the maximum number of elements Eshag can delete from the array $$$a$$$ by applying the operation described above some number (maybe, zero) times.A sequence $$$b$$$ is a subsequence of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements.

The first line contains an integer $$$t$$$ $$$(1\le t\le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 100)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1\le a_i \le 100)$$$ — the elements of the array $$$a$$$.

For each test case print a single integer — the maximum number of elements Eshag can delete from the array $$$a$$$.

NoteConsider the first test case.Initially $$$a = [1, 1, 1, 2, 2, 3]$$$.In the first operation, Eshag can choose the subsequence containing $$$a_1$$$, $$$a_5$$$ and $$$a_6$$$, their average is equal to $$$\frac{a_1 + a_5 + a_6}{3} = \frac{6}{3} = 2$$$. So $$$a_6$$$ will be deleted.After this $$$a = [1, 1, 1, 2, 2]$$$.In the second operation, Eshag can choose the subsequence containing the whole array $$$a$$$, the average of all its elements is equal to $$$\frac{7}{5}$$$. So $$$a_4$$$ and $$$a_5$$$ will be deleted.After this $$$a = [1, 1, 1]$$$.In the second test case, Eshag can't delete any element.


A sequence $$$(b_1, b_2, \ldots, b_k)$$$ is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $$$(i, j)$$$ with $$$1 \le i<j \le k$$$, we have $$$|a_i-a_j|\geq MAX$$$, where $$$MAX$$$ is the largest element of the sequence. In particular, any sequence of length at most $$$1$$$ is strange.For example, the sequences $$$(-2021, -1, -1, -1)$$$ and $$$(-1, 0, 1)$$$ are strange, but $$$(3, 0, 1)$$$ is not, because $$$|0 - 1| < 3$$$.Sifid has an array $$$a$$$ of $$$n$$$ integers. Sifid likes everything big, so among all the strange subsequences of $$$a$$$, he wants to find the length of the longest one. Can you help him?A sequence $$$c$$$ is a subsequence of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements.

The first line contains an integer $$$t$$$ $$$(1\le t\le 10^4)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 10^5)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(-10^9\le a_i \le 10^9)$$$ — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case output a single integer — the length of the longest strange subsequence of $$$a$$$.

NoteIn the first test case, one of the longest strange subsequences is $$$(a_1, a_2, a_3, a_4)$$$In the second test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5, a_7)$$$.In the third test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5)$$$.In the fourth test case, one of the longest strange subsequences is $$$(a_2)$$$.In the fifth test case, one of the longest strange subsequences is $$$(a_1, a_2, a_4)$$$.


Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$), denoting the number to be represented.

For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.

NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\,000\,000\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$.


To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.The table can be represented as a rectangle with height $$$h$$$ and width $$$w$$$, divided into $$$h \times w$$$ cells. Let $$$(i, j)$$$ denote the cell in the $$$i$$$-th row and the $$$j$$$-th column of the rectangle ($$$1 \le i \le h$$$; $$$1 \le j \le w$$$).Into each cell of the table you can either put a plate or keep it empty.As each guest has to be seated next to their plate, you can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell $$$(i, j)$$$ you put a plate into, at least one of the following conditions must be satisfied: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell $$$(i, j)$$$ contains a plate, you can't put plates into cells $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.Put as many plates on the table as possible without violating the rules above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each of the following $$$t$$$ lines describes one test case and contains two integers $$$h$$$ and $$$w$$$ ($$$3 \le h, w \le 20$$$) — the height and the width of the table.

For each test case, print $$$h$$$ lines containing $$$w$$$ characters each. Character $$$j$$$ in line $$$i$$$ must be equal to $$$1$$$ if you are putting a plate into cell $$$(i, j)$$$, and $$$0$$$ otherwise. If there are multiple answers, print any. All plates must be put on the edge of the table. No two plates can be put into cells that have a common side or corner. The number of plates put on the table under these conditions must be as large as possible. You are allowed to print additional empty lines.

NoteFor the first test case, example output contains the only way to put $$$6$$$ plates on the table.For the second test case, there are many ways to put $$$4$$$ plates on the table, example output contains one of them.Putting more than $$$6$$$ plates in the first test case or more than $$$4$$$ plates in the second test case is impossible.


You and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between $$$0$$$ and $$$100$$$ points, inclusive, for each stage, independently of other contestants.Points received by contestants in different stages are used for forming overall contest results. Suppose that $$$k$$$ stages of the contest are completed. For each contestant, $$$k - \lfloor \frac{k}{4} \rfloor$$$ stages with the highest scores are selected, and these scores are added up. This sum is the overall result of the contestant. (Here $$$\lfloor t \rfloor$$$ denotes rounding $$$t$$$ down.)For example, suppose $$$9$$$ stages are completed, and your scores are $$$50, 30, 50, 50, 100, 10, 30, 100, 50$$$. First, $$$7$$$ stages with the highest scores are chosen — for example, all stages except for the $$$2$$$-nd and the $$$6$$$-th can be chosen. Then your overall result is equal to $$$50 + 50 + 50 + 100 + 30 + 100 + 50 = 430$$$.As of now, $$$n$$$ stages are completed, and you know the points you and Ilya got for these stages. However, it is unknown how many more stages will be held. You wonder what the smallest number of additional stages is, after which your result might become greater than or equal to Ilya's result, at least in theory. Find this number!

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of completed stages. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$) — your points for the completed stages. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 100$$$) — Ilya's points for the completed stages. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest number of additional stages required for your result to be able to become greater than or equal to Ilya's result. If your result is already not less than Ilya's result, print $$$0$$$.

NoteIn the first test case, you have scored $$$100$$$ points for the first stage, while Ilya has scored $$$0$$$. Thus, your overall result ($$$100$$$) is already not less than Ilya's result ($$$0$$$).In the second test case, you have scored $$$0$$$ points for the first stage, while Ilya has scored $$$100$$$. A single stage with an opposite result is enough for both your and Ilya's overall scores to become equal to $$$100$$$.In the third test case, your overall result is $$$30 + 40 + 50 = 120$$$, while Ilya's result is $$$100 + 100 + 100 = 300$$$. After three additional stages your result might become equal to $$$420$$$, while Ilya's result might become equal to $$$400$$$.In the fourth test case, your overall result after four additional stages might become equal to $$$470$$$, while Ilya's result might become equal to $$$400$$$. Three stages are not enough.


Every December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.$$$n$$$ employees numbered from $$$1$$$ to $$$n$$$ take part in the event. Each employee $$$i$$$ is assigned a different employee $$$b_i$$$, to which employee $$$i$$$ has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all $$$b_i$$$ must be distinct integers between $$$1$$$ and $$$n$$$, and for any $$$i$$$, $$$b_i \ne i$$$ must hold.The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee $$$i$$$ has said that they wish to make a gift to employee $$$a_i$$$.Find a valid assignment $$$b$$$ that maximizes the number of fulfilled wishes of the employees.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of participants of the event. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne i$$$) — wishes of the employees in order from $$$1$$$ to $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print two lines. In the first line, print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of fulfilled wishes in your assignment. In the second line, print $$$n$$$ distinct integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$; $$$b_i \ne i$$$) — the numbers of employees assigned to employees $$$1, 2, \ldots, n$$$. $$$k$$$ must be equal to the number of values of $$$i$$$ such that $$$a_i = b_i$$$, and must be as large as possible. If there are multiple answers, print any.

NoteIn the first test case, two valid assignments exist: $$$[3, 1, 2]$$$ and $$$[2, 3, 1]$$$. The former assignment fulfills two wishes, while the latter assignment fulfills only one. Therefore, $$$k = 2$$$, and the only correct answer is $$$[3, 1, 2]$$$.


Prefix function of string $$$t = t_1 t_2 \ldots t_n$$$ and position $$$i$$$ in it is defined as the length $$$k$$$ of the longest proper (not equal to the whole substring) prefix of substring $$$t_1 t_2 \ldots t_i$$$ which is also a suffix of the same substring.For example, for string $$$t = $$$ abacaba the values of the prefix function in positions $$$1, 2, \ldots, 7$$$ are equal to $$$[0, 0, 1, 0, 1, 2, 3]$$$.Let $$$f(t)$$$ be equal to the maximum value of the prefix function of string $$$t$$$ over all its positions. For example, $$$f($$$abacaba$$$) = 3$$$.You are given a string $$$s$$$. Reorder its characters arbitrarily to get a string $$$t$$$ (the number of occurrences of any character in strings $$$s$$$ and $$$t$$$ must be equal). The value of $$$f(t)$$$ must be minimized. Out of all options to minimize $$$f(t)$$$, choose the one where string $$$t$$$ is the lexicographically smallest.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The only line of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase English letters. It is guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single string $$$t$$$. The multisets of letters in strings $$$s$$$ and $$$t$$$ must be equal. The value of $$$f(t)$$$, the maximum of prefix functions in string $$$t$$$, must be as small as possible. String $$$t$$$ must be the lexicographically smallest string out of all strings satisfying the previous conditions.

NoteA string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.In the first test case, $$$f(t) = 0$$$ and the values of prefix function are $$$[0, 0, 0, 0, 0]$$$ for any permutation of letters. String ckpuv is the lexicographically smallest permutation of letters of string vkcup.In the second test case, $$$f(t) = 1$$$ and the values of prefix function are $$$[0, 1, 0, 1, 0, 1, 0]$$$.In the third test case, $$$f(t) = 5$$$ and the values of prefix function are $$$[0, 1, 2, 3, 4, 5]$$$.


Getting ready for VK Fest 2021, you prepared a table with $$$n$$$ rows and $$$n$$$ columns, and filled each cell of this table with some event related with the festival that could either happen or not: for example, whether you will win a prize on the festival, or whether it will rain.Forecasting algorithms used in VK have already estimated the probability for each event to happen. Event in row $$$i$$$ and column $$$j$$$ will happen with probability $$$a_{i, j} \cdot 10^{-4}$$$. All of the events are mutually independent.Let's call the table winning if there exists a line such that all $$$n$$$ events on it happen. The line could be any horizontal line (cells $$$(i, 1), (i, 2), \ldots, (i, n)$$$ for some $$$i$$$), any vertical line (cells $$$(1, j), (2, j), \ldots, (n, j)$$$ for some $$$j$$$), the main diagonal (cells $$$(1, 1), (2, 2), \ldots, (n, n)$$$), or the antidiagonal (cells $$$(1, n), (2, n - 1), \ldots, (n, 1)$$$).Find the probability of your table to be winning, and output it modulo $$$31\,607$$$ (see Output section).

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 21$$$) — the dimensions of the table. The $$$i$$$-th of the next $$$n$$$ lines contains $$$n$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, n}$$$ ($$$0 < a_{i, j} < 10^4$$$). The probability of event in cell $$$(i, j)$$$ to happen is $$$a_{i, j} \cdot 10^{-4}$$$.

Print the probability that your table will be winning, modulo $$$31\,607$$$. Formally, let $$$M = 31\,607$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

NoteIn the first example, any two events form a line, and the table will be winning if any two events happen. The probability of this is $$$\frac{11}{16}$$$, and $$$5927 \cdot 16 \equiv 11 \pmod{31\,607}$$$.


You have two strings $$$a$$$ and $$$b$$$ of equal length $$$n$$$ consisting of characters 0 and 1, and an integer $$$k$$$.You need to make strings $$$a$$$ and $$$b$$$ equal.In one step, you can choose any substring of $$$a$$$ containing exactly $$$k$$$ characters 1 (and arbitrary number of characters 0) and reverse it. Formally, if $$$a = a_1 a_2 \ldots a_n$$$, you can choose any integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) such that there are exactly $$$k$$$ ones among characters $$$a_l, a_{l+1}, \ldots, a_r$$$, and set $$$a$$$ to $$$a_1 a_2 \ldots a_{l-1} a_r a_{r-1} \ldots a_l a_{r+1} a_{r+2} \ldots a_n$$$.Find a way to make $$$a$$$ equal to $$$b$$$ using at most $$$4n$$$ reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2000$$$). Description of the test cases follows. Each test case consists of three lines. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2000$$$; $$$0 \le k \le n$$$). The second line contains string $$$a$$$ of length $$$n$$$. The third line contains string $$$b$$$ of the same length. Both strings consist of characters 0 and 1. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case, if it's impossible to make $$$a$$$ equal to $$$b$$$ in at most $$$4n$$$ reversals, print a single integer $$$-1$$$. Otherwise, print an integer $$$m$$$ ($$$0 \le m \le 4n$$$), denoting the number of reversals in your sequence of steps, followed by $$$m$$$ pairs of integers $$$l_i, r_i$$$ ($$$1 \le l_i \le r_i \le n$$$), denoting the boundaries of the substrings of $$$a$$$ to be reversed, in chronological order. Each substring must contain exactly $$$k$$$ ones at the moment of reversal. Note that $$$m$$$ doesn't have to be minimized. If there are multiple answers, print any.

NoteIn the first test case, after the first reversal $$$a = $$$ 011010, after the second reversal $$$a = $$$ 010110, after the third reversal $$$a = $$$ 010101.


Alan Turing is standing on a tape divided into cells that is infinite in both directions.Cells are numbered with consecutive integers from left to right. Alan is initially standing in cell $$$0$$$. Every cell $$$x$$$ has cell $$$x - 1$$$ on the left and cell $$$x + 1$$$ on the right.Each cell can either contain an integer or be empty. Initially all cells are empty.Alan is given a permutation $$$a_1, a_2, \ldots, a_n$$$ of integers from $$$1$$$ to $$$n$$$ that was chosen uniformly at random among all permutations of length $$$n$$$.At time $$$1$$$, integer $$$a_1$$$ is written down into cell $$$0$$$ where Alan is located.At each time $$$i$$$ from $$$2$$$ to $$$n$$$ inclusive, the following happens. First, Alan decides whether to stay in the same cell he's currently in, move to the neighboring cell on the left, or move to the neighboring cell on the right. After that, integer $$$a_i$$$ is written down into the cell where Alan is located. If that cell already contained some integer, the old integer is overwritten and irrelevant from that moment on.Once $$$a_n$$$ is written down into some cell at time $$$n$$$, sequence $$$b$$$ of all integers contained in the cells from left to right is formed. Empty cells are ignored.Turing's award is equal to the length of the longest increasing subsequence of sequence $$$b$$$.Help Alan and determine the largest possible value of his award if he acts optimally.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. Each test case is given in two lines. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 15\,000$$$) — the length of the permutation given to Alan. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the elements of the permutation. It is guaranteed that the permutation was chosen uniformly at random among all permutations of the corresponding length. The sum of $$$n$$$ over all test cases does not exceed $$$15\,000$$$.

For each test case output a single integer — the largest possible value of Turing's award. Hacks are not allowed for this problem.

NoteLongest increasing subsequence of sequence $$$b$$$ is the longest increasing sequence that can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.In the first test case, Alan can make a decision only at time $$$2$$$. If Alan stays in cell $$$0$$$, sequence $$$b$$$ will be equal to $$$[2]$$$. If Alan moves to the left, to cell $$$-1$$$, sequence $$$b$$$ will be equal to $$$[2, 1]$$$. If Alan moves to the right, to cell $$$1$$$, sequence $$$b$$$ will be equal to $$$[1, 2]$$$. Only in the last case the length of the longest increasing subsequence of $$$b$$$ is $$$2$$$, therefore, the answer is equal to $$$2$$$.In the second test case, one of the optimal sequences of actions looks as follows: move to the left at times $$$2$$$ and $$$3$$$, and move to the right at time $$$4$$$. Then sequence $$$b$$$ will be equal to $$$[2, 3, 4]$$$, and the length of its longest increasing subsequence is $$$3$$$.In the third test case, one of the best ways is to always move to the left. Then sequence $$$b$$$ will be equal to $$$[2, 1, 4, 7, 5, 6, 3]$$$, and the length of its longest increasing subsequence is $$$4$$$.In the fourth test case, one of the best ways is to move to the right four times, then move to the left once, and stay in the same cell once. Sequence $$$b$$$ will be equal to $$$[5, 2, 3, 4, 6]$$$.


Немногие знают, что сотрудники ВКонтакте могут менять цвет подсветки в куполе знаменитого Дома Зингера, где расположена штаб-квартира ВКонтакте. Для этого нужно всего лишь отправить сообщение с цветом в специальный чат «Зингер | color», а бот его распознает и сменит подсветку. При этом на время городских мероприятий смена цвета блокируется.Формально, бот обрабатывает три типа сообщений:   lock: заблокировать изменение цвета. Если оно и так заблокировано на данный момент, сообщение игнорируется.  unlock: разблокировать изменение цвета. Если оно и так разблокировано на данный момент, сообщение игнорируется.  red / orange / yellow / green / blue / indigo / violet: изменить цвет купола на заданный, если изменение цвета на данный момент не заблокировано. Вам дана история сообщений, полученных ботом, в хронологическом порядке. Считайте, что перед получением первого сообщения купол подсвечивается голубым (blue), а изменение цвета не заблокировано.Определите, какой цвет будет у купола Дома Зингера после обработки этих сообщений.

стандартный ввод

стандартный вывод

512 мегабайт

В первой строке задано одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — число сообщений, полученных ботом. В следующих $$$n$$$ строках заданы сообщения, полученные ботом, в хронологическом порядке, по одному сообщению в строке. Каждое сообщение — строка из следующего набора: lock, unlock, red, orange, yellow, green, blue, indigo, violet.

Выведите цвет купола после обработки сообщений ботом.

7
red
violet
unlock
red
orange
lock
indigo


ВКонтакте открыла второй штаб в Санкт-Петербурге! Вы не преминули возможностью сменить обстановку и решили переехать из офиса в Доме Зингера в офис на Красном мосту.Для комфортной работы вам потребуются два монитора с одинаковой высотой, чтобы изображение на них выглядело единым целым. На складе офиса на Красном мосту есть $$$n$$$ мониторов, $$$i$$$-й из них имеет ширину $$$w_i$$$ и высоту $$$h_i$$$. Любой монитор можно повернуть на 90 градусов, и тогда он будет иметь ширину $$$h_i$$$ и высоту $$$w_i$$$.Назовём неупорядоченную пару из двух различных мониторов подходящей, если можно их повернуть так, чтобы они имели одинаковую высоту. Любой из мониторов в паре можно как повернуть относительно исходной ориентации, так и не поворачивать.Подсчитайте подходящие пары мониторов.

стандартный ввод

стандартный вывод

512 мегабайт

В первой строке задано одно целое число $$$n$$$ — число мониторов на складе. В каждой из следующих $$$n$$$ строк заданы два целых числа $$$w_i$$$ и $$$h_i$$$ ($$$1 \le w_i, h_i \le 10^9$$$) — ширина и высота $$$i$$$-го монитора. Обратите внимание, что мониторы могут быть квадратными ($$$w_i = h_i$$$), а размеры разных мониторов могут совпадать. В этой версии задачи $$$2 \le n \le 10^3$$$.

Выведите число подходящих пар мониторов.

ПримечаниеВ первом примере подходящими являются пары мониторов с номерами $$$(1, 2)$$$, $$$(1, 4)$$$, $$$(1, 5)$$$, $$$(3, 4)$$$, $$$(4, 5)$$$.Во втором примере все пары мониторов — подходящие.


Все готовятся к VK Fest 2021! Для того, чтобы зрителям была лучше видна главная сцена, планируется построить амфитеатр. В этой задаче мы будем рассматривать его сбоку — схематично он будет иметь форму лестницы из $$$n$$$ одинаковых квадратов. Лестница — это одна или более башен квадратов, выстроенных в ряд, где высоты башен невозрастают слева направо.На следующем рисунке можно видеть три разные фигуры из $$$12$$$ квадратов. Первые две фигуры — лестницы, а третья — нет.  Из эстетических соображений было решено, что амфитеатр должен быть симметричным. Формально, амфитеатр называется симметричным, если при отражении его схемы относительно прямой $$$x = y$$$ получается тот же самый рисунок (где ось $$$x$$$ направлена слева направо, а ось $$$y$$$ — снизу вверх). Например, первая лестница на рисунке выше — симметричная, а вторая — нет.  Кроме того, амфитеатр должен быть максимально компактным — а именно, сторона минимального квадрата, внутрь которого можно его поместить, должна быть как можно меньше.По заданному числу $$$n$$$ нарисуйте схему амфитеатра из ровно $$$n$$$ квадратов, удовлетворяющую всем условиям.

стандартный ввод

стандартный вывод

512 мегабайт

В единственной строке задано одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — число квадратов, из которых нужно составить схему амфитеатра.

Если не существует схемы амфитеатра из $$$n$$$ квадратов, выведите единственное число $$$-1$$$. Иначе в первой строке выведите целое число $$$m$$$ — минимальное возможное число строк и столбцов в схеме амфитеатра. Далее выведите $$$m$$$ строк, описывающих схему. Каждая строка должна содержать ровно $$$m$$$ символов 'o' (строчная латинская буква) или '.', где 'o' описывает построенный квадрат, а '.' — пустое место. Схема амфитеатра должна состоять ровно из $$$n$$$ символов 'o'. Ячейка в левом нижнем углу должна содержать квадрат. Если возможных ответов с минимальным $$$m$$$ несколько, выведите любой из них.


Немногие знают, что сотрудники ВКонтакте могут менять цвет подсветки в куполе знаменитого Дома Зингера, где расположена штаб-квартира ВКонтакте. Для этого нужно всего лишь отправить сообщение с цветом в специальный чат «Зингер | color», а бот его распознает и сменит подсветку. При этом на время городских мероприятий смена цвета блокируется.Формально, бот обрабатывает три типа сообщений:   lock: заблокировать изменение цвета. Если оно и так заблокировано на данный момент, сообщение игнорируется.  unlock: разблокировать изменение цвета. Если оно и так разблокировано на данный момент, сообщение игнорируется.  red / orange / yellow / green / blue / indigo / violet: изменить цвет купола на заданный, если изменение цвета на данный момент не заблокировано. Вам дана история сообщений, полученных ботом, в хронологическом порядке. Считайте, что перед получением первого сообщения купол подсвечивается голубым (blue), а изменение цвета не заблокировано.В качестве эксперимента было решено поддержать в боте эффективную обработку редактирования сообщений. Вам дана последовательность пар вида $$$(i, msg)$$$, означающих, что $$$i$$$-е в хронологическом порядке сообщение было отредактировано и теперь имеет вид $$$msg$$$. Обратите внимание, что редактироваться может любое сообщение, и при редактировании сообщения бот должен обработать всю историю сообщений заново (в частности, перед обработкой первого сообщения цвет купола голубой, а изменение цвета не заблокировано).Определите, какой цвет будет у купола Дома Зингера до первой операции редактирования, а также после каждой операции редактирования.

стандартный ввод

стандартный вывод

512 мегабайт

В первой строке задано одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — число сообщений, полученных ботом. В следующих $$$n$$$ строках заданы сообщения, полученные ботом, в хронологическом порядке, по одному сообщению в строке. Каждое сообщение — строка из следующего набора: lock, unlock, red, orange, yellow, green, blue, indigo, violet. Сообщения пронумерованы от $$$1$$$ до $$$n$$$. В следующей строке задано одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — число операций редактирования сообщений. В следующих $$$t$$$ строках заданы операции редактирования в хронологическом порядке, по одной в строке. Каждая операция — пара из номера сообщения $$$i$$$ ($$$1 \le i \le n$$$) и его нового содержимого $$$msg$$$, также принадлежащего набору lock, unlock, red, orange, yellow, green, blue, indigo, violet.

Выведите $$$t+1$$$ строку: цвет купола до первой операции редактирования, а также после каждой операции редактирования в хронологическом порядке.

7
red
violet
unlock
red
orange
lock
indigo
6
5 green
6 lock
6 yellow
4 lock
1 lock
5 unlock

1
red
8
1 lock
1 unlock
1 blue
1 unlock
1 unlock
1 lock
1 yellow
1 lock

orange
green
green
indigo
violet
blue
indigo

red
blue
blue
blue
blue
blue
blue
yellow
blue