Permutation

This is an interactive problem.

There is a hidden permutation of n. Recall that a permutation of n is a sequence where each integer from 1 to n (both inclusive) appears exactly once. Piggy wants to unravel the permutation with some queries.

Each query must consist of a sequence (not necessarily a permutation) with n integers ranging from 1 to n (both inclusive). Each query is answered with an integer x, indicating the number of the positions where the corresponding element in Piggy's query sequence matches that of the hidden permutation. For example, if the hidden permutation is {1, 3, 4, 2, 5} and the sequence Piggy asks is {2, 3, 5, 2, 5}, he'll receive 3 as the answer.

As Piggy is busy recently, he gives this problem to you. This problem is graded based on the number of queries you recieve. In order to receive any points, you must get better than a baseline of 10000 queries. After that, your answer will be compared to a solution best_queries.
Your final score will be calculated as the average of 100 * clamp((10000 - your_queries)/(10000 - best_queries), 0, 1) across all cases

Input

There is only one test case in each test file.

The first line of the input contains an integer n (1≤n≤10^3) indicating the length of the hidden permutation.

Interaction

To ask a query, output one line. First output 0 followed by a space, then print a sequence of n integers ranging from 1 to n separated by a space. After flushing your output, your program should read a single integer x indicating the answer to your query.

If you want to guess the permutation, output one line. First output 1 followed by a space, then print a permutation of n separated by a space. After flushing your output, your program should exit immediately.

Note that the answer for each test case is pre-determined. That is, the interactor is not adaptive. Also note that your guess does not count as a query.

To flush your output, you can use:

    fflush(stdout) (if you use printf) or cout.flush() (if you use cout) in C and C++.

    System.out.flush() in Java.

    stdout.flush() in Python.

Example

(The example content is missing from the provided text).

Note

Please note that if you receive a Time Limit Exceeded verdict, it is possible that your query is invalid or the number of queries exceeds the limit.

Time limit: 4 seconds

Memory Limit: 1024 MB

Example input:

0 3 1 3 2 2

0 3 1 5 2 2

0 3 5 4 4 4

1 3 1 5 2 4

Example output:
5

3

4

2

# Set the problem type to interactive
type: interactive

# Specify the interactor source file
interactor: interactor.cc

# Time and memory limits still apply to the contestant's solution
time: 1s
memory: 256m

# The subtasks section works the same way
subtasks:
  - score: 100
    n_cases: 3 # Looks for 1.in, 2.in, ... 5.in


Chameleon

This is an interactive problem.

There are 2N chameleons in the JOI Zoo, numbered from 1 to 2N. Among them, N chameleons are gender X, and N are gender Y. Every chameleon has its own "original color." The original colors satisfy the following properties:
- The original colors of chameleons of the same gender are all distinct.
- For every chameleon, there exists exactly one chameleon of the opposite gender that has the same original color.

It is currently the season of love in JOI Zoo. Every chameleon loves exactly one chameleon of the opposite gender. The love relationships satisfy:
- Every chameleon loves exactly one chameleon of the opposite gender.
- The chameleon a loves, denoted by b, has an original color different from a's original color.
- No two chameleons love the same chameleon.

You can organize meetings for some chameleons. For each chameleon s attending the meeting, its "displayed color" is determined as follows:
- If the chameleon that s loves also attends the meeting, the displayed color of s is the original color of the chameleon s loves.
- Otherwise, the displayed color of s is the original color of s itself.

The displayed color of a chameleon may change across different meetings. For each meeting, you can only see the number of distinct colors among the attending chameleons. Your goal is to find all pairs of chameleons that have the same original color using at most 20,000 queries.

Interaction Protocol

This is an interactive problem. Your program must interact with the judge through standard input and output.

At the beginning, the judge will output one integer N (the number of chameleons of each gender). You should read this value first.

To make a query:
- Output "Query k c1 c2 ... ck" where:
  - k is the number of chameleons attending the meeting (1 ≤ k ≤ 2N)
  - c1, c2, ..., ck are the IDs of chameleons attending (each between 1 and 2N, all distinct)
- After outputting, flush your output stream
- The judge will respond with one integer: the number of distinct displayed colors in this meeting
- You can make at most 20,000 queries. Exceeding this limit results in Wrong Answer.

To submit an answer:
- Output "Answer a b" where a and b are two chameleons with the same original color (1 ≤ a, b ≤ 2N, a ≠ b)
- You must call this exactly N times to report all N pairs
- Each pair must be correct and distinct (no duplicates)

Important:
- After each output, you must flush your output stream:
  - In C++: cout.flush() or cout << endl; (endl flushes automatically)
  - In Python: sys.stdout.flush()
  - In Java: System.out.flush()
- The judge is NOT adaptive; all secret information is fixed at the start.

Scoring

This problem is graded based on the number of Query operations Q.
- If Q ≤ 4,000: you receive 100 points
- If 4,000 < Q ≤ 20,000: you receive 100 × (20,000 - Q) / (20,000 - 4,000) points
- If Q > 20,000: you receive 0 points

Your final score is the average score across all test cases.

Constraints

- 2 ≤ N ≤ 500

Example Interaction

For N = 4 (8 chameleons total), suppose:
- Chameleons 1, 2, 3, 4 are gender X
- Chameleons 5, 6, 7, 8 are gender Y
- Color pairs: (1,5), (2,8), (3,7), (4,6) have the same colors
- Love relationships are fixed but hidden

Interaction Example:

> 4
(Judge outputs N = 4)

< Query 1 1
(You query with only chameleon 1)

> 0
(Judge responds: 0 distinct colors - actually this would be 1, but depends on the setup)

< Query 6 6 2 1 3 5 8
(You query with 6 chameleons)

> 2
(Judge responds: 2 distinct colors)

< Query 8 8 1 6 4 5 7 3 2
(You query with all 8 chameleons)

> 4
(Judge responds: 4 distinct colors)

< Answer 1 5
(You report chameleons 1 and 5 have the same color)

< Answer 2 8
(You report chameleons 2 and 8 have the same color)

< Answer 3 7
(You report chameleons 3 and 7 have the same color)

< Answer 4 6
(You report chameleons 4 and 6 have the same color)

(After N=4 correct answers, the judge calculates your score based on query count)

Note: ">" indicates output from the judge, "<" indicates your program's output.

Sample Implementation Template

Here is a template showing the interaction structure:

C++:
```cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int N;
    cin >> N;  // Read N from judge

    // Example query
    cout << "Query 3 1 2 3" << endl;  // endl flushes automatically
    int result;
    cin >> result;  // Read query result

    // More queries...

    // Submit answers (exactly N times)
    cout << "Answer 1 5" << endl;
    cout << "Answer 2 8" << endl;
    // ... N answers total

    return 0;
}
```

Python:
```python
import sys

N = int(input())  # Read N from judge

# Example query
print("Query 3 1 2 3")
sys.stdout.flush()  # Must flush!
result = int(input())  # Read query result

# More queries...

# Submit answers (exactly N times)
print("Answer 1 5")
print("Answer 2 8")
# ... N answers total
```

Error Conditions (Wrong Answer)

Your program will receive Wrong Answer if:
- Query count exceeds 20,000
- Query format is invalid (e.g., duplicate chameleons, IDs out of range)
- Answer count is not exactly N
- Any answer is incorrect (the two chameleons don't have the same color)
- Duplicate answers for the same pair
- Invalid command (not "Query" or "Answer")

# Set the problem type to interactive
type: interactive

# Specify the interactor source file
interactor: interactor.cc

# Time and memory limits still apply to the contestant's solution
time: 1s
memory: 256m

# The subtasks section works the same way
subtasks:
  - score: 100
    n_cases: 3 # Looks for 1.in, 2.in, ... 10.in in fulldata/


Sequence Transformation

Problem Description:
You are given two valid parenthesis sequences s1 and s2, both of length 2n. Your goal is to transform s1 into s2 using the minimum number of operations.

Available Operations:
- Op 1: Transform p(((A)B)C)q into p((A)B)(C)q
- Op 2: Transform p((A)(B)C)q into p((A)B)(C)q
- Op 3: Transform p(A)((B)C)q into p((A)B)(C)q
- Op 4: Transform p(A)(B)(C)q into p((A)B)(C)q

Where A, B, C are valid parenthesis sequences (possibly empty), and p, q are arbitrary sequences.

Special Operations (Each can be used at most 2 times per case):
- Op 5: Insert a pair of empty parentheses "()" at any position (max 2 times).
- Op 6: Remove a pair of empty parentheses "()" from any position (max 2 times).

Input Format:
- First line: an integer n (1 <= n <= 100,000)
- Second line: a string s1 of length 2n
- Third line: a string s2 of length 2n

Output Format:
- First line: an integer Q (the number of operations, must not exceed 3n)
- Next Q lines: each line contains two integers op and x
  - op: operation number (1-6)
  - x: position where the operation is applied

Position definition:
- For operations 1-4: x is the starting position of the leftmost '(' in the pattern
- For operations 5-6: x is the position to insert/remove "()"
- All positions are 0-indexed

Example:
Input:
3
(())()
((()))

Output:
3
5 6
4 0
6 6

Explanation:
Initial: (())()
After Op 5 at position 6: (())()()
After Op 4 at position 0: ((()))()
After Op 6 at position 6: ((()))

Scoring:
This problem is graded based on the number of operations Q:
- If Q <= 1.9n, you receive full score (1.0).
- If Q >= 3n, you receive 0 score.
- Otherwise, Score = (3n - Q) / (1.1n), clamped to [0, 1]

Constraints:
- 1 <= n <= 100,000
- Total operations must not exceed 3n.
- Op 5 can be used at most 2 times.
- Op 6 can be used at most 2 times.
- Both s1 and s2 are valid parenthesis sequences.

# Set the problem type to standard
type: default

# Specify the checker source file
checker: chk.cc

# Time and memory limits
time: 2s
memory: 256m

# The subtasks section
subtasks:
  - score: 100
    n_cases: 3 # Looks for 1.in/1.ans, 2.in/2.ans, ... 10.in/10.ans in testdata/


Efficient Sorting

Description

You are given a permutation S of N distinct integers from 0 to N-1. Your task is to sort the permutation into increasing order (i.e., S[i] = i for all 0 <= i < N) while playing a game against a character named Jerry.

The game proceeds in a sequence of rounds. You must decide in advance the total number of rounds, R, you wish to play. Jerry has a predetermined sequence of M planned swaps. In each round k (where 0 <= k < R):

1. Jerry's Move: Jerry performs his k-th planned swap on the array S.
2. Your Move: You choose two indices u_k and v_k (0 <= u_k, v_k < N) and swap the elements S[u_k] and S[v_k].

After the R rounds are completed, the array S must be sorted. If the array becomes sorted before the R-th round, you must still complete the remaining rounds (you may perform dummy swaps, such as swapping an index with itself).

We define the "Energy Cost" of a single swap (u, v) as the distance between the indices: |u - v|.

Your objective is to minimize the "Total Efficiency Value" (V), defined as:
V = R * (Sum of |u_k - v_k| for all k from 0 to R-1)

Input Format

The first line contains an integer N, the length of the permutation.
The second line contains N space-separated integers S_0, S_1, ..., S_{N-1}, representing the initial permutation.
The third line contains an integer M, the number Jerry's planned swaps.
The following M lines each contain two space-separated integers X_j and Y_j, representing the indices Jerry intends to swap in round j (for 0 <= j < M).

Output Format

The first line of output should contain a single integer R, the number of rounds you choose to play.
The following R lines should each contain two space-separated integers u_k and v_k, representing your swap in round k.
The last line of output should contain a single integer V, the Total Efficiency Value.

The value of R must satisfy 0 <= R <= M. After the completion of all R rounds (including Jerry's moves and your moves), the array S must be sorted.

Scoring

Your score is calculated based on the Total Efficiency Value V.

The scoring function is defined as follows:
- If V <= 10,000,000,000,000 (10^13), you receive 100 points.
- If V >= 3,300,000,000,000,000 (3.3×10^15), you receive 0 points.
- Otherwise, your score is calculated linearly:
  Score = 100 * (3.3×10^15 - V) / (3.3×10^15 - 10^13)

Constraints

- 1 <= N <= 200,000
- 1 <= M <= 600,000
- 0 <= S_i < N, all S_i are distinct.
- 0 <= X_j, Y_j < N
- It is guaranteed that it is possible to sort the array within M rounds.

Example

Input:
5
4 3 2 1 0
6
0 1
1 2
2 3
3 4
0 1
1 2

Output:
3
0 4
1 3
3 4
21

Explanation:
Initial sequence: [4, 3, 2, 1, 0]

Round 0:
- Jerry swaps indices (0, 1). Sequence becomes: [3, 4, 2, 1, 0]
- You swap indices (0, 4). Cost |0-4| = 4. Sequence becomes: [0, 4, 2, 1, 3]

Round 1:
- Jerry swaps indices (1, 2). Sequence becomes: [0, 2, 4, 1, 3]
- You swap indices (1, 3). Cost |1-3| = 2. Sequence becomes: [0, 1, 4, 2, 3]

Round 2:
- Jerry swaps indices (2, 3). Sequence becomes: [0, 1, 2, 4, 3]
- You swap indices (3, 4). Cost |3-4| = 1. Sequence becomes: [0, 1, 2, 3, 4]

The array is now sorted.
Total cost sum = 4 + 2 + 1 = 7.
Total Efficiency Value V = 3 * 7 = 21.

type: default
checker: chk.cc

# Time and memory limits still apply to the contestant's solution
time: 10s
memory: 256m

# The subtasks section works the same way
subtasks:
- score: 100
  n_cases: 3


Hidden Weights

Description

This is an interactive problem.

You are given a positive integer h. Let n = 2^h - 1.
There is a perfect binary tree G with n nodes, numbered 1 to n. The root of the tree is node 1. For any node u (2 <= u <= n), its parent is floor(u / 2).

The interactor maintains two hidden arrays:

1. A permutation p of length n, containing integers from 1 to n.
2. A weight array f of length n, where each element f_v corresponds to the weight of tree node v. All weights are non-negative integers not exceeding 10^9.

Your task is to determine the sum of all weights in the tree.

Interaction

First, your program should read a single integer h (2 <= h <= 18) from standard input.
Then, you may ask queries to the interactor. To make a query, print a line in the following format:

? u d

where u is an integer index (1 <= u <= n) and d is a distance (1 <= d <= 10^9).

The interactor will respond with a single integer: the sum of weights f_v for all nodes v in the tree such that the distance between node p_u and node v is exactly d.
Formally, the interactor returns the sum of f_v for all v where dist(p_u, v) = d.
If no such nodes v exist, the interactor returns 0.

* p_u denotes the u-th element of the hidden permutation p.
* dist(x, y) is the number of edges on the simple path between node x and node y in the tree.

Once you have determined the total sum of weights, output the answer in the following format:

! S

where S is the calculated sum. After outputting the answer, your program must terminate immediately.

Constraints

* 2 <= h <= 18
* n = 2^h - 1
* 0 <= f_v <= 10^9
* The interactor is not adaptive (p and f are fixed at the start).
* 1 <= d <= 10^9 (Note: d must be at least 1).

Scoring

Your score depends on Q, the number of queries you perform.
Let L = 3 * n / 4 (integer division) and R = (13 * n + 21) / 8 (integer division).

* If Q <= L, you receive 100 points.
* If Q >= R, you receive 0 points.
* Otherwise, your score is calculated linearly:
Score = floor(100 * (R - Q) / (R - L))

Technical Note

Remember to flush the output buffer after every query and the final answer.

* C++: cout << endl; or fflush(stdout);
* Python: print(..., flush=True)
* Java: System.out.flush();

Example

Input:
2
11
59
11

Output:
? 1 1
? 2 1
? 3 1
! 70

Explanation of Example:
h = 2, so n = 3. The tree has nodes 1 (root), 2 (left child), 3 (right child).
Hidden permutation p = [2, 1, 3].
Hidden weights f = [11, 45, 14] (f_1=11, f_2=45, f_3=14). Total sum is 70.

Query 1: "? 1 1"
u=1. Center is p_1 = 2.
Nodes at distance 1 from node 2 are {1}. (Node 3 is at distance 2).
Response: f_1 = 11.

Query 2: "? 2 1"
u=2. Center is p_2 = 1.
Nodes at distance 1 from node 1 are {2, 3}.
Response: f_2 + f_3 = 45 + 14 = 59.

Query 3: "? 3 1"
u=3. Center is p_3 = 3.
Nodes at distance 1 from node 3 are {1}. (Node 2 is at distance 2).
Response: f_1 = 11.

Calculation:
From Query 2, we know the sum of weights of children (nodes 2 and 3) is 59.
From Query 1 (or 3), we know the weight of the root (node 1) is 11.
Total Sum = 59 + 11 = 70.

type: interactive
interactor: interactor.cc

# Time and memory limits still apply to the contestant's solution
time: 10s
memory: 512m

# The subtasks section works the same way
subtasks:
- score: 100
  n_cases: 3


# Military Exercise: Fighter Scheduling and Base Strikes (Blue Side)

You are the **blue side** in a simplified military exercise on a 2D grid.

The map is an \(n \times m\) grid (0-indexed coordinates):

- `#` : red base (enemy)
- `*` : blue base (friendly)
- `.` : neutral cell

Both sides have bases. Blue controls a set of fighters and must plan actions to destroy red bases and maximize score.

This is a **planning / simulation** task: your program reads the input once and outputs a sequence of per-frame commands. A custom checker simulates the world and computes your score.

---

## Rules

### Fighters

There are \(k\) blue fighters, indexed \(0..k-1\). Each fighter has:

- Initial position \((x,y)\) (guaranteed to be on a blue base)
- Fuel tank capacity `G` (max fuel carried)
- Missile capacity `C` (max missiles carried)

Initial fuel and missiles are both **0**.

### Movement

- In one frame, a fighter may move by **1 cell** in one of 4 directions:
  - `0`: up, `1`: down, `2`: left, `3`: right
- A **successful move consumes 1 unit of fuel**.
- A fighter cannot leave the grid.
- A fighter **must not enter a red base cell that is not yet destroyed**.

If a fighter does not successfully move in a frame, it is considered "landed" for that frame (no fuel consumption).

### Refueling / Reloading (only on blue bases)

If a fighter is currently on a **blue base** cell, it can:

- `fuel`: transfer fuel from the base to the fighter (up to remaining base supply and tank capacity)
- `missile`: transfer missiles from the base to the fighter (up to remaining base supply and missile capacity)

Refueling/reloading time is ignored; multiple such commands in a frame are allowed (subject to supplies/capacity).

### Attacking

- A fighter may attack in one of 4 directions (`0..3`) with range **1 cell** (adjacent).
- The target cell must contain a **not-yet-destroyed red base**.
- `attack <id> <dir> <count>` consumes exactly `count` missiles from the fighter.
- Each red base has an integer defense `d`. When cumulative missiles received reaches `d`, the base is destroyed.

### Scoring

Each red base has a military value `v`. When a red base is **destroyed**, you gain **+v** points (only once per base).

Your goal is to **maximize the total score** after up to **15000 frames**.

Invalid commands are ignored (the simulation continues).

---

## Input Format

### Map

- Line 1: `n m` \((1 \le n,m \le 200)\)
- Next `n` lines: `m` characters each, describing the grid.

### Bases

Blue bases first, then red bases.

For each side:

- Line: integer `N` = number of bases
- For each base:
  - Line: `x y` (0-indexed)
  - Line: `g c d v`
    - `g`: fuel supply
    - `c`: missile supply
    - `d`: defense (missiles needed to destroy)
    - `v`: military value

### Fighters

- Line: integer `k` \((1 \le k \le 10)\)
- Next `k` lines: `x y G C` for fighter `id = i-1`

---

## Output Format

For each frame, output **zero or more** command lines, then a line:

```
OK
```

Commands:

- `move <id> <dir>`
- `attack <id> <dir> <count>`
- `fuel <id> <count>`
- `missile <id> <count>`

There are at most **15000 frames**. Your output may end early (remaining frames are treated as doing nothing).

---

## Sample Input

See `testdata/1.in`.

type: default
checker: chk.cc
checker_type: testlib

# Time and memory limits apply to the contestant's solution program.
time: 5s
memory: 512m

subtasks:
  - score: 100
    n_cases: 3


Super Dango Maker

Description

This is an interactive problem.

JOI-kun is a professional confectioner making dangos (Japanese dumplings). There are N different colors of dangos, numbered from 1 to N.

JOI-kun has M dangos of each color. Therefore, there are N * M dangos in total. These dangos are uniquely indexed from 1 to N * M. The color of each specific dango is hidden from you.

A "beautiful dango stick" consists of exactly N dangos skewered together, such that every color from 1 to N appears exactly once on the stick.

Your task is to partition all N * M dangos into M disjoint sets, where each set constitutes a valid beautiful dango stick.

You have access to a "dango checker". You can provide the checker with a subset of dango indices, and it will return the maximum number of beautiful dango sticks that can be formed simultaneously using only the dangos in that subset.

Interaction

First, your program should read two integers N and M from standard input.
- N: The number of colors.
- M: The number of dangos of each color.

Then, you may perform queries to the interactor. To make a query, output a line in the following format:

? k i_1 i_2 ... i_k

- k is the size of the subset you are querying.
- i_1, i_2, ..., i_k are the distinct indices of the dangos in the subset (1 <= i_j <= N * M).

The interactor will respond with a single integer: the maximum number of beautiful dango sticks that can be made using the provided subset of dangos.

Once you have identified a valid set of N dangos that form a beautiful stick, you must output it. To report a stick, output a line in the following format:

! e_1 e_2 ... e_N

- e_1, ..., e_N are the distinct indices of the dangos forming one stick.

You must perform this output action exactly M times (once for each stick). The M sets you output must be disjoint (i.e., every dango index from 1 to N * M must appear in exactly one Answer).

After outputting the M-th stick, your program must terminate immediately.

Constraints

- 1 <= N <= 400
- 1 <= M <= 25
- The hidden colors are fixed in advance (non-adaptive).
- It is guaranteed that a valid solution exists.

Scoring

Your score is determined by Q, the total number of "?" queries performed. The "!" outputs do not count toward the query limit.

Let L = N * M (the total number of dangos).
Let Limit = 5 * N * M.

- If Q <= L, you receive 100 points.
- If Q >= Limit, you receive 0 points.
- Otherwise, your score is calculated linearly:
  Score = floor(100 * (Limit - Q) / (Limit - L))

Technical Note

Remember to flush the output buffer after every query and answer.
- C++: cout << endl; or fflush(stdout);
- Python: print(..., flush=True)
- Java: System.out.flush();

Example

Input:
3 2
1
0
1
2

Output:
? 4 4 2 1 3
? 3 3 4 5
? 3 2 6 5
? 6 6 5 4 3 2 1
! 1 6 5
! 2 3 4

Explanation of Example:
N=3, M=2. Total dangos = 6.
Suppose the hidden colors are:
Index 1: Color 3
Index 2: Color 3
Index 3: Color 1
Index 4: Color 2
Index 5: Color 1
Index 6: Color 2

Query 1: "? 4 4 2 1 3" asks about indices {1, 2, 3, 4}.
Colors present: {3, 3, 1, 2}.
We can form at most 1 stick (using indices 1, 3, 4 or 2, 3, 4).
Response: 1.

Query 2: "? 3 3 4 5" asks about indices {3, 4, 5}.
Colors present: {1, 2, 1}.
We cannot form any stick because color 3 is missing.
Response: 0.

Query 3: "? 3 2 6 5" asks about indices {2, 5, 6}.
Colors present: {3, 1, 2}.
We can form 1 stick.
Response: 1.

Query 4: "? 6 6 5 4 3 2 1" asks about all indices.
We can form 2 sticks.
Response: 2.

Output 1: "! 1 6 5". Indices {1, 5, 6} have colors {3, 1, 2}. This is valid.
Output 2: "! 2 3 4". Indices {2, 3, 4} have colors {3, 1, 2}. This is valid.
Program terminates.

type: interactive
interactor: interactor.cc

# Time and memory limits still apply to the contestant's solution
time: 10s
memory: 256m

# The subtasks section works the same way
subtasks:
- score: 100
  n_cases: 3


Problem C. A+B Problem
Input file: standard input
Output file: standard output
Time limit: 2 seconds
Memory limit: 1024 mebibytes

In the era of constructives and ad-hocs, what could be more sacrilegious than combining two query problems
into one?

KOI City consists of N intersections and N − 1 two-way roads. You can travel between two different
intersections using only the given roads. In other words, the city’s road network forms a tree structure.
Roads are on a two-dimensional plane, and two roads do not intersect at locations other than the endpoints.
Each road has an non-negative integer weight. This weight represents the time it takes to use the road.

KOI City was a small town until a few decades ago but began to expand rapidly as people arrived. In the
midst of rapid expansion, the mayor had numbered the intersections between 1 and N for administrative
convenience. The number system satisfies the following properties.

• Intersection 1 is the center of the city and is incident to at least 2 roads.

• The numbers assigned to intersections form one of the pre-orders of the tree rooted at intersection 1:
for any subtree, the number of its root is the least number in that subtree.

• For each intersection, consider the lowest-numbered intersection among all adjacent (directly
connected by road) intersections. When you list all adjacent intersections in a counterclockwise
order starting from this intersection, the numbers go in increasing order.

With a large influx of people to KOI City, the traffic congestion problem has intensified. To solve this
problem, the mayor connected the outermost cities with the outer ring road. Let {v1, v2, . . . , vk} be the
increasing sequence of numbers of all the intersections incident to exactly one road. For each 1 ≤ i ≤ k,
the mayor builds a two-way road between intersection vi and intersection v(i mod k)+1. The weight of each
road is a nonnegative integer wi. Due to the nature of the numbering system, you can observe that the
outer ring road can be added in a two-dimensional plane in a way such that two roads do not intersect at
any location except at the endpoint.

However, resolving traffic congestion only reduces commute times, making it easier for capitalists to
exploit workers. Workers would not fall for the capitalists’ disgusting plot — they want to go back to the
good old days when they could apply heavy-light and centroid decomposition in KOI City! The workers
successfully carried out the socialist revolution and overthrew the capitalist regime. Now they want to
rebuild the structure of the existing KOI city by creating a new tree, which satisfies the following:

• Let K be the number of vertices in the new tree; K ≤ 4N should hold. From now on, we will label
vertices of the new tree as 1, 2, . . . ,K.

• For each vertex i of the new tree, there is a corresponding set Xi which is a subset of {1, 2, . . . , N}.

• For all roads (u, v) in the KOI City (both tree and outer ring roads), there exists a set Xi where
{u, v} ⊆ Xi.

• For all 1 ≤ j ≤ N , let Sj be the set of vertices 1 ≤ i ≤ K such that j ∈ Xi. Then Sj must be
non-empty, and should be a revolutionary set on the new tree.

• For all 1 ≤ i ≤ K, it is true that |Xi| ≤ 4.

For a tree T and a set S which is a subset of vertices of T , the set S is revolutionary on T if for all
vertices u, v ∈ S it is connected under S. Two vertices (u, v) are connected under S if there exists a path
in T that only passes through the vertices in S.

For example, consider the following tree and the set S = {1, 2, 3, 4, 5, 6}.

In this case, (1, 2), (3, 5) and (4, 6) are connected under S, while (1, 6) and (2, 7) are not connected
under S.

Input
The first line contains the number of intersections N in the KOI City (4 ≤ N ≤ 100 000).

Each of the next N − 1 lines contains a single integer pi. This indicates that there is a two-way road
connecting intersection pi and intersection i+ 1 (1 ≤ pi ≤ i). Note that these are not outer ring roads.

Output
On the first line, print the number of vertices in the new tree K. Your answer should satisfy 1 ≤ K ≤ 4N .

Then print K lines. On i-th of these lines, print |Xi|+1 space-separated integers. The first integer should
be the size of set Xi. The next |Xi| integers should be elements of Xi in any order.

In each of the next K − 1 lines, print two space-separated integers a and b, denoting that there exists an
edge connecting a and b in the new tree.

It can be proved that the answer always exists.

Example
standard input standard output

4
1
1
1

1
4 1 2 3 4

type: default

time: 2s
memory: 512m

checker: checker.cpp
cheker_type: testlib
subtasks:
  - score: 100
    n_cases: 3


# A=B

**Input file:** standard input
**Output file:** standard output
**Time limit:** 1 second
**Memory limit:** 512 megabytes

Marisa has learned an interesting language called **A=B**. She finds that this language has the advantages of simple syntax, easy to learn and convenient to code.

Here is the user manual of A=B:

*(Note that it may differ from the original game “A=B”. So please read the statement carefully.)*

---

## Instruction set

A=B’s instruction set includes:

1. `string1=string2`
   Find the leftmost occurrence of `string1` in the string and replace it with `string2`.

2. `string1=(return)string2`
   If `string1` is found, replace the entire string with `string2` and end the program immediately.

---

## Program structure

- An A=B program consists of several lines of instructions.
- Each line must include exactly one equal sign (`=`).
- Following characters are reserved: `=`, `(`, `)`.

---

## Execution order

1. Read the input string.
2. Starting from the topmost line, find the first line that can be executed.
3. If found, execute that line and go to step 2.
4. If none is found, return the current string as output.

---

Marisa once introduced A=B to Alice. However, “You called this a programming language? You can’t even write a program that can check if string *t* is a substring of string *s*!” said Alice.

Now Marisa comes to you for help. She wants you to design an A=B program for this problem and show A=B’s efficiency.

---

## Requirements

Your program needs to meet the following requirements:

- Read the input string (the input format is `sSt`. `S` is the separator. `s` and `t` are two non-empty strings consisting of characters `a`, `b`, `c`).
- If `t` is a substring of `s`, the program should return **1** as output, else return **0** as output.
- The character set that your program can use is `{a–z, A–Z, 0–9, =, (, )}`.
  - Remember: `=`, `(`, `)` are reserved characters in A=B and you can’t use them in `string1` or `string2`.
- In the instruction format, the length of `string1` and `string2` should be at most 3.
- Suppose the length of the input string is `L`, then:
  - The number of instruction executions can’t exceed `max(2L^2, 50)`.
  - The length of the string during execution can’t exceed `2L + 10`.
- The number of instructions in your A=B program can’t exceed **100**.

---

## Input

Input an integer `Tid` (`0 ≤ Tid ≤ 2×10^9`). It is used for generating test sets and may be no use to you.

---

## Output

Output your A=B program containing several lines of instructions.

The number of tests will not exceed 20. In each test, the checker will use `Tid` in the input file to generate several lines of input strings and their corresponding answers.
Your A=B program is considered correct **iff** for each input string in all tests, your A=B program gives the correct output.

It’s guaranteed that for each input string in all tests, the length `L` satisfies `3 ≤ L ≤ 1000`.

---

## Examples

### Example 1
**Input**
```

114514

```

**Output**
```

514=(return)1
=514

```

---

### Example 2
**Input**
```

1919810

```

**Output**
```

S=Sakuya
=(return)0

```

---

### Example 3
**Input**
```

caba

```

**Output**
```

aabc

```

**Input**
```

cbacab

```

**Output**
```

aabbcc

```

**Program**
```

ba=ab
ca=ac
cb=bc

```

---

### Example 4
**Input**
```

bababb

```

**Output**
```

b

```

**Input**
```

aababbaa

```

**Output**
```

a

```

**Program**
```

ba=ab
ab=
bb=b
aa=a

```

---

### Example 5
**Input**
```

abc

```

**Output**
```

true

```

**Input**
```

cabc

```

**Output**
```

false

```

**Input**
```

ca

```

**Output**
```

false

```

**Program**
```

b=a
c=a
aaaa=(return)false
aaa=(return)true
=(return)false

```

---

### Example 6
**Input**
```

10111+111

```

**Output**
```

11110

```

**Input**
```

101+10110

```

**Output**
```

11011

```

**Program**
```

A0=0A
A1=1A
B0=0B
B1=1B
0A=a
0B=b
1A=b
1B=ca
A=a
B=b
ac=b
bc=ca
0+=+A
1+=+B
+=
0c=1
1c=c0
c=1
a=0
b=1

```

---

## Note

- The first and second examples show how you should submit your answer.
- Examples 3–6 provide sample problems and their corresponding A=B programs to help you get familiar with the A=B language. Not all of them satisfy the problem’s constraints.

type: default

time: 2s
memory: 512m

checker: check.cpp
cheker_type: testlib
subtasks:
  - score: 100
    n_cases: 3


Time limit: 1 seconds
Memory limit: 512 megabytes
Bobo has an n×n symmetric matrix C consisting of zeros and ones. For a permutation p_1, ..., p_n of 1, ..., n, let c_i=(C_{p_i, p_{i+1}} for 1 ≤ i < n, C_{p_n, p_1} for i = n).
The permutation p is almost monochromatic if and only if the number of indices i (1 ≤ i < n) where c_i ̸= c_{i+1} is at most one.
Find an almost monochromatic permutation p_1, ... p_n for the given matrix C.

Input
The input consists of several test cases terminated by end-of-file. For each test case,
The first line contains an integer n.
For the following n lines, the i-th line contains n integers C_{i,1}, ..., C_{i,n}.
 •3≤n≤2000
 •C_{i,j} ∈ {0,1} for each1 ≤ i,j ≤ n
 •C_{i,j} = C_{j,i} for each1 ≤ i,j ≤ n
 •C_{i,i} = 0 for each 1 ≤ i ≤ n
 •In each input, the sum of n does not exceed 2000.

Output
For each test case, if there exists an almost monochromatic permutation, out put n integers p_1, ..., p_n which denote the permutation. Otherwise, output -1.
If there are multiple almost monochromatic permutations, you need to minimize the lexicographical order. Basically, set S = n * p_1 + (n - 1) * p_2 + ... + 1 * p_n, your score is inversely linear related to S.

SampleInput
3
001
000
100
4
0000
0000
0000
0000
SampleOutput
3 1 2
2 4 3 1

Note
For the first test case, c1 = C_{3,1} = 1, c2 = C_{1,2} = 0, c3 = C_{2,3} = 0. Only when i=1, c_i ̸= c_{i+1}.Therefore, the permutation 3,1,2 is an almost monochromatic permutation

type: default
time: 1s
memory: 512m
# A custom checker is required for the special scoring.
checker: chk.cc
subtasks:
  - score: 100
    n_cases: 3


Time limit: 2 seconds
Memory limit: 512 megabytes
This is an interactive problem, where your program and the judge interact via standard input and output.
In the kingdom of Duloc, Lord Farquaad is developing a network of watchtowers to monitor every corner of his land. He has a map of towers and the roads that connect them, forming an undirected simple graph G=(V,E), where each tower is a vertex and each road is an edge between two towers. However, Farquaad is worried that some parts of Duloc might be isolated, making it impossible to reach every tower from any other.
To ensure full connectivity, he tasks you with verifying whether his network is connected. However, there’s a catch: you’re only allowed limited access to information about the graph.
You can query the network to investigate its connectivity. A query allows you to select a subset of towers S and receive a count of the towers not in S that have direct roads connecting them to at least one tower in S. More precisely, query(S) = |N(S) \ S|, where S ⊆ V and N(S) = {x | ∃y ∈ S such that (x,y) ∈ E} .
Your goal is to use these queries efficiently to determine if the network is connected.
Can you help Lord Farquaad confirm the security of his kingdom by verifying that every tower is reachable from any other in Duloc’s network?

Input
First input an integer T (T <= 5), representing the number of testcases.
For each testcase:
Interaction starts by reading an integer the number of vertices.
Then you can make queries of the type "? s" (without quotes) where s is a binary string of length n such that character s_i is 1 if node i ∈ S and 0 otherwise. After the query, read an integer, which is the answer to your query.
After printing a query do not forget to output end of line and flush the output. The interactor is nonadaptive. The graph does not change during the interaction.

Constraints
1 <= |V| <= 200.
You are allowed to use at most 3500 queries for each testcase. Your score is inversely linear related to the number of queries.

Output
When you find if G is connected or disconnected, print it in the format "! x" (without quotes), where x is 1 if G is connected and 0 otherwise.

Note
In the following interaction, T = 1, |V| = 4, G = (V,E), V = {1,2,3,4} , E = {(1,2), (2,3), (3,4), (2,4)} .
Input|Output|Description
  1  |      | 1 testcase.
  4  |      | |V| is given.
     |? 1100| Ask a query for subset {1,2}.
  2  |      | The judge responds with 2.
     |? 0010| Ask a query for subset {3}.
  2  |      | The judge responds with 2.
     |? 1001| Ask a query for subset {1,4}.
  2  |      | The judge responds with 2.
     |! 1   | The algorithm detected that G is connected.
Here is another example, |V| = 2, G = (V,E), V = {1,2} , E = Φ.
Input|Output|Description
  2  |      | |V| is given.
     |? 10  | Ask a query for subset {1}.
  0  |      | The judge responds with 0.
     |? 11  | Ask a query for subset {1,2}.
  0  |      | The judge responds with 0.
     |! 0   | The algorithm detected that G is disconnected.

type: interactive
time: 2s
memory: 512m
# A custom checker is required for the special scoring.
checker: interactor.cc
subtasks:
  - score: 100
    n_cases: 3


OgreSort

You need to sort a permutation v of length n. All elements of the permutation are indexed from 1 to n.
The only permitted type of move allows you to take an element from some position x and insert it at
another position y, shifting all elements in between by one. The cost of such a move is y.
Formally, a move takes an element valued t from position x, “freeing” the index x. We then shift the
remaining elements in v, such that the “free” position becomes y. We then put t in the free position at
index y.
For example, if we have a permutation [4, 3, 2, 1], some of the possible moves:
• x = 2, y = 4, the resulting permutation is [4, 2, 1, 3], the cost of the move is 4.
• x = 2, y = 1, the resulting permutation is [3, 4, 2, 1], the cost of the move is 1.
The final cost is computed as (total cost + 1) * (number of moves + 1). You need to minimize the final cost.

Input
The first line contains an integer n — the length of the permutation.
The second line contains n integers v1, v2, . . . , vn — the values of the permutation.

Constraints
1 <= n <= 3 * 10^5
1 <= vi <= n,
vi != vj for all 1 <= i < j <= n.

Output
On the first line, print two numbers min_cost and len_moves — the minimum final cost needed to sort the
permutation and the length of the proposed sequence of moves respectively.
The next len_moves lines should each contain two integers xk, yk each, signifying that the k-th operation
should move the element from position xk to position yk (1 ≤ k ≤ len_moves, 1 <= xk, yk <= n).
If several possible sequences of moves exist, you can print any of them.

Scoring
You will be graded based on the final costs you give.
To be more specific, your answer will be compared to a solution best_answer.
Your final score will be calculated as the average of 100 * min(best_answer / your_answer, 1) across all cases.

Time limit: 2 seconds

Memoriy limit: 512 MB

Sample input:
5
2 4 1 3 5
Sample Output:
12 2
4 2
4 1
Sample Explanation:
The total cost is (2 + 1) = 3, and the number of moves is 2. Thus the final cost is (3 + 1) * (2 + 1) = 12.

type: default
time: 2s
memory: 512m
checker: chk.cc
subtasks:
  - score: 100
    n_cases: 3


# Problem

You are given an n by m grid. You want to place as many black points (cells) as possible so that no four of them form the four corners of an axis-parallel rectangle.

Formally, if you place black points at positions (r, c) with 1 ≤ r ≤ n and 1 ≤ c ≤ m, your set S of chosen positions must not contain four distinct pairs (r1, c1), (r1, c2), (r2, c1), (r2, c2) with r1 ≠ r2 and c1 ≠ c2.

## Input
A single line with two integers n and m (1 ≤ n, m and n · m ≤ 100000).

## Output
Print:
- The first line: an integer k — the number of black points you place (0 ≤ k ≤ n · m).
- The next k lines: two integers ri and ci each (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), denoting the coordinates of the i-th black point.

All listed pairs must be distinct. You may print the points in any order.

## Goal
Maximize k subject to the validity constraint (no axis-parallel rectangle formed by four chosen points).

## Scoring
Let k be the number of points you output, and let U(n, m) be the theoretical upper bound we use for this problem:
U(n, m) = floor(min(n · sqrt(m) + m, m · sqrt(n) + n, n · m)).

Your score for a test is:
score = 100 × min(k / U(n, m), 1).

- Achieving the upper bound U(n, m) yields a score of 100.
- Outputting 0 points yields a score of 0.
- Invalid outputs (out-of-range coordinates, duplicates, or violating the rectangle constraint) receive a score of 0 for that test.
Your final score is the average over all tests.

## Time limit
1 second

## Memory limit
512 MB

## Sample
Input
2 2

Output
3
1 1
1 2
2 1

(The sample illustrates the format and a valid solution; for a 2×2 grid, 3 is optimal under the given constraint.)

type: default
# The time limit is now 1 second.
time: 1s
memory: 512m
# A custom checker is required for the special scoring.
checker: chk.cc
subtasks:
  - score: 100
    n_cases: 3


Hacking the Project
Input ﬁle: standard input
Output ﬁle: standard output
Time limit: 1 second
Memory limit: 512 mebibytes
This is an interactive problem.
Lewis is one of the developers of the new programming language called DiverC. The main feature of the
program written in this language is that the code consists of pairwise distinct words. The compiler of
DiverC developed by Lewis is, of course, written in DiverC and consists ofN pairwise distinct words.
Lewis is using the DiverC online autoﬁll service. But Lewis has made one serious mistake: he forgot to
switch the “use my data for the improvement of the service database” function oﬀ. And Lewis was the
ﬁrst person who registered on this service, so now the service contains only the words from his compiler.
Hacker Fernando wants to know all the words Lewis used in the compiler. So he registered at the DiverC
online autoﬁll service (wisely switching the dangerous function oﬀ), and now, for each preﬁxS and integer
K entered by Fernando, the service returns, in lexicographic order, the ﬁrstK words from Lewis’s code
that begin with the preﬁxS. If there are onlyk < Kwords, the service gives out onlyk words (but the
service usage counter increases byK even in this case).
Fernando checked the scripts used for the online service and found that one user is limited with the total value ofK in all queries. He wants to determine allN words used by Lewis with several queries
such as the sum ofK in those queries is as less as possible.
Can you help him?
Interaction Protocol
In the beginning, your program shall read one integerT /emdash.cyr the number of the test cases to be processed
(1 ≤T ≤5).
At the beginning of each test case, the jury program tells one integerN /emdash.cyr the number of the words in
Lewis’s DiverC compiler (1 ≤N ≤1 000).
Your program can then make two types of requests:
• query S K /emdash.cyr getK (1 ≤ K ≤ N) lexicographically minimal words starting with preﬁx S
(1 ≤|S|≤ 10). If the dictionary contains onlyk such words, where k < K, the answer to the
query will containk words. The response to the query will be one line of the formkS1S2 . . . Sk,
where k is the number of the words (0 ≤k ≤K), and thenk words Si in lexicographic order follow.
• answer S1 S2 ...SN /emdash.cyr tell the full Lewis’s dictionary. After the wordanswer you shall print allN
words in an arbitrary order separated by spaces. There will be no response from the jury program
to this request, and your program must then continue with the next test case or exit if the current
test case was the last one.
The words in Lewis’s code are composed of lowercase English letters. The length of words is between 1
to 10 characters. All words in Lewis’s code are pairwise distinct.
The sum ofK for all queries of the ﬁrst type for each test should be as less as possible. Your score will be determined by the number of this value. If this value is smaller, you will get a higher score if your final answer is correct.
If value is greater than 4000, the solution will get 0 points.
Violating the interaction protocol or exceeding the limits for the sum ofK cause the “Wrong answer”
verdict.
Make sure you print the newline character after each query and ﬂush the output stream buﬀer (flush
languagecommand)aftereachrequest.Otherwise,thesolutionmaygettheidlenesslimitexceededverdict.
Note that the jury program isadaptive, i.e. the set of Lewis’s words may be generated at the runtime,
but the set is guaranteed to be consistent with the answers to previous queries.
Page 1 of 2Example
standard input standard output
1
4
1 aaa
2 aaa aba
1 cxyxy
0
1 czzzz
query a 1
query a 4
query c 1
query cy 1
query cz 1
answer aaa aba czzzz cxyxy
Page 2 of 2

type: interactive
time: 1s
memory: 512m
subtasks:
  - score: 100
    n_cases: 3
interactor: interactor.cc
checker_type: testlib


This is an interactive question.

time limit: 10 seconds (up to 5 seconds for interactive library)
Space limitations: 1GB (up to 64MB for interactive library)

Description
Hope City is a city built on a floating island. At the edge of the floating island, there are n lamp sockets evenly distributed, forming a ring shape. Each lamp holder is labeled with a number between 1 and n, and forms an arrangement of length n in a clockwise direction p1, p2,..., pn. You don't know this arrangement and hope to restore it through interaction with the system.

You can ask the system to switch the state of a set of lamp holders at a time (if it was not originally lit, it will be lit; if it was originally lit, it will be extinguished).

The system will maintain a set of currently lit lamp holders S (initially empty) internally. You cannot directly see the contents of the set, but you can obtain the following information through interaction:

You can submit a set of operations at once (i.e. a series of target IDs for wick input), and the system will process each of these operations one by one:

- If a lamp holder is not in S, it will be lit up after inserting the wick (add into S);
- If a lamp holder is already in S, it will be extinguished up after inserting the wick (remove it from S);
- After each operation, the system will record whether there is a pair of adjacent lamp holders on the ring in the current set S, and return the records of all operations together.
After you submit a set of operations at once and receive the returned records, S will not be cleared, but will continue to serve as the initial set for the next set of operations.

Input
One line, contains two integers, subtask, n, representing the subtask ID and the length of the loop;

Implementation Details
To ask a query, output one line. First output a number L followed by a space, then print a sequence of L integers ranging from 1 to n separated by a space.
After flushing your output, your program should read a sequence of L integers, indicating whether there are adjacent pairs in S after each operation.
Specifically, The system will maintain a set S, which is initially the result of the previous query (i.e. not reset), and sequentially scans each element u in this query:
If u is not in S when scanned, perform an operation to light up u so that u is in S; if u is in S when scanned, perform an operation to extinguish u so that u is not in S. Then report an integer indicating whether there are adjacent pairs in S after this operation(0: does not exist; 1: exist).

If you want to guess the permutation, output one line. First output -1 followed by a space, then print a permutation of n separated by a space, representing the arrangement of lamp holder numbers p1~pn. Since the ring has no starting point or direction, any cyclic shift of p1~pn or p1~pn is considered correct. After flushing your output, your program should exit immediately.

Note that the answer for each test case is pre-determined. That is, the interactor is not adaptive. Also note that your guess does not count as a query.

To flush your output, you can use:
fflush(stdout) (if you use printf) or cout.flush() (if you use cout) in C and C++.

Subtask
Subtask 1 (10 points): Ensure n=1000.
Subtask 2 (90 points): Ensure n=10 ^ 5.

For a testcase, if your interaction process is illegal or the returned answer is incorrect, you will directly receive 0 points.

Otherwise, record the total number of times you call query as t, and record the sum of the number of operations you perform each time when calling query as Q.

Your score ratio lambda will be calculated according to the following formula:
lambda=max (0, 1-0.1 (f (t/18)+f (Q/ (1.5 * 10^7)))
Where f (x)=min (max (log_2 (x), 0), 8)
Then, if the subtask where this testcase is located has a maximum score of S, then you will get lambda * S.

The total number of times you call query cannot exceed 10 ^ 7, and the sum of the number of operations you perform each time when calling 'query' cannot exceed 3 * 10 ^ 8.
To prevent unexpected behavior caused by a large vector, you also need to ensure that the number of operations in a single query call always does not exceed 10 ^ 7.

Interactive Example
Assuming n=4 and the arrangement of lamp holder is [2,4,1,3], the following is a valid interaction process:

Player Program | Interaction Library | Description
- | Call solve (4, 0) | Start the interaction process
Call query ([1, 2]) | Return [0, 0] | Found that the two lamp holders with numbers 1 and 2 are not adjacent on the ring
Call query ([1, 2]) | Return [0, 0] | extinguish 1,2
Call query ([1, 3]) | Return [0, 1] | Found that two lamp holders with numbers 1 and 3 are adjacent on the ring
Call query ([1, 3]) | Return [0, 0] | extinguish 1,3
Call query ([1, 4]) | Return [0, 1] | Found that two lamp holders with numbers 1,4 are adjacent on the ring
Call query ([1, 4]) | Return [0, 0] | extinguish 1,4
Call query ([2, 3]) | Return [0, 1] | Found that two lamp holders with numbers 2 and 3 are adjacent on the ring
Call query ([2, 3]) | Return [0, 0] | extinguish 2,3
Call query ([2, 4]) | Return [0, 1] | Found that two lamp holders with numbers 2 and 4 are adjacent on the ring
Call query ([2, 4]) | Return [0, 0] | extinguish 2,4
Call query ([3, 4]) | Return [0, 0] | Found that the two lamp holders with numbers 3 and 4 are not adjacent on the ring
Call query ([3, 4]) | Return [0, 0] | extinguish 3,4
Run ends and returns [1, 4, 2, 3] | Print interaction result to screen | Interaction ends, result is correct

type: interactive
time: 10s
memory: 1024m
# A custom checker is required for the special scoring.
interactor: interactor.cc
subtasks:
  - score: 100
    n_cases: 3


This is an interactive problem.

You are given a tree of n
 nodes with node 1
 as its root node.

There is a hidden mole in one of the nodes. To find its position, you can pick an integer x
 (1≤x≤n
) to make an inquiry to the jury. Next, the jury will return 1
 when the mole is in subtree x
. Otherwise, the judge will return 0
. If the judge returns 0
 and the mole is not in root node 1
, the mole will move to the parent node of the node it is currently on.

Use at most 160
 operations to find the current node where the mole is located. If the number of operations is more than 160, you will get zero grade. Otherwise, your grade will be determined by the sum of the depth of the nodes in your query (the same node in two different queries will be counted twice). The depth of a node is the distance from the node to the root and the depth of the root is 0.

Input
Each test contains multiple test cases. The first line contains the number of test cases t
 (1≤t≤100
). The description of the test cases follows.

Interaction
The first line of each test case contains one integer n
 (2≤n≤5000
).

The following n−1
 lines describe the edges of the tree. Each line contains two space-separated integers ui
 and vi
 (1≤ui,vi≤n
), indicating an edge between nodes ui
 and vi
.

It is guaranteed that the input data represents a tree.

The interactor in this task is not adaptive. In other words, the node where the mole is located at first is fixed in every test case and does not change during the interaction.

To ask a query, you need to pick a vertex x
 (1≤x≤n
) and print the line of the following form:

"? x"
After that, you receive:

0
 if the mole is not in subtree x
;
1
 if the mole is in subtree x
.
You can make at most 500
 queries of this form for each test case. Apart from this condition, you need to try to minimize the sum of the depth of the nodes in your query.

Next, if your program has found the current node where the mole is located, print the line of the following form:

"! x"
Note that this line is not considered a query and is not taken into account when counting the number of queries asked.

After this, proceed to the next test case.

If you make more than 160
 queries during an interaction, your program must terminate immediately, and you will receive the Wrong Answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.

After printing a query or the answer for a test case, do not forget to output the end of line and flush the output. Otherwise, you will get the verdict Idleness Limit Exceeded. To do this, use:

fflush(stdout) or cout.flush() in C++;
System.out.flush() in Java;
flush(output) in Pascal;
stdout.flush() in Python;
see the documentation for other languages.

Example
InputCopy
2
2
1 2

1

6
1 2
1 3
1 4
4 5
5 6

0

0

1
OutputCopy

? 2

! 2

? 2

? 6

? 4

! 4
Note
In the first test case, the mole is in node 2
 initially.

For the query "? 2", the jury returns 1
 because the mole is in subtree 2
. After this query, the mole does not move.

The answer 2
 is the current node where the mole is located, so the answer is considered correct.

In the second test case, the mole is in node 6
 initially.

For the query "? 2", the jury returns 0
 because the mole is not in subtree 2
. After this query, the mole moves from node 6
 to node 5
.

For the query "? 6", the jury returns 0
 because the mole is not in subtree 6
. After this query, the mole moves from node 5
 to node 4
.

For the query "? 4", the jury returns 1
 because the mole is in subtree 4
. After this query, the mole does not move.

The answer 4
 is the current node where the mole is located, so the answer is considered correct.

Please note that the example is only for understanding the statement, and the queries in the example do not guarantee to determine the unique position of the mole.

type: interactive
time: 4s
memory: 256m
subtasks:
  - score: 100
    n_cases: 3
interactor: interactor.cc
checker_type: testlib


Permutation (Modified Version)

Time Limit: 5 s
Memory Limit: 1024 MB

The Pharaohs use the relative movement and gravity of planets to accelerate their spaceships. Suppose a spaceship will pass by some planets with orbital speeds in order. For each planet, the Pharaohs' scientists can choose whether to accelerate the spaceship using this planet or not. To save energy, after accelerating by a planet with orbital speed p[i], the spaceship cannot be accelerated using any planet with orbital speed p[j] < p[i]. In other words, the chosen planets form an increasing subsequence of p.

The scientists have identified that there are exactly k different ways a set of planets can be chosen to accelerate the spaceship. They have lost their record of all the orbital speeds (even the value of n). However, they remember that p is a permutation of {0, 1, …, n−1}. Your task is to find one possible permutation of sufficiently small length.

Input
The first line contains an integer q (1 ≤ q ≤ 100), the number of spaceships.
The second line contains q integers k1, k2, …, kq (2 ≤ ki ≤ 10^18).

Output
For each ki, output two lines:
- The first line contains an integer n (the length of the permutation).
- The second line contains n integers: a valid permutation of {0, 1, …, n−1} having exactly ki increasing subsequences.

Scoring
Let m be the maximum permutation length you used across all queries.
Your score for the test file will be determined as follows:

m ≤ 90 → 100 points

90 < m < 2000 -> linear function

m >= 2000 -> 0

Example
Input
2
3 8

Output
2
1 0
3
0 1 2

Explanation
For k = 3, one valid permutation is [1, 0], which has exactly 3 increasing subsequences: [], [0], [1].
For k = 8, one valid permutation is [0, 1, 2], which has exactly 8 increasing subsequences: [], [0], [1], [2], [0, 1], [0, 2], [1, 2], [0, 1, 2].

type: default
time: 5s
memory: 1024m
subtasks:
  - score: 100
    n_cases: 3
checker: checker.cpp
checker_type: testlib


Language: C++ only

Time limit per test: 5 seconds
Memory limit per test: 1024 megabytes

This is an interactive problem.

There is a hidden array a containing all the numbers from 1 to n, and all of them appear twice except one (which only appears once).

You can ask queries in the following format, where S is a subset of {1,2,…,2n−1} and x is an integer in [1,n]:

? x |S| S1 S2 ... S|S|

The answer to this query is: does there exist i ∈ S such that a_i = x ?

Your task is to find the number appearing exactly once, using at most 5000 queries. You don’t need to find its position.

Note that the interactor is not adaptive, which means that the hidden array does not depend on the queries you make.

Input
Each test contains multiple test cases.
The first line contains the number of test cases t (1 ≤ t ≤ 20).

The description of the test cases follows.

The first line of each test case contains a single integer n (n = 300) — the maximum value in the hidden array.

Interaction
For each test case, first read a single integer. If the integer you read is -1, it means that the answer to the previous test case was wrong, and you should exit immediately.

You may ask up to 5000 queries in each test case.

To ask a query, print a line in the format described above.
As a response to the query, you will get:

1 if the answer is yes,

0 if the answer is no,

-1 if you made an invalid query. In this case you should exit immediately.

To output an answer, print:
! y
where y is the number that appears exactly once.
Printing the answer doesn’t count as a query.

If you ask too many queries, you ask a malformed query, or your answer is wrong, you will get -1.

After printing a query, do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded.
In C++, you can use:
fflush(stdout);
cout.flush();

Scoring

If you solve the problem with at most 500 queries, you get 100 points.

If you solve it with 5000 queries, you get 0 points.

For values in between, the score decreases linearly.

Example
Input
1
300
0

Explanation
In the first test case, n = 300, so the hidden array has length 2n − 1 = 599.

Contestant prints / Interactor replies
? 187 1 1
0
! 187

Query: does a1 = 187? → No.
We then output ! 187.
Fortunately, the answer is correct.

We have asked 1 query (printing the answer does not count as a query), which is less than the maximum allowed number of queries (5000).

# Set the problem type to interactive
type: interactive

# Specify the interactor source file
interactor: interactor.cpp

# Time and memory limits still apply to the contestant's solution
time: 5s
memory: 1024m

# The subtasks section works the same way
subtasks:
  - score: 100
    n_cases: 3 # Looks for 1.in, 2.in, ... 5.in


Hack!

This is an I/O interactive problem. I/O interaction refers to interactive problems, where the program communicates with a special judge during execution instead of producing all output at once. In these problems, the program sends queries (output) to the judge and must immediately read responses (input) before continuing. The solution must strictly follow the input-output protocol defined in the problem statement, because any extra output, missing flush, or incorrect format can cause a wrong answer. Unlike standard problems, interactive problems require careful handling of I/O, synchronization, and flushing to ensure smooth communication between the contestant’s code and the judge.

You know that unordered_set uses a hash table with n buckets, which are numbered from 0 to
n − 1. Unfortunately, you do not know the value of n and wish to recover it.
When you insert an integer x into the hash table, it is inserted to the (x mod n) -th bucket. If
there are b elements in this bucket prior to the insertion, this will cause b hash collisions to occur.

By giving k distinct integers x[0],x[1],…,x[k − 1] to the interactor, you can find out the total
number of hash collisions that had occurred while creating an unordered_set containing the
numbers. However, feeding this interactor k integers in one query will incur a cost of k.
For example, if n = 5, feeding the interactor with x = [2, 15, 7, 27, 8, 30] would cause 4 collisions in
total:

Operation       New  collisions Buckets
initially        −   [],[],[],[],[]
insert x[0] = 2  0   [],[],[2],[],[]
insert x[1] = 15 0   [15],[],[2],[],[]
insert x[2] = 7  1   [15],[],[2, 7],[],[]
insert x[3] = 27 2   [15],[],[2, 7, 27],[],[]
insert x[4] = 8  0   [15],[],[2, 7, 27],[8],[]
insert x[5] = 30 1   [15, 30],[],[2, 7, 27],[8],[]

Note that the interactor creates the hash table by inserting the elements in order into an initially empty unordered_set, and a new empty unordered_set will be created for each query. In other words, all queries are independent.

Your task is to find the number of buckets n (2<=n<=10^9) using total cost of at most 1 000 000. Total cost is the total length of your queries. You have to minimize total cost as much as possible. Your final score will be calculated as the average of 100 * clamp(log_50(10^6 / (your_total_cost - 9 * 10^4)), 0, 1) across all cases.

Input

There is no input in this problem.

Interaction

To ask a query, output one line. First output 0 followed by a space, then output an positive integer m, the number of elements in this query, then print a sequence of m integers ranging from 1 to 10^18 separated by a space. After flushing your output, your program should read a single integer x indicating the number of collisions created by inserting the elements in order to an unordered_set.

If you want to guess n, output one line. First output 1 followed by a space, then print the n you guess. After flushing your output, your program should exit immediately.

Note that the answer for each test case is pre-determined. That is, the interactor is not adaptive. Also note that your guess does not count as a query.

To flush your output, you can use:

    fflush(stdout) (if you use printf) or cout.flush() (if you use cout) in C and C++.

    System.out.flush() in Java.

    stdout.flush() in Python.

Note

Please note that if you receive a Time Limit Exceeded verdict, it is possible that your query is invalid or the number of queries exceeds the limit.

Constraints
- Time limit: 3 seconds
- Memory Limit: 1024 MB
- Let Q be the query cost you make.
  - If your program exceeds time limit, memory limit, or returns incorrect answer → score=0.
  - Otherwise, your score depends on Q:
    - score(Q) = 1000001 / (Q + 1)
    - In other words, a solution with Q <= 1000000 is awarded the full score.

Example input (you to interactor):
0 6 2 15 7 27 8 30

0 3 1 2 3

0 5 10 20 30 40 50

1 5

Example output (interactor to you):

4

0

10

# Set the problem type to interactive
type: interactive

# Specify the interactor source file
interactor: interactor.cpp

# Time and memory limits still apply to the contestant's solution
time: 3s
memory: 1024m

# The subtasks section works the same way
subtasks:
  - score: 100
    n_cases: 3 # Looks for 1.in, 2.in, ... 5.in


Problem: Matrix k-th Smallest (Interactive)

You are given an unknown n×n matrix a. You must find the k-th smallest value among all a[i][j].
You cannot read the matrix directly. Instead, you must interact with the judge using the protocol below.
The matrix satisfies:
for all i<=n and j<n: a{i,j}<=a{i,j+1}
for all i<n and j<=n: a{i,j}<=a{i+1,j}

- First you need to read the input n and k.
- Your program must write commands to stdout and read responses from stdin. Flush after every command.

Supported commands you may send:
1) QUERY x y
   - Asks for the value a[x][y].
   - Constraints: 1 ≤ x, y ≤ n.
   - The interactor replies with an integer v:
     v
     where v = a[x][y].

2) DONE ans
   - You announce your final answer.
   - The interactor will terminate after printing a single floating-point score to stdout.

Limits
- You may call QUERY at most 50000	times per test file.
- Any out-of-bounds query or exceeding the query limit results in score 0.0.
- n<=2000, a{i,j}<=10^18
- You need to use c++17
- Time limit: 5 seconds per test.
- Memory limit: 1024 MB.

Scoring
- Let used be the number of QUERY calls you made for the current test.
- Let correct be the true k-th smallest value among all 50000 entries.
- If your final ans equals correct, your score is:
    if used ≤ n: 1.0
    else if used ≥ n*n: 0.0
    else: (50000 - used) / (50000 - n)
  Otherwise, your score is 0.0.

# Set the problem type to interactive
type: interactive

# Specify the interactor source file
interactor: interactor.cc

# Time and memory limits still apply to the contestant's solution
time: 5s
memory: 1024m

# The subtasks section works the same way
subtasks:
  - score: 100
    n_cases: 3 # Looks for 1.in, 2.in, ... 5.in


Interactive RBS

This is an I/O interactive problem. I/O interaction refers to interactive problems, where the program communicates with a special judge during execution instead of producing all output at once. In these problems, the program sends queries (output) to the judge and must immediately read responses (input) before continuing. The solution must strictly follow the input-output protocol defined in the problem statement, because any extra output, missing flush, or incorrect format can cause a wrong answer. Unlike standard problems, interactive problems require careful handling of I/O, synchronization, and flushing to ensure smooth communication between the contestant’s code and the judge.

There is a hidden bracket sequence s of length n, where s only contains '(' and ')'. It is guaranteed that s contains at least one '(' and one ')'.

To find this bracket sequence, you can ask queries. Each query has the following form: you pick an integer k and arbitrary indices i_1,i_2,...,i_k (1<=k<=1000, 1<=i_1,i_2,...,i_k<=n). Note that the indices can be equal. Next, you receive an integer f(s_{i_1}s_{i_2}...s_{i_k}) calculated by the jury.

For a bracket sequence t, f(t) is the number of non-empty regular bracket substrings in t (the substrings must be contiguous). For example, f("()())")=3.

A bracket sequence is called regular if it can be constructed in the following way.

1. The empty sequence ∅ is regular.
2. If the bracket sequence A is regular, then (A) is also regular.
3. If the bracket sequences A and B are regular, then the concatenated sequence AB is also regular.

For example, the sequences "(())()", "()" are regular, while "(()" and "())(" are not.

Find the sequence s using no more than 200 queries. Specifically, your score will be (200 - q) / 200, where q is the number of queries.

The first line of each test case contains one integer n (2<=n<=1000). At this moment, the bracket sequence s is chosen. The interactor in this task is not adaptive. In other words, the bracket sequence s is fixed in every test case and does not change during the interaction.

To ask a query, you need to pick an integer k and arbitrary indices i_1,i_2,...,i_k (1<=k<=1000), 1<=i_1,i_2,...,i_k<=n) and print the line of the following form (without quotes):

"0 k i_1 i_2 ... i_k"

After that, you receive an integer f(s_{i_1}s_{i_2}...s_{i_k}).

You can ask at most 200 queries of this form.

Next, if your program has found the bracket sequence s, print a line with the following format (without quotes):

"1 s_1s_2...s_n"

Note that this line is not considered a query and is not taken into account when counting the number of queries asked.

If you ask more than 200 queries during an interaction, your program must terminate immediately, and you will receive the Wrong Answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.

After printing a query or the answer for a test case, do not forget to output the end of the line and flush the output. Otherwise, you will get the verdict Idleness Limit Exceeded. To do this, use:

fflush(stdout) or cout.flush() in C++;
System.out.flush() in Java;
flush(output) in Pascal;
stdout.flush() in Python;
see the documentation for other languages.

Example Input 1 (interactor to you):

3

0

1

1

Example Output 1 (you to interactor):

0 4 1 2 3 3

0 2 2 1

0 2 3 1

1 )((

Example Input 2 (interactor to you):

2

3

Example Output 2 (you to interactor):

0 4 1 2 1 2

1 ()

# Set the problem type to interactive
type: interactive

# Specify the interactor source file
interactor: interactor.cpp

# Time and memory limits still apply to the contestant's solution
time: 2s
memory: 256m

# The subtasks section works the same way
subtasks:
  - score: 100
    n_cases: 3 # Looks for 1.in, 2.in, ... 5.in


# Problem

Anton owns \(n\) umbrellas, each labeled with a distinct integer from \(1\) to \(n\). He wants to arrange some of them in a line to form a brilliant sequence of umbrellas (BSU).

A sequence of \(k\) umbrellas with numbers \(a_1, a_2, \ldots, a_k\) is a BSU if:

- \(a_i > a_{i-1}\) for all \(2 \le i \le k\);
- \(\gcd(a_i, a_{i-1}) > \gcd(a_{i-1}, a_{i-2})\) for all \(3 \le i \le k\).

Here, \(\gcd(x, y)\) denotes the greatest common divisor of integers \(x\) and \(y\).

## Input
A single line containing an integer \(n\) — the number of umbrellas \((1 \le n \le 10^{12})\).

## Output
Print two lines:

- The first line should contain an integer \(k\), the length of your BSU \((1 \le k \le 10^6)\).
- The second line should contain \(k\) integers \(a_1, a_2, \ldots, a_k\) \((1 \le a_i \le n)\), forming a valid BSU.

## Goal
Maximize the objective:
\[
V \;=\; \text{length}(\text{BSU}) \times \sum_{i=1}^{k} a_i \;=\; k \times \Big(\sum_{i=1}^{k} a_i\Big).
\]

## Scoring
We compare your objective value \(V_{\text{you}}\) with a fixed baseline heuristic’s value \(V_{\text{base}}\) on the same test. There is **no** best/optimal reference in scoring.

Your score for a test is:
\[
\text{score} \;=\; 100 \times \min\!\left(\frac{V_{\text{you}}}{1.05 \times V_{\text{base}}},\, 1\right).
\]

Thus, reaching \(1.05 \times V_{\text{base}}\) yields a score of 100. Your final score is the average over all tests. Invalid outputs (violating constraints) receive 0 for that test.

## Time limit
1 second

## Memory limit
512 MB

## Sample
**Input**
22
**Output**
5
1 2 4 8 16

(The sample only illustrates format and validity; it is not necessarily optimal for the new objective.)


Problem
You are given an integer n. Place n unit squares (side length 1) inside an axis-parallel square container of side length L so that:
- Every unit square lies entirely inside the container.
- Unit squares have no common interior points (touching edges/corners is allowed).
- Each unit square may be rotated by an arbitrary angle.

Your goal is to minimize L.

Input
A single integer n (1 ≤ n ≤ 100000).

Output
- First line: a real number L (the claimed container side length).
- Next n lines: three real numbers xi, yi, ai for i = 1..n:
  - (xi, yi) is the center of the i-th unit square.
  - ai is its rotation angle in degrees counterclockwise, 0 ≤ ai < 180.

All numbers must be finite reals. Any reasonable precision is allowed; at least 6 decimal places is recommended.

Validity
Your output is valid if and only if:
- Containment: Every point of every unit square lies inside [0, L] × [0, L].
- Non-overlap (interiors): The interiors of any two unit squares are disjoint. Touching along edges or at corners is allowed.
- Angles: 0 ≤ ai < 180 for all i.

The judge verifies geometry with epsilon = 1e-7:
- Containment: A square is accepted if its maximum outward violation beyond the container is ≤ 1e-7.
- Non-overlap: Two squares are accepted as interior-disjoint if the minimum signed distance between their boundaries is ≥ −1e-7.

Invalid submissions score 0 for that test.

Goal
Minimize L subject to the validity constraints.

Baseline
A simple baseline packs all squares unrotated (ai = 0) on the unit grid, with centers at (0.5 + x, 0.5 + y), using the smallest integer-sided container that fits all n. The baseline side length is
- L0(n) = ceil(sqrt(n)).

For example, for n = 11, the baseline uses L0 = 4.000000.

Scoring
Let L be your reported container side length (validated by the judge). Define:
- LB = sqrt(n)  (trivial area lower bound; no packing can have L < LB),
- L0 = ceil(sqrt(n))  (baseline side length),
- s = s(n)  (reference scale defined below; s satisfies LB ≤ s ≤ L0).

The score is computed as follows:
- If invalid: 0 points.
- If L ≥ L0: 1 points.
- If L = LB: 100 points.
- If LB < L ≤ s:
  - Let p2 = (s − L) / (s − LB) ∈ (0, 1].
  - Score = 95 + 5 × min(1.0, 1.1 × p2).
- If s < L < L0:
  - Let p1 = (L0 − L) / (L0 − s) ∈ (0, 1).
  - Score = 94 × min(1.0, 1.1 × p1) + 1.

This scheme:
- Gives 0 points at the baseline (L = L0).
- Reaches at least 95 points once you meet the reference s(n) (i.e., L ≤ s(n)).
- Reaches 100 points at the area bound (L = LB).
- Applies a +10% amplification to progress within each band, capped at the band’s ceiling (95 in the upper band, 100 in the lower band), to enhance differentiation while keeping anchors fixed.

Reference scale s(n), we define s(n) as the best human score for n <= 100, and then s(n) = 2 * s(ceil(n / 4)) for n > 100.

Notes on scoring
- Baseline (L = L0): 1 points.
- Meeting s(n): at least 95 points.
- Area bound (L = LB): 100 points.
- Scores vary smoothly between these anchors.
- The +10% amplification is applied within each band and capped at that band’s ceiling (95 or 100) to increase separation among close solutions without exceeding the anchors.

Time limit
1 second

Memory limit
512 MB

Sample
Input
11

Output
4.000000
0.500000 0.500000 0.000000
1.500000 0.500000 0.000000
2.500000 0.500000 0.000000
3.500000 0.500000 0.000000
0.500000 1.500000 0.000000
1.500000 1.500000 0.000000
2.500000 1.500000 0.000000
3.500000 1.500000 0.000000
0.500000 2.500000 0.000000
1.500000 2.500000 0.000000
2.500000 2.500000 0.000000

(The sample is a valid baseline packing for n = 11 with L = 4.000000.)

Additional clarifications
- Unit squares: Side length exactly 1, centered at (xi, yi), rotated by ai degrees around the center.
- Ordering: Squares may be listed in any order.
- Precision: Inputs are read as doubles; small rounding differences are tolerated per epsilon.
- Touching: Squares may touch each other and the container boundary; only interior overlap is forbidden.

Design notes (for organizers and contestants)
- Why this scoring? It anchors 0 at the simple baseline L0, assigns ≥95 once a high-quality reference s(n) is matched (using best-known/curated targets for n ≤ 100 and a recursion for larger n), and caps at 100 at the area bound LB. A +10% amplification within each band enhances differentiation while keeping the anchor points fixed.
- Existence: For fixed n and L, the feasible set (positions and angles satisfying containment and non-overlap) is closed and bounded. Minimizers exist by compactness; hence a minimal container side length exists for each n.
- Implementation tip: The baseline generator achieves L = ceil(sqrt(n)) with unrotated squares on a grid. Heuristics (local search, small rotations, nonlinear optimization with overlap penalties) often reduce L below the baseline for many n.


Bigger Sokoban 40k
Time Limit: 2 seconds
Memory Limit: 1024 MB

Problem
Sokoban is a famous puzzle game where a player moves around in a grid and pushes boxes to their storage locations.

Bigger Sokoban is a variation of Sokoban where both the boxes and the storage locations are larger than 1×1.
In this version, both boxes and storage locations are 2×2 in size.

The rules are the same as in the original Sokoban:

- Each cell in the grid is either empty or a wall.
- Some 2×2 areas of empty squares contain a box, and some 2×2 areas are marked as storage locations.
- The player may move up, down, left, or right into adjacent empty squares, but cannot pass through walls, boxes, or go outside the grid.
- If the player moves into a box, the box is pushed one square in that direction, provided that doing so does not push it into a wall, another box, or outside the grid.
- Boxes cannot be pulled.
- The number of boxes equals the number of storage locations.
- The puzzle is solved when all boxes are placed on the storage locations.

The grid must satisfy the following constraints:
- The grid contains one box and one storage location (each 2×2).
- The player, the box, and the storage location must not overlap.
- 1 ≤ N, M, N + M ≤ 100

Input
There is no input for this problem.

Output
On the first line, print two integers N and M, the grid size.
Then print N lines of length M, describing the grid.
Each character must be one of the following:
- '.' : empty square
- '#' : wall
- 'P' : player
- 'B' : box (2×2 block)
- 'S' : storage location (2×2 block)

The grid must contain exactly:
- 1 player (P)
- 4 'B' cells forming a single 2×2 square
- 4 'S' cells forming a single 2×2 square
The grid must be solvable.

Example Output
(Note: This is just an example of correct format.)
5 6
....SS
....SS
.#BB#.
..BB.P
......

Scoring
Your program must output a valid and solvable grid according to the above format.
Your solution will be evaluated by a checker program that computes the minimum number of moves required to solve your grid.

Scoring rule:
- 63,000 moves → 100 points
- 0 moves → 0 points
- Linear scaling between them.

Formula:
score = min(100, max(0, moves / 630))

Task
Write a C++ program that outputs one valid grid satisfying the above conditions to standard output.
Your goal is to maximize the minimum number of moves needed to solve the puzzle.

type: default
time: 2s
memory: 1024m
subtasks:
  - score: 100
    n_cases: 1
checker: chk.cpp
checker_type: testlib


Problem: Traveling Santa with Carrot Constraint

Story
Rudolph plans to shorten Santa’s route by choosing a better order to visit cities. Every 10th step takes 10% longer unless that step starts from a prime-numbered city. Your task is to output a valid tour and compete on how much you improve over a strengthened baseline.

Formal definition
- There are N cities labeled 0, 1, 2, …, N−1. City 0 is the North Pole.
- Each city i has 2D Cartesian coordinates (xi, yi).
- A route is a sequence P of length N+1: P0, P1, …, PN with:
  - P0 = PN = 0
  - {P1, P2, …, PN−1} is a permutation of {1, 2, …, N−1}
- The Euclidean distance between cities a and b is dist(a, b) = sqrt((xa − xb)^2 + (ya − yb)^2).
- Carrot constraint (10% step penalty):
  - For each step t = 1, 2, …, N (moving from P[t−1] to P[t]), define a multiplier:
    - If t is a multiple of 10 and P[t−1] is not a prime number, multiplier m[t] = 1.1
    - Otherwise, m[t] = 1.0
  - We use the standard definition of primes over city IDs: 2, 3, 5, 7, 11, … are prime; 0 and 1 are not prime.
- The penalized length of the route is:
  L(P) = sum over t = 1..N of m[t] × dist(P[t−1], P[t])

Goal
Minimize L(P) subject to the route validity constraints.

Input
- First line: integer N (2 ≤ N ≤ 200000).
- Next N lines: two integers xi yi for i = 0..N−1.
  - Coordinates satisfy |xi|, |yi| ≤ 10^9.
  - IMPORTANT: The N lines are given in strictly increasing order by x:
    x0 < x1 < x2 < … < xN−1.
    City IDs equal their input order. This strengthens the baseline path that follows the input order.

Output
- First line: integer K, which must be exactly N+1.
- Next K lines: one integer per line, the city ID sequence P0, P1, …, PN.
  - Must satisfy P0 = PN = 0 and visit every city 1..N−1 exactly once.

Validity checks
- City IDs must be in [0, N−1].
- The sequence must start and end at 0.
- Each city 1..N−1 must appear exactly once between P1 and PN−1.
- If any of these fail, the output is invalid and receives 0 for that test.

Notes and clarifications
- Step indexing for penalties is global over the entire tour: steps t = 10, 20, 30, … may be penalized depending on the source city ID at that step.
- If N < 10, no step index is a multiple of 10, so no 10% penalties occur.
- 0 and 1 are not prime. The first prime city ID is 2.
- Distances and sums are computed in double precision; no rounding beyond floating-point arithmetic.
- The platform may display normalized scores in [0, 100]; the checker outputs [0, 1] (after remap).
- Multiple tests of varying sizes are used; your final score is the average of per-test scores.

Constraints and limits
- Time limit: 2 seconds
- Memory limit: 512 MB

Sample
Input
5
0 0
1 0
2 0
3 1
4 1

Output
6
0
1
2
3
4
0

(The sample illustrates format only.)

type: default
# The time limit is now 1 second.
time: 2.5s
memory: 512m
# A custom checker is required for the special scoring.
checker: chk.cc
subtasks:
  - score: 100
    n_cases: 3


Problem: Balanced Graph Partitioning (DIMACS10-style, EC & CV)

Overview
--------
You are given an undirected, unweighted graph G = (V, E) and an integer k (a power of two).
Assign each vertex to one of k parts so that:
  1) the balance constraint is satisfied, and
  2) two quality measures are minimized with equal importance:
     • Edge Cut (EC): the number of edges whose endpoints are in different parts.
     • Communication Volume (CV): defined below.

This statement precisely defines the graph model, balance rule, metrics, I/O, and scoring.

Definitions
-----------
Graph model
• Input may contain duplicate edges and self-loops; the judge reduces to a simple undirected graph
  by ignoring self-loops and merging parallel edges.
• Vertices are labeled 1..n.

Partition
• A k-way partition is p : V → {1,2,…,k}. Empty parts are allowed.
• k is always a power of two in the official tests.

Balance constraint
• Let n = |V| and k be given. Let ideal = ceil(n / k). Let eps be the slack from the input.
• Every part must satisfy:  size(part) ≤ floor((1 + eps) * ideal).

Edge Cut (EC)
• EC(p) = |{ {u,v} ∈ E : p(u) ≠ p(v) }| (minimize).

Communication Volume (CV)
• For a vertex v with part P = p(v), define F(v) = number of DISTINCT other parts Q ≠ P such that
  v has at least one neighbor in part Q.
• For each part Q, Comm(Q) = Σ_{v : p(v)=Q} F(v).
• CV(p) = max_{Q} Comm(Q) (minimize).

Input
-----
Line 1:  n m k eps
Lines 2..m+1:  u v   (1 ≤ u,v ≤ n).

Output
------
Print exactly n integers, the labels p_1 … p_n with 1 ≤ p_i ≤ k. Whitespace is free.

Scoring
-------
The .ans file accompanying each test provides four integers:
    bestEC bestCV baselineEC baselineCV
Per metric, the checker computes:
    s = clamp((baseline - your) / (baseline - best), 0, 1)    (minimization)
and returns score = (s_EC + s_CV) / 2.

Important for this pack:
• We set bestEC = 0 and bestCV = 0 for all tests. These are theoretical lower bounds (ideal targets) and
  do not imply that EC=0 or CV=0 is achievable on a given graph or with k>1. They are used solely for
  normalization, i.e. your normalized improvement is (baseline - your) / baseline (clamped to [0,1]).
• baselineEC and baselineCV are computed from median performance of multiple random balanced partitions
  (or may be fixed by the organizers).

Constraints
-----------
• Time:   1 s per test
• Memory: 512 MB
• k: power of two
• eps = 0.03 in this dataset
• Graphs are large and structure-rich (R-MAT, BA, SBM-like, regular/expander-ish, torus, 3D grid).

Validation by the checker
-------------------------
• Exactly n labels read; each in [1..k].
• Balance enforced: size(part) ≤ floor((1 + eps) * ceil(n / k)).
• EC and CV computed on the simplified simple graph.
• Partial credit reported with the substring “Ratio: <score>”.

type: default
time: 1s
memory: 512m
checker: chk.cc
subtasks:
  - score: 1
    n_cases: 3


Title: Job Shop Scheduling (JSPLIB-style) — Open Optimization Track

Overview
--------
You are given a classic Job Shop Scheduling Problem (JSSP). There are J jobs and M machines.
Each job must be processed exactly once on each machine, in a job-specific order (its *route*).
Processing is non-preemptive. A machine can process at most one operation at a time. The goal is to minimize the *makespan*:
the completion time of the last operation among all jobs.

This problem is NP-hard. We therefore use an *open scoring* scheme that rewards better (lower) makespans. See **Scoring** below.

Terminology
-----------
• Operation: A single (job, machine) processing step with a fixed processing time.
• Route of a job j: A sequence of M distinct machines (0..M-1) listing the order in which job j must visit them.
• Precedence (job chain): If the k-th operation of job j precedes its (k+1)-th, the latter cannot start before the former finishes.
• Resource constraint (machine): Operations assigned to the same machine cannot overlap in time.
• Makespan (C_max): The maximum completion time over all operations in the schedule.

Input Format
------------
The input is plain text with 0-based indices.

Line 1:
  J M
  • J (integer): number of jobs (J ≥ 1)
  • M (integer): number of machines (M ≥ 1)

Lines 2..(J+1): one line per job j in order j = 0..J-1. Each line contains 2*M integers
representing the route and processing times for job j:

  m_0 p_0  m_1 p_1  ...  m_{M-1} p_{M-1}

where:
  • m_k ∈ {0,1,...,M-1} is the machine index of the k-th operation of job j.
  • p_k is a positive integer (processing time of that operation).
  • Each machine index must appear **exactly once** in a job’s line (every job uses every machine exactly once).
  • The order of the pairs on the line determines the job’s precedence constraints.

Output Format
-------------
You must output **exactly M lines**.
Line m (for m = 0..M-1) must contain **J distinct integers**: a permutation of {0,1,...,J-1}.
This permutation specifies the order in which machine m processes the J jobs (from first to last).

Important:
• You **do not** print start or finish times.
• Your permutations must mention each job exactly once on every machine. Otherwise, the checker will reject the output.
• The judge constructs the earliest-feasible schedule implied by your machine orders and the job precedence constraints
  (equivalently: the longest-path length in the disjunctive graph with your chosen orientations on machine arcs).

Validity Rules
--------------
Your output is rejected if any of the following occurs:
• A machine line does not contain a permutation of {0..J-1} (duplicate/missing job index; out-of-range index).
• The machine orders together with the job precedence constraints induce a cycle in the disjunctive graph
  (i.e., there exists no feasible schedule consistent with your machine orders).

Scoring (Lower is Better)
-------------------------
Let P be the makespan computed from your output for a test case. The answer file for each test contains two integers:
(B, T). For this problem, **T is fixed to 0** (a trivial lower bound), and **B > 0** is the makespan of a simple feasible
baseline schedule (a naïve dispatch heuristic). The checker applies the general formula:

  If B ≤ T:   score = 1.0 if P ≤ T else 0.0
  Else:       score = clamp( (B - P) / (B - T), 0, 1 )

With T = 0 and B > 0, this simplifies to:

  score = clamp( 1 - P / B, 0, 1 )

Your final problem score is the average of your per-test scores. The checker prints partial credit messages containing
the substring “Ratio: <value>” as required by the judge.

Constraints
-----------
The official test set is deliberately challenging:
• Sizes range up to ~ (J, M) ≈ (50, 25) (total operations up to ~1,250).
• Processing times are positive integers and may range broadly (including very large values).
• Route structures include random, nearly-flow, block-flow, and strong bottlenecks (one or two machines dominating).

Tips
----
Feasible and competitive schedules often come from combinations of:
• Priority rules (SPT/LPT/weighted), bottleneck-aware dispatching.
• Local improvement via adjacent swaps per machine.
• Metaheuristics (tabu search, simulated annealing, iterated local search).
• Shifting bottleneck heuristics or relax-and-fix styles.

Example (Illustrative Only; Not in the Tests)
---------------------------------------------
Input:
  3 2
  0 3  1 4
  1 2  0 5
  0 4  1 1

Valid Output (two lines; each line is a permutation of {0,1,2}):
  2 0 1
  1 2 0

This tells the judge to process jobs on machine 0 in order [2,0,1] and on machine 1 in order [1,2,0].
The judge then computes the earliest-feasible schedule and its makespan.

type: default
# The time limit is now 1 second.
time: 1s
memory: 512m
# A custom checker is required for the special scoring.
checker: chk.cc
subtasks:
  - score: 1
    n_cases: 3


2D Rectangular Knapsack with (Optional) 90° Rotations — Official Problem Statement (Hard Set)
============================================================================================

Summary
-------
You are given a single rectangular **bin** and several **item types**. Each item type t has
dimensions (w_t, h_t), profit v_t, and an availability limit L_t. You may place zero or more
axis‑aligned rectangles (items) of these types into the bin, without overlap and fully inside
its boundary. In some tests, 90° rotation of items is allowed; in others it is not. Your goal is
to maximize the **total profit** of the placed items.

This is an **optimization** problem with **partial scoring**. Your program prints a **feasible packing**
(i.e., a list of placements). The judge validates feasibility and computes your score relative to
reference values for that test case.

1) Formal Model
---------------
• The bin is a rectangle of integer width W and height H, with its bottom‑left corner at (0, 0).
  Coordinates increase to the right (x) and up (y).

• There are M item types. Each type t has:
  – width  w_t  (integer, ≥ 1)
  – height h_t  (integer, ≥ 1)
  – profit v_t  (integer, ≥ 0)
  – limit  L_t  (integer, ≥ 0), the maximum number of copies you may place.

• A **placement** is a tuple (type_id, x, y, rot) where:
  – type_id is the string id of some item type t,
  – (x, y) are **integers** giving the bottom‑left corner of the placed rectangle,
  – rot ∈ {0, 1}. If rot = 1 and rotation is allowed in this test, the item is rotated by 90°
    so its realized size is (w′, h′) = (h_t, w_t). If rot = 0, size is (w′, h′) = (w_t, h_t).
    If rotation is **not** allowed in this test, then rot must be 0 for every placement.

• **Feasibility constraints**:
  – **Inside the bin**: 0 ≤ x and 0 ≤ y and x + w′ ≤ W and y + h′ ≤ H.
  – **Non‑overlap**: we use the **half‑open rectangle** convention. A placement occupies the set
    [x, x + w′) × [y, y + h′). Two placements are considered non‑overlapping iff their intervals
    are disjoint on **at least one** axis. In particular, **touching at edges or corners is allowed**.
  – **Limits**: for each type t, the number of placements with type_id = t must be ≤ L_t.

• Objective: maximize the sum of profits v_t over all placed items.

2) Input Format (read from stdin)
---------------------------------
The input is a single JSON object with exactly two keys: "bin" and "items".

• "bin" is a JSON object:
  { "W": <int>, "H": <int>, "allow_rotate": <true|false> }

• "items" is a JSON array of item‑type objects. Each item object has **exactly** the following keys:
  {
    "type":  "<id-string>",
    "w":     <int>,
    "h":     <int>,
    "v":     <int>,
    "limit": <int>
  }

Additional or missing keys are considered invalid.

Example (abridged):
{
  "bin":   {"W": 1399, "H": 1699, "allow_rotate": true},
  "items": [
    {"type":"A","w":33,"h":89,"v":4237,"limit":120},
    {"type":"B","w":91,"h":55,"v":8121,"limit":60}
    // ... more types ...
  ]
}

3) Output Format (write to stdout)
----------------------------------
Your program must print a single JSON object with exactly one key: "placements".

• "placements" is a JSON array. Each element is a placement object with **exactly** these keys:
  { "type": "<id-string>", "x": <int>, "y": <int>, "rot": <0|1> }

Notes:
• The order of placements does not matter.
• Do **not** add extra keys; the checker will reject unknown keys.
• It is valid to output an empty array if you choose to place nothing.

Example (feasible output):
{
  "placements": [
    {"type":"B","x":0,"y":0,"rot":1},
    {"type":"A","x":91,"y":0,"rot":0},
    {"type":"A","x":124,"y":0,"rot":0}
  ]
}

4) Feasibility Details and Edge Cases
-------------------------------------
• **Half‑open geometry**: A rectangle occupies [x, x+w′)×[y, y+h′). Therefore:
  – Two rectangles with x + w′ = x′ (or y + h′ = y′) **do not overlap** (touching is allowed).
  – The checker’s sweep‑line treats rectangles that **end** at x before inserting rectangles that
    **start** at the same x. This matches the half‑open convention.

• **Rotation permission**: If "allow_rotate" is false in the input, every placement must have rot = 0
  (no rotation). If "allow_rotate" is true, you may choose rot ∈ {0, 1} per placement.

• **Limits**: The checker counts how many times each type appears in your placements and rejects outputs
  that exceed the per‑type limit L_t.

• **Coordinate system**: (0,0) is the bin’s bottom‑left corner. x increases to the right, y upward.
  Coordinates and sizes are integers throughout.

• **Validation**: The checker rejects outputs that are not valid JSON or that violate any of the rules
  above (unknown types, out‑of‑bounds, overlap, invalid rot, extra/missing keys).

5) Constraints (Hard Set for this Round)
----------------------------------------
The official hidden tests in this round follow these ranges:

• Bin:
  – 900 ≤ W, H ≤ 2000
  – Some tests use near‑prime/co‑prime‑like dimensions to discourage trivial tilings.

• Items:
  – Number of types M: 8 ≤ M ≤ 12
  – Dimensions: 7 ≤ w_t, h_t ≤ ⌊0.6 · max(W, H)⌋ and w_t ≤ W, h_t ≤ H
  – Profit: 1 ≤ v_t ≤ 10^9
  – Limit: 1 ≤ L_t ≤ 2000
  – The distribution mixes high‑density but supply‑limited types with awkward aspect ratios
    and strip‑like pieces. Rotation is disabled in some tests.

• Output size: Near‑optimal solutions typically use O(10^2–10^3) placements per test.
  (There is no explicit hard cap, but extremely large outputs may risk time limits.)

• Time & memory limits: see Section 8.

6) Scoring
----------
For each test, the judge computes:
• V = your total profit (sum of v_t for all placements).
• B = a **lower bound** (baseline value) — a simple shelf heuristic without rotation, in input order.
• K = an **upper bound** (“best” for this round) — a fractional area fill that respects per‑type limits
      but ignores geometry (optimistically packs by value density).

Your per‑test ratio is:
  ratio = clamp( (V − B) / (K − B), 0, 1 )

Corner case: if K ≤ B, then ratio = 1 if V ≥ K, else 0.

Your problem score is the **average** ratio over all tests. Future rounds may tighten how B and/or K
are computed; you do not need to output B or K.

7) Common Mistakes That Cause Wrong Answer
------------------------------------------
• Using rot = 1 when "allow_rotate" is false.
• Overlapping rectangles (especially at shared edges): remember we use **half‑open** geometry; touching
  is allowed, overlap is not.
• Out‑of‑bounds placements: x + w′ must be ≤ W and y + h′ ≤ H.
• Exceeding per‑type limits L_t.
• Output JSON not exactly following the schema (wrong top‑level key, extra keys in placements,
  missing keys, non‑integer x/y/rot).

8) Limits
---------
• Time limit: 1 second
• Memory limit: 512 MB
• Number of test cases: 15
(These values correspond to the current hard set and match the contest configuration.)

9) Reference Implementations and Hints (Non‑binding)
----------------------------------------------------
You may find success with:
• Maximal‑rectangles or skyline‑based packers, combined with multiple item orderings (by value density,
  by height/width/area), and local repair.
• Consider that the highest value density items are **supply‑limited**; good solutions typically mix
  several types and use strips/slenders to close narrow leftovers.
• When rotation is disabled, favor orderings that reduce fragmentation in one orientation.

10) Small Worked Example
------------------------
Input:
{
  "bin": {"W": 10, "H": 6, "allow_rotate": true},
  "items": [
    {"type":"a","w":4,"h":3,"v":10,"limit":3},
    {"type":"b","w":3,"h":2,"v":6,"limit":10}
  ]
}

One feasible output (not necessarily optimal):
{
  "placements": [
    {"type":"a","x":0,"y":0,"rot":0},
    {"type":"a","x":4,"y":0,"rot":0},
    {"type":"b","x":8,"y":0,"rot":1},
    {"type":"b","x":8,"y":2,"rot":1},
    {"type":"b","x":0,"y":3,"rot":0},
    {"type":"b","x":3,"y":3,"rot":0},
    {"type":"b","x":6,"y":3,"rot":0}
  ]
}

These placements are inside the bin, respect limits, and do not overlap under the half‑open convention.

11) Compliance Checklist (Before You Submit)
--------------------------------------------
[ ] Output exactly one top‑level key: "placements".
[ ] Each placement contains exactly the keys "type", "x", "y", "rot".
[ ] All coordinates and rot are **integers**; rot ∈ {0,1}.
[ ] When rotation is disabled in the test input, use rot = 0 everywhere.
[ ] No placement exceeds the bin boundary.
[ ] No two placements overlap (touching at edges/corners is OK).
[ ] Per‑type counts do not exceed L_t.
[ ] Your JSON is syntactically valid (commas, quotes, etc.).

12) Clarifications
------------------
• “Half‑open”: a rectangle [x, x+w′)×[y, y+h′) includes all integer points with x ≤ X < x+w′ and
  y ≤ Y < y+h′. Two rectangles that meet at a vertical or horizontal line **do not** overlap.
• There is **no requirement** to fill the bin or to use all limits; you may place any multiset
  that satisfies the constraints.
• Rotations are exactly 90°; no other angles are allowed. Rotating swaps width and height.
• Profits, coordinates, and counts are within 64‑bit signed integer ranges in all official tests.

End of statement.