This task uses a 15 second time limit and provides a grader interface for interacting with the black box.

The Black Box Game is played with a square-shaped black box lying flat on a table. Each of its four sides has $n$ holes (for a total of $4\cdot n$ holes) into which a ball can be thrown. A thrown ball will eventually exit from one of the $4\cdot n$ holes, potentially the same hole into which it was thrown.

The black box's internals can be envisioned as an $n \times n$ grid. The holes in the sides are the starts and ends of rows and columns. Each of the box's squares is either empty or occupied by a deflector. A deflector is a piece of hardware that changes the direction of the ball by 90 degrees. Consider this example of a $5 \times 5$ box.

 ![](https://ioi.contest.codeforces.com/espresso/ff98996d1f014917d9047397f1ac94be98d14b72.png)

A ball thrown into the box follows a straight line until it either hits a deflector or exits the box. When a ball hits a deflector, the ball changes direction and the deflector toggles its position (by "toggle" we mean rotate 90 degrees). The examples below show the action of a deflector.

 ![](https://ioi.contest.codeforces.com/espresso/0aed97ae1bb4bf5d5068d49c4255efda2bca9128.png)

1. A ball is thrown through a hole; it hits a deflector and changes direction.
2. After the first ball was thrown, the deflector has toggled its position. A new ball is thrown into the same hole, hits the deflector and is deflected in a direction opposite to that of the first ball.
3. The deflector toggles every time it is hit.

Whenever a deflector is hit, it makes a beep. The number of times the ball was deflected can be deduced by counting the beeps. It can be proved that the ball always exits the box. The box has a button that resets it to its original state and another button that toggles all of its deflectors.

You will be provided with an interface to black box via grader. You must determine the internals of the box as best as possible .

$1 \le n \le 30$

Input

You are given a grader that provides the following functions

```
int throwBall(int holeIn, int sideIn, int &holeOut, int &sideOut);
```

Throws a ball into the box through hole number holeIn in side sideIn, sides are numbered as 1 — Top, 2 — Right, 3 — Bottom and 4 — Left. Holes are numbered from left to right and from top to bottom starting from number 1 in each side. In holeOut and sideOut you'll receive the hole and side number where the ball exits the box. The function throwBall returns the number of beeps caused by the ball hitting a deflector.

```
void ResetBox();
```

Resets every deflector in the box to its initial position.

```
void ToggleDeflectors();
```

Toggles every deflector in the box.

You need to implement function

```
void solve(vector<string>& ans);
```

This function should put answer in to given vector. $ans[i][j]$ should be equal to content of cell $(i, j)$ with same symbols, that are used for input below. If you can't determinate content of cell, you can fill it with ?, and still receive part of points. Size of vector is equal to size of field. Initially all elements are filled with ?

A sample interaction for the box in the previous figure could be:

throwBall(3, 4, holeOut, sideOut);

A ball is thrown into hole number 3 (third from the top) on the left side. Returns 1, indicating that the ball hit 1 deflector. When the function returns, holeOut will equal 2 and sideOut will equal 3 indicating that the ball exited through hole 2 (second from the left) of the bottom side of the box.

Grader will read input in following format:

LINE 1: Contains n, the number of holes on each side.

n LINES: Each line describes a row of the box, starting from the topmost row to the bottom row. Each line must contain exactly n characters; each character corresponds to a column (running from left to right).

* "." means that the square is empty.
* "/" means the square contains a deflector with initial position "/"
* "\" means the square contains a deflector with initial position "\"

Input for test 01 can be found in problem graders archive. Solving it will not be rewarded by any points.

Scoring

If your submission has a '.", "/" or "\" character in an incorrect position, you'll get zero points for that box.

Let $n$ be the size of box, and let $B$ be the number of discovered positions in your submission, then percentage of your score for that test would be $\frac{100 \cdot B}{n^2}$.

#include "blackbox.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 32
#define K (N * N)

static char F[N][N];
static char _F[N][N];

static int _x[K], _y[K];
static char _v[K];
static int pt = 0;

static int n;

void ToggleDeflectors() {
  int i;
  for (i = 0; i < pt; i++)
    F[_y[i]][_x[i]] ^= '/' ^ '\\';
}

void ResetBox() {
  int i;
  for (i = 0; i < pt; i++)
    F[_y[i]][_x[i]] = _v[i];
}

static void internal_init() {
  int i, j;
  scanf("%s", F[0]);
  n = strlen(F[0]);
  for (i = 1; i < n; i++)
    scanf("%s", F[i]);
  memcpy(_F, F, sizeof(F));
  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      if (F[i][j] != '.')
        _x[pt] = j, _y[pt] = i, _v[pt] = F[i][j], pt++;
}

static int vy[] = {1, 0, -1, 0};
static int vx[] = {0, -1, 0, 1};

// 0 - down, 1 - left, 2 - up, 3 - right

int throwBall(int h, int s, int &newh, int &news) {
  if (!(1 <= s && s <= 4)) {
    printf("Invalid side : %d\n", s);
    exit(0);
  }
  if (!(1 <= h && h <= n)) {
    printf("Invalid hole : %d\n", h);
    exit(0);
  }
  --s;
  --h;
  int x, y;
  if (s % 2)
    y = h, x = (s == 1) * (n - 1);
  else
    x = h, y = (s == 2) * (n - 1);
  int v = s;
  int count = 0;
  while (1) {
    if (F[y][x] != '.') {
      v = ((F[y][x] == '/') ?
                            // 0 - 1, 2 - 3
               1 ^ v
                            :
                            // 0 - 3, 1 - 2
               3 ^ v);
      count++;
      F[y][x] ^= ('/' ^ '\\');
    }
    y += vy[v];
    x += vx[v];
    if (y < 0 || x < 0 || y >= n || x >= n)
      break;
  }
  h = (v % 2) ? y : x;
  h++;
  s = 2 ^ v;
  s++;
  news = s;
  newh = h;
  return count;
}

static int notFound;

static void CheckAnswer(std::vector<std::string> pans) {
  int i, j;
  ResetBox();
  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++) {
      if (pans[i][j] != F[i][j] && pans[i][j] != '?') {
        printf("Position (%d,%d) doesn't match", i + 1, j + 1);
        exit(0);
      } else if (pans[i][j] == '?')
        notFound++;
    }
}

int main() {
  internal_init();
  std::vector<std::string> pans(n, std::string(n, '?'));
  solve(pans);
  CheckAnswer(pans);
  printf("OK %d cells not found\n", notFound);
  return 0;
}

#pragma once

#include <vector>
#include <string>

void ToggleDeflectors();
void ResetBox();
int throwBall(int sideIn, int holeIn, int& sideOut, int& holeOut);
void solve(std::vector<std::string> &ans);


Jian-Jia is a young boy who loves playing games. When he is asked a question, he prefers playing games rather than answering directly. Jian-Jia met his friend Mei-Yu and told her about the flight network in Taiwan. There are $n$ cities in Taiwan (numbered $0, \ldots, n - 1$), some of which are connected by flights. Each flight connects two cities and can be taken in both directions.

Mei-Yu asked Jian-Jia whether it is possible to go between any two cities by plane (either directly or indirectly). Jian-Jia did not want to reveal the answer, but instead suggested to play a game. Mei-Yu can ask him questions of the form "Are cities $x$ and $y$ directly connected with a flight?", and Jian-Jia will answer such questions immediately. Mei-Yu will ask about every pair of cities exactly once, giving $r = \frac{n(n - 1)}{2}$ questions in total. Mei-Yu wins the game if, after obtaining the answers to the first $i$ questions for some $i < r$, she can infer whether or not it is possible to travel between every pair of cities by flights (either directly or indirectly). Otherwise, that is, if she needs all $r$ questions, then the winner is Jian-Jia.

In order for the game to be more fun for Jian-Jia, the friends agreed that he may forget about the real Taiwanese flight network, and invent the network as the game progresses, choosing his answers based on Mei-Yu's previous questions. Your task is to help Jian-Jia win the game, by deciding how he should answer the questions

Task

Please write a program that helps Jian-Jia win the game. Note that neither Mei-Yu nor Jian-Jia knows the strategy of each other. Mei-Yu can ask about pairs of cities in any order, and Jian-Jia must answer them immediately without knowing the future questions. You need to implement the following two functions.

* void initialize(int n) — We will call your initialize first. The parameter $n$ is the number of cities.
* int hasEdge(int u, int v) — Then we will call hasEdge for $r = \frac{n(n - 1)}{2}$ times. These calls represent Mei-Yu's questions, in the order that she asks them. You must answer whether there is a direct flight between cities $u$ and $v$. Specifically, the return value should be $1$ if there is a direct flight, or $0$ otherwise.

Input

The sample grader reads the input in the following format:

* line 1: $n$
* the following $r$ lines: each line contains two integers $u$ and $v$ that describe a question regarding cities $u$ and $v$.

Output

For each request the sample grader will return 1 if hasEdge return $1$ for and 0 otherwise.

Scoring

Each subtask consists of several games. You will only get points for a subtask if your program wins all of the games for Jian-Jia.

|  |  |  |
| --- | --- | --- |
| Subtask | Points | $n$ |
| 1 | 15 | $n = 4$ |
| 2 | 27 | $4 \le n \le 80$ |
| 3 | 58 | $4 \le n \le 1500$ |

Examples

Input

```
4
0 1
3 0
1 2
0 2
3 1
2 3
```

Output

```
100101
```

Input

```
4
0 3
2 0
0 1
1 2
1 3
2 3
```

Output

```
001101
```

Input

```
4
0 3
1 0
0 2
3 1
1 2
2 3
```

Output

```
010011
```

Note

We explain the game rules with three examples. Each example has $n = 4$ cities and $r = 6$ rounds of question and answer.

In the first example (the following table), Jian-Jia loses because after round 4, Mei-Yu knows for certain that one can travel between any two cities by flights, no matter how Jian-Jia answers questions 5 or 6.

|  |  |  |
| --- | --- | --- |
| Round | Question | Answer |
| 1 | 0, 1 | yes |
| 2 | 3, 0 | yes |
| 3 | 1, 2 | no |
| 4 | 0, 2 | yes |
| — | — | — |
| 5 | 3, 1 | no |
| 6 | 2, 3 | no |

In the next example Mei-Yu can prove after round 3 that no matter how Jian-Jia answers questions 4, 5, or 6, one cannot travel between cities 0 and 1 by flights, so Jian-Jia loses again.

|  |  |  |
| --- | --- | --- |
| Round | Question | Answer |
| 1 | 0, 3 | no |
| 2 | 2, 0 | no |
| 3 | 0, 1 | no |
| — | — | — |
| 4 | 1, 2 | yes |
| 5 | 1, 3 | yes |
| 6 | 2, 3 | yes |

In the final example Mei-Yu cannot determine whether one can travel between any two cities by flights until allsix questions are answered, so Jian-Jia wins the game. Specifically, because Jian-Jia answered yes to the last question (in the following table), then it is possible to travel between any pair of cities. However, if Jian-Jia had answered no to the last question instead then it would be impossible.

|  |  |  |
| --- | --- | --- |
| Round | Question | Answer |
| 1 | 0, 3 | no |
| 2 | 1, 0 | yes |
| 3 | 0, 2 | no |
| 4 | 3, 1 | yes |
| 5 | 1, 2 | no |
| 6 | 2, 3 | yes |

#include "game.h"

void initialize(int n) {

}

int hasEdge(int u, int v) {
    return 1;
}

#include <cstdio>
#include <cassert>
#include "game.h"

int read_int() {
    int x;
    assert(scanf("%d", &x) == 1);
    return x;
}

int main() {
    int n, u, v;
    n = read_int();
    initialize(n);
    for (int i = 0; i < n * (n - 1) / 2; i++) {
        u = read_int();
        v = read_int();
        printf("%d\n", hasEdge(u, v));
    }
    return 0;
}

#ifndef _GAME_H
#define _GAME_H

void initialize(int n);
int hasEdge(int u, int v);

#endif


A game called Memory is played using $50$ cards. Each card has one of the letters from A to Y (ASCII $65$ to $89$) printed on the face, so that each letter appears on exactly two cards. The cards are shuffled into some random order and dealt face down on the table.

Jack plays the game by turning two cards face up so the letters are visible. For each of the $25$ letters Jack gets a candy from his mother the first time he sees both copies of the letter on the two face up cards. For example, the first time Jack turns over both cards that contain the letter M, he gets a candy. Regardless of whether the letters were equal or not, Jack then turns both cards face down again. The process is repeated until Jack receives $25$ candies — one for each letter.

You are to implement a procedure play that plays the game. Your implementation should call the procedure faceup(C) which is implemented by the grader. $C$ is a number between $1$ and $50$ denoting a particular card you wish to be turned face up. The card $C$ must not currently be face up. faceup(C) returns the character that is printed on the card $C$.

After every second call to faceup, the grader automatically turns both cards face down again.

Your procedure play may only terminate once Jack has received all $25$ candies. It is allowed to make calls to faceup(C) even after the moment when Jack gets the last candy.

The following is one possible sequence of calls your procedure play could make, with explanations.

|  |  |  |
| --- | --- | --- |
| Call | Returned value | Explanation |
| faceup(1) | 'B' | Card $1$ contains B. |
| faceup(7) | 'X' | Card $7$ contains X. The letters are not equal. The grader automatically turns cards $1$ and $7$ face down. |
| faceup(7) | 'X' | Card $7$ contains X. |
| faceup(15) | 'O' | Card $15$ contains O. The letters are not equal. The grader automatically turns cards $7$ and $15$ face down. |
| faceup(50) | 'X' | Card $50$ contains X. |
| faceup(7) | 'X' | Card $7$ contains X. Jack gets his first candy. The grader automatically turns cards $50$ and $7$ face down. |
| faceup(7) | 'X' | Card $7$ contains X. |
| faceup(50) | 'X' | Card $50$ contains X. Equal letters, but Jack gets no candy. The grader automatically turns cards $7$ and $50$ face down. |
| faceup(2) | 'B' | Card $2$ contains B. |
| ... | ... | Some function calls were omitted |
| faceup(1) | 'B' | Card $1$ contains B. |
| faceup(2) | 'B' | Card $2$ contains B. Jack gets his 25th candy. |

Scoring

|  |  |  |
| --- | --- | --- |
| Subtask | Points | Additional Input Constraints |
| 1 | 50 | Implement any strategy that obeys the rules of the game and finishes it within the time limit. For example, there is a simple strategy that always makes exactly $2 \cdot (49+48+...+2+1) = 2450$ calls to faceup(C). |
| 2 | 50 | Implement a strategy that finishes any possible game with at most $100$ calls to faceup(C). |

#include "memory.h"
#include "grader.h"
#include <stdio.h>
#include <stdlib.h>

static char card[51];
static int up[2], is_up[51], candy[25], candies, moves;

char faceup(int C){
   int c0, c1;
   if (C < 1 || C > 50 || is_up[C]) {
      exit(92);
   }
   is_up[C] = 1;
   up[moves%2] = C;
   moves++;
   if (moves%2 == 0) {
      c0 = card[ up[0] ] - 'A';
      c1 = card[ up[1] ] - 'A';
      if (c0==c1 && !candy[c0]) {
         candy[c0] = 1;
         ++candies;
      }
      is_up[ up[0] ] = is_up[ up[1] ] = 0;
   }
   return card[C];
}

void playgame(){
   int i;
   for (i=1;i<=50;i++) {
      card[i] = getchar();
   }
   moves = candies = 0;
   play();
   if (candies != 25) {
      exit(91);
   }
}

int main(){
   playgame();
   printf("OK %d\n",moves);
   return 0;
}

#include "grader.h"
#include "memory.h"

void play() {
   int i;
   char a, b;
   for (i=0; i<10; ++i) {
      a = faceup(42);
      b = faceup(47);
   }
}


Dr. Black has been murdered. Detective Jill must determine the murderer, the location, and the weapon. There are six possible murderers, numbered 1 to 6. There are ten possible locations, numbered 1 to 10. There are six possible weapons, numbered 1 to 6.

For illustration only, we show the names of the possible murderers, locations and weapons. The names are not required to solve the task.

|  |  |  |
| --- | --- | --- |
| Murderer | Location | Weapon |
| 1. Professor Plum 2. Miss Scarlet 3. Colonel Mustard 4. Mrs. White 5. Reverend Green 6. Mrs. Peacock  — | 1. Ballroom 2. Kitchen 3. Conservatory 4. Dining Room 5. Billiard Room 6. Library 7. Lounge 8. Hall 9. Study 10. Cellar   — | 1. Lead pipe 2. Dagger 3. Candlestick 4. Revolver 5. Rope 6. Spanner   — |

Jill repeatedly tries to guess the correct combination of murderer, location and weapon. Each guess is called a theory. She asks her assistant Jack to confirm or to refute each theory in turn. When Jack confirms a theory, Jill is done. When Jack refutes a theory, he reports to Jill that one of the murderer, location or weapon is wrong.

You are to implement the procedure Solve that plays Jill's role. The grader will call Solve many times, each time with a new case to be solved. Solve must repeatedly call Theory(M,L,W), which is implemented by the grader. M, L and W are numbers denoting a particular combination of murderer, location and weapon. Theory(M,L,W) returns 0 if the theory is correct. If the theory is wrong, a value of 1, 2 or 3 is returned. 1 indicates that the murderer is wrong; 2 indicates that the location is wrong; 3 indicates that the weapon is wrong. If more than one is wrong, Jack picks one arbitrarily between the wrong ones (not necessarily in a deterministic way). When Theory(M,L,W) returns 0, Solve should return.

Example

As example, assume that Miss Scarlet committed the murder (Murderer 2) in the conservatory (Location 3) using a revolver (Weapon 4). When procedure Solve makes the following calls to function Theory, the results in the second column could be returned.

|  |  |  |
| --- | --- | --- |
| Call | Returned value | Explanation |
| Theory(1, 1, 1) | 1, or 2, or 3 | All three are wrong |
| Theory(3, 3, 3) | 1, or 3 | Only the location is correct |
| Theory(5, 3, 4) | 1 | Only the murderer is wrong |
| Theory(2, 3, 4) | 0 | All are correct |

Scoring

|  |  |  |
| --- | --- | --- |
| Subtask | Points | Additional Input Constraints |
| 1 | 50 | Each test run may call Solve up to $100$ times. Each call might correspond to a different combination of murderer, location and weapon as the answer. Each time Solve is called, it must find the correct theory with no more than $360$ calls to Theory(M,L,W). Be sure to initialize any variables used by Solve every time it is called. |
| 2 | 50 | Each test run may call Solve up to $100$ times. Each time Solve is called, it must find the correct theory with no more than $20$ calls to Theory(M,L,W). Be sure to initialize any variables used by Solve every time it is called. |

#include "grader.h"
#include "cluedo.h"

void Solve(){
   int r;
   r = Theory(1,2,3);
   if (r == 0) return;
   r = Theory(3,2,1);
   if (r == 0) return;
   r = Theory(4,4,4);
   if (r == 0) return;
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "grader.h"
#include "cluedo.h"

static int M,L,W,gotit,cnt,maxcnt;

int Theory(int m, int l, int w) {
   ++cnt;
   if (m < 1 || m > 6 || l < 1 || l > 10 || w < 1 || w > 6) exit(92);
   if (rand()%2 && m != M) return 1;
   else if (rand()%2 && l != L) return 2;
   else if (rand()%2 && w != W) return 3;
   else if (m != M) return 1;
   else if (l != L) return 2;
   else if (w != W) return 3;
   gotit = 1;
   return 0;
}

int main(){
   while (3 == scanf("%d%d%d",&M,&L,&W)) {
      cnt = gotit = 0;
      Solve();
      if (cnt > maxcnt) maxcnt = cnt;
      if (!gotit) {
         printf("NO\n");
         return 91;
      }
   }
   printf("OK %d\n",maxcnt);
   return 0;
}


While lost on the long walk from the college to the UQ Centre, you have stumbled across the entrance to a secret cave system running deep under the university. The entrance is blocked by a security system consisting of $N$ consecutive doors, each door behind the previous; and N switches, with each switch connected to a different door.

![](https://ioi.contest.codeforces.com/espresso/1f7aed863559e3e0a541816cc2d8c998e32b4473.png)

The doors are numbered $0, 1, \dots, N - 1$ in order, with door $0$ being closest to you. The switches are also numbered $0, 1, \dots, N - 1$, though you do not know which switch is connected to which door.

The switches are all located at the entrance to the cave. Each switch can either be in an up or down position. Only one of these positions is correct for each switch. If a switch is in the correct position then the door it is connected to will be open, and if the switch is in the incorrect position then the door it is connected to will be closed. The correct position may be different for different switches, and you do not know which positions are the correct ones.

You would like to understand this security system. To do this, you can set the switches to any combination, and then walk into the cave to see which is the first closed door. Doors are not transparent: once you encounter the first closed door, you cannot see any of the doors behind it.

You have time to try $70\,000$ combinations of switches, but no more. Your task is to determine the correct position for each switch, and also which door each switch is connected to.

You should submit a file that implements the procedure exploreCave(). This may call the grader function tryCombination() up to $70\,000$ times, and must finish by calling the grader procedure answer(). These functions and procedures are described below.

Grader Function tryCombination():

int tryCombination(int S[]);

The grader will provide this function. It allows you to try a combination of switches, and then enter the cave to determine the first closed door. If all doors are open, the function will return $-1$. This function runs in $O(N)$ time; that is, the running time is at worst proportional to $N$.

This function may be called at most $70\,000$ times.

Parameters:

* $S$: An array of length $N$, indicating the position of each switch. The element $S[i]$ corresponds to switch $i$. A value of $0$ indicates that the switch is up, and a value of $1$ indicates that the switch is down.
* Returns: The number of the first door that is closed, or $-1$ if all doors are open.

Grader Procedure answer():

void answer(int S[], int D[]);

Call this procedure when you have identified the combination of switches to open all doors, and the door to which each switch is connected.

Parameters:

* $S$: An array of length $N$, indicating the correct position of each switch. The format matches that of the function tryCombination() described above.
* $D$: An array of length $N$, indicating the door each switch is connected to. Specifically, element $D[i]$ should contain the door number that switch $i$ is connected to.
* Returns: This procedure does not return, but will cause the program to exit.

Your Procedure exploreCave():

void exploreCave(int N);

Your submission must implement this procedure.

This function should use the grader routine tryCombination() to determine the correct position for each switch and the door each switch is connected to, and must call answer() once it has determined this information.

Parameters:

* $N$: The number of switches and doors in the cave.

Input

The sample grader reads input in the following format:

* line $1$: $N$
* line $2$: $S[0]\ S[1]\dots S[N - 1]$
* line $3$: $D[0]\ D[1]\dots D[N - 1]$

Here $N$ is the number of doors and switches, $S[i]$ is the correct position for switch $i$, nd $D[i]$ is the door that switch $i$ is connected to.

Scoring

Full constraints: $1 \leq N \leq 5\,000$

|  |  |  |
| --- | --- | --- |
| Subtask | Points | Additional Input Constraints |
| 1 | 12 | For each $i$, switch $i$ is connected to door $i$. Your task is simply to determine the correct combination. |
| 2 | 13 | The correct combination will always be $[0,0,0, \dots ,0]$. Your task is simply to determine which switch connects to which door. |
| 3 | 21 | $N \leq 100$ |
| 4 | 30 | $N \leq 2\,000$ |
| 5 | 24 | (None) |

Example

Input

```
4
1 1 1 0
3 1 0 2
```

Output

Note

Suppose the doors and switches are arranged as in the picture above:

|  |  |  |
| --- | --- | --- |
| Function Call | Returns | Explanation |
| tryCombination([1, 0, 1, 1]) | $1$ | This corresponds to the picture. Switches $0$, $2$ and $3$ are down, while switch $1$ is up. The function returns $1$, indicating that door $1$ is the first door from the left that is closed. |
| tryCombination([0, 1, 1, 0]) | 3 | Doors $0$, $1$ and $2$ are all opened, while door $3$ is closed. |
| tryCombination([1, 1, 1, 0]) | $-1$ | Moving switch $0$ down causes all doors to be opened, indicated by the return value of $-1$. |
| answer([1, 1, 1, 0],[3, 1, 0, 2]) | (Program exits) | We guess that the correct combination is $[1,1, 1,0]$, and that switches $0$, $1$, $2$ and $3$ connect to doors $3$, $1$, $0$ and $2$ respectively. |

#include "cave.h"

void exploreCave(int N) {
    /* ... */
}

#ifndef __CAVE_H__
#define __CAVE_H__

#ifdef __cplusplus
extern "C" {
#endif

int tryCombination(int S[]);
void answer(int S[], int D[]);
void exploreCave(int N);

#ifdef __cplusplus
}
#endif

#endif /* __CAVE_H__ */

#include "graderlib.c"

int main() {
    int N;
	N = init();
	exploreCave(N);
    printf("INCORRECT\nYour solution did not call answer().\n");
	return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include "cave.h"

#define MAX_N 5000
#define MAX_CALLS 70000

#define fail(s, x...) do { \
		fprintf(stderr, s "\n", ## x); \
		exit(1); \
	} while(0)

/* Symbol obfuscation */
#define N koala
#define realS kangaroo
#define realD possum
#define inv platypus
#define num_calls echidna

static int N;
static int realS[MAX_N];
static int realD[MAX_N];
static int inv[MAX_N];
static int num_calls;

void answer(int S[], int D[]) {
    int i;
    int correct = 1;
    for (i = 0; i < N; ++i)
        if (S[i] != realS[i] || D[i] != realD[i]) {
            correct = 0;
            break;
        }

    if (correct)
        printf("CORRECT\n");
    else
        printf("INCORRECT\n");

    for (i = 0; i < N; ++i) {
        if (i > 0)
            printf(" ");
        printf("%d", S[i]);
    }
    printf("\n");

    for (i = 0; i < N; ++i) {
        if (i > 0)
            printf(" ");
        printf("%d", D[i]);
    }
    printf("\n");

    exit(0);
}

int tryCombination(int S[]) {
    int i;

    if (num_calls >= MAX_CALLS) {
        printf("INCORRECT\nToo many calls to tryCombination().\n");
        exit(0);
    }
    ++num_calls;

    for (i = 0; i < N; ++i)
        if (S[inv[i]] != realS[inv[i]])
            return i;
    return -1;
}

int init() {
    int i, res;

	res = scanf("%d", &N);

    for (i = 0; i < N; ++i) {
        res = scanf("%d", &realS[i]);
    }
    for (i = 0; i < N; ++i) {
        res = scanf("%d", &realD[i]);
        inv[realD[i]] = i;
    }

    num_calls = 0;
    return N;
}


The N ($1 \le N \le 50$) cows in Farmer John's herd look very much alike and are numbered $1 \ldots N$. When Farmer John puts a cow to bed in her stall, he must determine which cow he is putting to bed so he can put her in the correct stall.

Cows are distinguished using P ($1 \le P \le 8$) properties, numbered $1 \ldots P$, each of which has three possible values. For example, the color of a cow's ear tag might be yellow, green, or red. For simplicity, the values of every property are represented as the letters 'X', 'Y', and 'Z'. Any pair of Farmer John's cows will differ in at least one property.

Write a program that, given the properties of the cows in Farmer John's herd, helps Farmer John determine which cow he is putting to bed. Your program can ask Farmer John no more than 100 questions of the form: Is the cow's value for some property $T$ in some set $S$?

Try to ask as few questions as possible to determine the cow.

Interaction

The first line of the input file contains two space-separated integers, $N$ and $P$.

Each of the next $N$ lines describes a cow's properties using $P$ space-separated letters. The first letter on each line is the value of property 1, and so on. The second line in the input file describes cow 1, the third line describes cow 2, etc. The question/answer phase takes place via standard input and standard output.

Your program asks a question about the cow being put to bed by writing to standard output a line that is a 'Q' followed by a space, the property number, a space, and a spaceseparated set of one or more values. For example, "Q 1 Z Y" means "Does property 1 have value either 'Z' or 'Y' for the cow being put to bed?". The property must be an integer in the range $1 \ldots P$. All values must be 'X', 'Y', or 'Z' and no value should be listed more than once for a single question.

After asking each question your program asks, read a single line containing a single integer. The integer $1$ means the value of the specified property of the cow being put to bed is in the set of values given; the integer $0$ means it is not.

The program's last line of output should be a 'C' followed by a space and a single integer that specifies the cow that your program has determined Farmer John is putting to bed.

Scoring

Correctness: 30% of points

Programs will receive full score on correctness only if the cow specified is the only cow that is consistent with the answers given. A program that asks more than 100 questions for a test case will receive no points for that test case.

Question count: 70% of points

The remaining points will be determined by the number of questions required to correctly determine the cow. The test cases are designed to reward minimizing the worst-case question count. Partial credit will be given for near-optimal question counts.

Example

Input

```
4 2
X Z
X Y
Y X
Y Y

0

1
```

Output

```
Q 1 X Z

Q 2 Y

C 4
```

// IOI03_D (guess) - Guess Which Cow Interactor
#include <bits/stdc++.h>
using namespace std;

int N, P;
int target;  // target cow (1-indexed)
vector<vector<char>> cows;
int queries = 0;
int MAX_QUERIES;

void finish(int code, const char* msg) {
    fprintf(stderr, "%s\n", msg);
    FILE* tout = fopen("tout.txt", "w");
    if (tout) {
        fprintf(tout, "queries=%d\n", queries);
        fprintf(tout, "query_limit=%d\n", MAX_QUERIES);
        fclose(tout);
    }
    exit(code);
}

int main(int argc, char* argv[]) {
    if (argc < 3) {
        finish(2, "Usage: interactor <input_file> <answer_file>");
    }

    // Read input
    FILE* fin = fopen(argv[1], "r");
    if (!fin) finish(2, "Cannot open input file");

    fscanf(fin, "%d %d", &N, &P);
    cows.resize(N, vector<char>(P));

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < P; j++) {
            char c;
            fscanf(fin, " %c", &c);
            cows[i][j] = c;
        }
    }
    fclose(fin);

    // Read answer (target cow)
    FILE* fans = fopen(argv[2], "r");
    if (!fans) finish(2, "Cannot open answer file");
    fscanf(fans, "%d", &target);
    fclose(fans);

    // Query limit based on problem constraints
    MAX_QUERIES = 3 * N;

    // Send N and P to solver
    printf("%d %d\n", N, P);
    // Send cow properties
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < P; j++) {
            printf("%c%c", cows[i][j], j == P-1 ? '\n' : ' ');
        }
    }
    fflush(stdout);

    char cmd[10];
    while (scanf("%s", cmd) == 1) {
        if (cmd[0] == 'Q') {
            int prop;
            scanf("%d", &prop);

            queries++;
            if (queries > MAX_QUERIES) {
                finish(1, "WA: Query limit exceeded");
            }

            if (prop < 1 || prop > P) {
                finish(1, "WA: Invalid property");
            }

            // Read values until newline
            set<char> values;
            char c;
            while ((c = getchar()) != '\n' && c != EOF) {
                if (c != ' ') values.insert(c);
            }

            // Check if target cow's property is in values
            char target_val = cows[target - 1][prop - 1];
            printf("%d\n", values.count(target_val) ? 1 : 0);
            fflush(stdout);

        } else if (cmd[0] == 'C') {
            int guess;
            scanf("%d", &guess);

            if (guess == target) {
                finish(0, "OK");
            } else {
                finish(1, "WA: Wrong cow");
            }
        } else {
            finish(2, "PE: Unknown command");
        }
    }

    finish(2, "PE: No guess provided");
    return 0;
}

// IOI03_D (guess) - Guess Which Cow Interactor
#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static int queries = 0;
static int query_limit = 0;

void log_metrics() {
    tout << "queries=" << queries << endl;
    tout << "query_limit=" << query_limit << endl;
}

void finish(TResult verdict, const string& msg) {
    log_metrics();
    quitf(verdict, "%s", msg.c_str());
}

int read_target_from_ans(const string& in_path) {
    string ans_path = in_path;
    size_t pos = ans_path.rfind(".in");
    if (pos != string::npos) {
        ans_path.replace(pos, 3, ".out");
    }
    ifstream ans(ans_path);
    int target = 1;
    if (ans) ans >> target;
    return target;
}

int main(int argc, char* argv[]) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    int target = read_target_from_ans(argv[1]);

    int N = inf.readInt();
    int P = inf.readInt();

    vector<vector<char>> cows(N, vector<char>(P));
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < P; j++) {
            cows[i][j] = inf.readChar();
            if (cows[i][j] == ' ' || cows[i][j] == '\n') {
                j--;
                continue;
            }
        }
    }

    query_limit = 3 * N;
    log_metrics();

    cout << N << " " << P << endl;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < P; j++) {
            cout << cows[i][j] << (j == P-1 ? '\n' : ' ');
        }
    }
    cout.flush();

    string cmd;
    while (cin >> cmd) {
        if (cmd == "Q") {
            int prop;
            if (!(cin >> prop)) {
                finish(_wa, "EOF after Q");
            }

            queries++;
            if (queries > query_limit) {
                finish(_wa, "Query limit exceeded");
            }

            if (prop < 1 || prop > P) {
                finish(_wa, "Invalid property index");
            }

            string line;
            getline(cin, line);
            set<char> values;
            for (char c : line) {
                if (c != ' ') values.insert(c);
            }

            char target_val = cows[target - 1][prop - 1];
            cout << (values.count(target_val) ? 1 : 0) << endl;
            cout.flush();

        } else if (cmd == "C") {
            int guess;
            if (!(cin >> guess)) {
                finish(_wa, "EOF after C");
            }

            if (guess == target) {
                finish(_ok, "Correct");
            } else {
                finish(_wa, "Wrong cow");
            }
        } else {
            finish(_pe, "Unknown command");
        }
    }

    finish(_pe, "No guess provided");
    return 0;
}


Mirko is a big fan of crop circles, geometrical formations of flattened crops that are supposedly of alien origin.

One summer night he decided to make his own formation on his grandmother's meadow. The great patriot that he is, Mirko decided to make a crop formation that would have the shape of the shield part of the Croatian coat of arms, which is a $5 \times 5$ chessboard with $13$ red squares and $12$ white squares.

![](https://ioi.contest.codeforces.com/espresso/08818a0e55bc586b67034b4c4fa314f49d8f0e57.png)

The chessboard part of the Croatian coat of arms. Grandma's meadow is a square divided into $N \times N$ cells. The cell in the lower left corner of the meadow is represented by the coordinates $(1, 1)$ and the cell in the upper right corner is represented by $(N, N)$.

Mirko decided to flatten only the grass belonging to red squares in the chessboard, leaving the rest of the grass intact. He picked an odd integer $M \ge 3$ and flattened the grass so that each square of the chessboard comprises $M \times M$ cells in the meadow, and the chessboard completely fits inside the meadow.

![](https://ioi.contest.codeforces.com/espresso/6856cf1ac83cbecbb3180c112fd11dedcc5d750e.png)

Example meadow and Mirko's crop formation, with $N = 19$ and $M = 3$. Cells with flattened grass are shown in gray. The center of the formation is at $(12, 9)$ and is marked with a black point.

After Mirko went to sleep, his peculiar creation drew the attention of real aliens! They are floating high above the meadow in their spaceship and examining Mirko's crop formation with a simple device. This device can only determine whether the grass in a particular cell is flattened or not.

The aliens have found one cell with flattened grass and now they want to find the center cell of Mirko's masterpiece, so that they may marvel at its beauty. They do not know the size $M$ of each square in Mirko's formation.

Write a program that, given the size $N$ of the meadow, the coordinates $(X_0, Y_0)$ of one cell with flattened grass, and the ability to interact with the alien device, finds the coordinates of the center cell of Mirko's crop formation.

The device may be used at most $300$ times in one test run.

Interaction

This is an interactive task. Your program sends commands to the alien device using the standard output, and receives feedback from the device by reading from the standard input.

* At the beginning of your program, you should read three integers $N$, $X_0$ and $Y_0$ from the standard input, separated by single spaces. The number $N$ ($15 \le N \le 2\,000\,000\,000$) is the size of the meadow, while $(X_0, Y_0)$ are the coordinates of one cell with flattened grass.
* To examine the grass in the cell $(X, Y)$ using the alien device, you should output a line of the form "examine X Y" to the standard output. If the coordinates $(X, Y)$ are not inside the meadow (the conditions $1 \le X \le N$ and $1 \le Y \le N$ are not satisfied), or if you use this facility more than $300$ times, your program will receive a score of zero on that test run.
* The alien device will respond with a single line containing the word "true" if the grass in cell $(X, Y)$ is flattened and the word "false" otherwise.
* When your program has found the center cell, it should output a line of the form "solution $X_C$ $Y_C$" to the standard output, where $(X_C, Y_C)$ are the coordinates of the center cell.

In order to interact properly with the grader, your program needs to flush the standard output after every write operation.

Scoring

In test cases worth a total of $40$ points, the size $M$ of each of Mirko's squares will be at most $100$. Each test run will have a unique correct answer that will not depend on the questions asked by your program.

Example

Input

```
19 7 4

true

false

false

true
```

Output

```
examine 11 2

examine 2 5

examine 9 14

examine 18 3

solution 12 9
```

// IOI07_A (aliens) - Interactor
// Check if point is inside circle
#include <bits/stdc++.h>
using namespace std;

int N, R;
int cx, cy;  // circle center
int known_x, known_y;  // known flattened point
int queries = 0;
const int MAX_QUERIES = 300;

void finish(int code, const char* msg) {
    fprintf(stderr, "%s\n", msg);
    FILE* tout = fopen("tout.txt", "w");
    if (tout) {
        fprintf(tout, "queries=%d\n", queries);
        fprintf(tout, "query_limit=%d\n", MAX_QUERIES);
        fclose(tout);
    }
    exit(code);
}

bool inside_circle(int x, int y) {
    long long dx = x - cx;
    long long dy = y - cy;
    return dx * dx + dy * dy <= (long long)R * R;
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        finish(2, "Usage: interactor <input_file>");
    }

    FILE* fin = fopen(argv[1], "r");
    if (!fin) {
        finish(2, "Cannot open input file");
    }

    fscanf(fin, "%d %d", &N, &R);
    fscanf(fin, "%d %d", &cx, &cy);
    fscanf(fin, "%d %d", &known_x, &known_y);
    fclose(fin);

    // Send initial info: N, known_x, known_y
    printf("%d %d %d\n", N, known_x, known_y);
    fflush(stdout);

    char cmd[20];
    while (scanf("%s", cmd) == 1) {
        if (strcmp(cmd, "examine") == 0) {
            int x, y;
            if (scanf("%d %d", &x, &y) != 2) {
                finish(2, "PE: Invalid examine format");
            }

            queries++;
            if (queries > MAX_QUERIES) {
                finish(1, "WA: Query limit exceeded");
            }

            if (x < 1 || x > N || y < 1 || y > N) {
                finish(1, "WA: Point out of bounds");
            }

            printf("%s\n", inside_circle(x, y) ? "true" : "false");
            fflush(stdout);

        } else if (strcmp(cmd, "solution") == 0) {
            int sx, sy;
            if (scanf("%d %d", &sx, &sy) != 2) {
                finish(2, "PE: Invalid solution format");
            }

            if (sx == cx && sy == cy) {
                finish(0, "OK");
            } else {
                finish(1, "WA: Wrong center");
            }
        } else {
            finish(2, "PE: Unknown command");
        }
    }

    finish(2, "PE: No solution provided");
    return 0;
}

// IOI07_A (aliens) - Croatian Coat of Arms Interactor
#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static int queries = 0;
static int query_limit = 300;
static long long N, M, cx, cy;

void log_metrics() {
    tout << "queries=" << queries << endl;
    tout << "query_limit=" << query_limit << endl;
}

void finish(TResult verdict, const string& msg) {
    log_metrics();
    quitf(verdict, "%s", msg.c_str());
}

bool is_flattened(long long x, long long y) {
    // Check if (x,y) is within the 5x5 chessboard pattern centered at (cx,cy)
    // Each square is M×M, total size is 5M×5M
    long long half = (5 * M) / 2;  // 2.5 * M, but M is odd so 5M is odd

    // Bounds of the chessboard
    long long left = cx - half;
    long long right = cx + half;
    long long bottom = cy - half;
    long long top = cy + half;

    if (x < left || x > right || y < bottom || y > top) {
        return false;
    }

    // Determine which square (i, j) the point is in (0-indexed, 0-4)
    // Square (0,0) is bottom-left, (4,4) is top-right
    long long dx = x - left;
    long long dy = y - bottom;
    int i = dx / M;  // column (0-4)
    int j = dy / M;  // row (0-4)

    if (i < 0 || i > 4 || j < 0 || j > 4) {
        return false;
    }

    // Red squares: (i + j) % 2 == 0
    // Pattern (j from top to bottom, i from left to right):
    // R W R W R  (j=4)
    // W R W R W  (j=3)
    // R W R W R  (j=2)
    // W R W R W  (j=1)
    // R W R W R  (j=0)
    return (i + j) % 2 == 0;
}

int main(int argc, char* argv[]) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    N = inf.readLong();
    M = inf.readLong();
    long long x0 = inf.readLong();
    long long y0 = inf.readLong();
    cx = inf.readLong();
    cy = inf.readLong();

    log_metrics();

    cout << N << " " << x0 << " " << y0 << endl;
    cout.flush();

    string cmd;
    while (cin >> cmd) {
        if (cmd == "examine") {
            long long x, y;
            if (!(cin >> x >> y)) {
                finish(_pe, "Invalid examine format");
            }

            queries++;
            if (queries > query_limit) {
                finish(_wa, "Query limit exceeded");
            }

            if (x < 1 || x > N || y < 1 || y > N) {
                finish(_wa, "Point out of bounds");
            }

            cout << (is_flattened(x, y) ? "true" : "false") << endl;
            cout.flush();

        } else if (cmd == "solution") {
            long long sx, sy;
            if (!(cin >> sx >> sy)) {
                finish(_pe, "Invalid solution format");
            }

            if (sx == cx && sy == cy) {
                finish(_ok, "Correct");
            } else {
                finish(_wa, "Wrong center");
            }
        } else {
            finish(_pe, "Unknown command");
        }
    }

    finish(_pe, "No solution provided");
    return 0;
}


The Big Prize is a famous TV game show. You are the lucky contestant who has advanced to the final round. You are standing in front of a row of $n$ boxes, labeled $0$ through $n - 1$ from left to right. Each box contains a prize that cannot be seen until the box is opened. There are $v \geq 2$ different types of prizes. The types are numbered from $1$ to $v$ in decreasing order of value.

The prize of type $1$ is the most expensive one: a diamond. There is exactly one diamond in the boxes. The prize of type $v$ is the cheapest one: a lollipop. To make the game more exciting, the number of cheaper prizes is much larger than the number of more expensive ones. More specifically, for all $t$ such that $2 \leq t \leq v$ we know the following: if there are $k$ prizes of type $t - 1$, there are strictly more than $k^2$ prizes of type $t$.

Your goal is to win the diamond. At the end of the game you will have to open a box and you will receive the prize it contains. Before having to choose the box to open you get to ask Rambod, the host of the game show, some questions. For each question, you choose some box $i$. As his answer, Rambod will give you an array $a$ containing two integers. Their meaning is as follows:

* Among the boxes to the left of box $i$ there are exactly $a[0]$ boxes that contain a more expensive prize than the one in box $i$.
* Among the boxes to the right of box $i$ there are exactly $a[1]$ boxes that contain a more expensive prize than the one in box $i$.

For instance, suppose that $n = 8$. For your question, you choose the box $i = 2$. As his response, Rambod tells you that $a = [1, 2]$. The meaning of this response is:

* Exactly one of the boxes $0$ and $1$ contains a prize more expensive than the one in box $2$.
* Exactly two of the boxes $3, 4, \ldots, 7$ contain a prize more expensive than the one in box $2$.

Your task is to find the box containing the diamond by asking a small number of questions.

Implementation details

You should implement the following procedure:

* int find\_best(int n)
  + This procedure is called exactly once by the grader.
  + $n$: the number of boxes.
  + The procedure should return the label of the box which contains the diamond, i.e., the unique integer $d$ ($0 \leq d \leq n - 1$) such that box $d$ contains a prize of type $1$.

The above procedure can make calls to the following procedure:

* int[] ask(int i)
  + $i$: label of the box that you choose to ask about. The value of $i$ must be between $0$ and $n - 1$, inclusive.
  + This procedure returns the array $a$ with 2 elements. Here, $a[0]$ is the number of more expensive prizes in the boxes to the left of box $i$ and $a[1]$ is the number of more expensive prizes in the boxes to the right of box $i$.

Input

The sample grader is not adaptive. Instead, it just reads and uses a fixed array $p$ of prize types. For all $0 \leq b \leq n - 1$, the type of the prize in box $b$ is given as $p[b]$. The sample grader expects input in the following format:

* line 1: $n$ ($3 \leq n \leq 200\,000$)
* line 2: $p[0], p[1], \ldots, p[n - 1]$

The type of the prize in each box is between $1$ and $v$, inclusive.

There is exactly one prize of type $1$.

For all $2 \le t \le v$, if there are $k$ prizes of type $t - 1$, there are strictly more than $k ^ 2$ prizes of type $t$.

Output

The sample grader prints a single line containing the return value of find\_best and the number of calls to the procedure ask.

Scoring

In some test cases the behavior of the grader is adaptive. This means that in these test cases the grader does not have a fixed sequence of prizes. Instead, the answers given by the grader may depend on the questions asked by your solution. It is guaranteed that the grader answers in such a way that after each answer there is at least one sequence of prizes consistent with all the answers given so far.

|  |  |  |
| --- | --- | --- |
| Subtask | Points | Additional Input Constraints |
| 1 | 20 | There is exactly 1 diamond and $n - 1$ lollipops (hence, $v = 2$). You can call the procedure ask at most $10\,000$ times |
| 2 | 80 | No additional constraints |

In subtask 2 you can obtain a partial score. Let $q$ be the maximum number of calls to the procedure ask among all test cases in this subtask. Then, your score for this subtask is calculated according to the following table:

|  |  |
| --- | --- |
| Questions | Score |
| $10\,000 \textless q$ | $0$ (reported in CMS as 'Wrong Answer') |
| $6000 \textless q \leq 10\,000$ | $70$ |
| $5000 \textless q \leq 6000$ | $80 - (q-5000)/100$ |
| $q \leq 5000$ | $80$ |

Note

The grader makes the following procedure call:

find\_best(8)

There are $n = 8$ boxes. Suppose the prize types are $[3,2,3,1,3,3,2,3]$. All possible calls to the procedure 'ask' and the corresponding return values are listed below.

* 'ask(0)' returns $[0, 3]$
* 'ask(1)' returns $[0, 1]$
* 'ask(2)' returns $[1, 2]$
* 'ask(3)' returns $[0, 0]$
* 'ask(4)' returns $[2, 1]$
* 'ask(5)' returns $[2, 1]$
* 'ask(6)' returns $[1, 0]$
* 'ask(7)' returns $[3, 0]$

In this example, the diamond is in box $3$. So the procedure find\_best should return $3$.

![](https://ioi.contest.codeforces.com/espresso/d687edca56d5f86f2c4caa309615bf72cc5ce0dc.png)

The above figure illustrates this example. The upper part shows the types of the prizes in each box. The lower part illustrates the query ask(2). The marked boxes contain more expensive prizes than the one in box $2$.

#include "prize.h"

#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <cassert>

using namespace std;

static FILE *fin;
static FILE *fout;

vector<int> ask(int i) {
    fprintf(fout, "A %d\n", i);
    fflush(fout);
    vector<int> result(2);
    if (fscanf(fin, "%d %d", &result[0], &result[1]) != 2) {
        cerr << "tester error" << endl;
        cerr << "could not read query response" << endl;
        exit(0);
    }
    if (result[0] < 0) {
        exit(0);
    }
    return result;
}

int main(int argc, char **argv) {
    if(argc!=3) {
        cerr << "grader error" << endl;
        cerr << "number of argument isn't 3" << endl;
        exit(0);
    }
    fin = fopen(argv[1], "r11");
    fout = fopen(argv[2], "a");

    int n;
    if (fscanf(fin, "%d", &n) != 1) {
        cerr << "tester error" << endl;
        cerr << "could not read 'n'" << endl;
        exit(0);
    }

    int result = find_best(n);
    fprintf(fout, "B %d\n", result);
    fflush(fout);
    return 0;
}

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <set>
#include <cmath>

using namespace std;

#define forv(i, v) for (int i=0; i<int((v).size()); i++)
#define X first
#define Y second
#define MP make_pair

typedef pair<int,int> pii;
FILE *fin;
FILE *fout;

vector<pair<int,pii> > queries;
int n, answer=-1;
const int maxq=10000, maxgen=5;

struct ManagerStrategy {
    virtual void read_input(istream& in)=0;
    virtual pii ask(int index)=0;
    virtual bool isBest(int index)=0;
    virtual vector<int> get_levels()=0;
} *strategy;

inline void finish() {
  cout << n << " " << queries.size() << " " << answer << endl;
  vector<int> levels = strategy->get_levels();
  forv(i, levels)
    cout << (i>0?" ":"") << levels[i];
  cout << endl;
  forv(i, queries)
    cout << queries[i].X << " " << queries[i].Y.X << " " << queries[i].Y.Y << endl;
  cout.flush();
}

inline void doubleWrite(string code, string msg) {
  cout << code << endl << msg << endl;
#ifdef ERRLOG
  cerr << code << endl << msg << endl;
#endif
}

inline void die(string code, string msg, bool sendDie) {
    if (sendDie) {
      fprintf(fout, "%d %d\n", -1, -1);
      fflush(fout);
    }
    doubleWrite(code, msg);
    finish();
    exit(0);
}

const string OK ="OK";
const string WA = "WA";
const string FAIL = "FAIL";

inline int readValidIndex(string cmd, bool sendDie) {
    int index;
    if (fscanf(fin, "%d", &index) != 1) {
      die(WA, "io error, could not read index", sendDie);
    }
#ifdef ERRLOG
    cerr << cmd << " " << index << endl;
#endif
    if (index < 0 || index>=n) {
        die(WA, "invalid index" , sendDie);
    }
    return index;
}

struct ManagerStrategy_Plain : public ManagerStrategy {
    vector<int> g;
    vector<vector<int> > rank_count;

    virtual void read_input(istream& cin) {
      cin >> n ;

        g.resize(n);
        for (int i = 0; i < n; i++) {
            cin >> g[i];
        }

        int max_rank = *max_element(g.begin(), g.end());
        rank_count.resize(max_rank + 1, vector<int>(n + 1, 0));
        for (int r = 0; r <= max_rank; r++) {
            for (int i = 1; i <= n; i++) {
                rank_count[r][i] = rank_count[r][i - 1] + int(g[i - 1] == r);
            }
        }

        for (int i = 0; i <= n; i++) {
            for (int r = 1; r <= max_rank; r++) {
                rank_count[r][i] += rank_count[r - 1][i];
            }
        }
    }
    virtual pii ask(int i) {
        pii result;
        result.first = rank_count[g[i] - 1][i + 1];
        result.second = rank_count[g[i] - 1][n] - result.first;
        return result;
    }
    virtual bool isBest(int index) {
        return g[index] == 1;
    }
    virtual vector<int> get_levels(){
        return g;
    }
};

struct ManagerStrategy_Adversary : public ManagerStrategy {
  int max_rank;
  vector<int>num;
  set<int>s[maxgen+1];
  vector<vector<int> >t;
  virtual void read_input(istream& cin) {
      cin >> n >> max_rank;
      num.resize(max_rank+1, 0);
        for (int i = 1; i <=max_rank ; i++){
	  cin>>num[i];
	  num[i]+=num[i-1];
	}
      t.resize(max_rank + 1, vector<int>(n + 2, 0));
      for(int i=2;i<=max_rank;i++){
	s[i].insert(0);
	s[i].insert(num[i]+1);
	t[i][num[i]+1]=num[i]-num[i-1]+1;
      }
    }
    virtual pii ask(int x) {
      x++;
      for(int i = max_rank; i > 1; i--)
	{
	  set<int>:: iterator it = s[i].lower_bound(x);
	  int r = (*it);
	  int l = (*(--it));
	  if(r == x) return pii(x-t[i][x], num[i-1]-(x-t[i][x]));
	  if(t[i][r] > t[i][l] + 1) {
	      s[i].insert(x);
	      if(r-l-2==0) t[i][x] = t[i][l] + 1;
	      else t[i][x] = t[i][l] + 1 + round(((double)t[i][r]-t[i][l]-2)*(x-l-1)/(r-l-2));
	      return pii(x-t[i][x], num[i-1]-(x-t[i][x]));
	    }
	  else {
	    x -= t[i][l];
	  }
	}
      return pii(0,0);
    }
    virtual bool isBest(int index) {
      pii tmp = ask(index);
      return (tmp.X + tmp.Y == 0);
    }
    virtual vector<int> get_levels(){
      vector<int> ret;
      ret.resize(n);
      for(int i=0;i<n;i++)
	{
	  pii tmp=ask(i);
	  for(int j=1;j<=max_rank;j++)
	    if(tmp.X+tmp.Y==num[j-1])
	      ret[i]=j;
	}
      return ret;
    }
};

struct ManagerStrategy_AdversaryRandom : public ManagerStrategy {
  int max_rank;
  vector<int>num, tmp_place;
  set<int>s[maxgen+1];
  vector<vector<int> >t, here;
  vector<pii> g;
  virtual void read_input(istream& cin) {
      int seed_rand;
      cin>>seed_rand;
      srand(seed_rand);
      cin >> n >> max_rank;
      g.resize(n+1,pii(-1,-1));
      num.resize(max_rank+1, 0);
        for (int i = 1; i <=max_rank ; i++){
	  cin>>num[i];
	  num[i]+=num[i-1];
	}
      t.resize(max_rank + 1, vector<int>(n + 2, 0));
      here.resize(max_rank + 1, vector<int>(n + 2, 0));
      for(int i=2;i<=max_rank;i++){
	s[i].insert(0);
	s[i].insert(num[i]+1);
	t[i][num[i]+1]=num[i]-num[i-1];
      }
    }
    virtual pii ask(int x) {
      x++;
      //cout<<x<<": ";
      int index=x;
      if(g[x]!=pii(-1,-1)) return g[x];
      tmp_place.clear();
      for(int i = max_rank; i > 1; i--)
	{
	  set<int>:: iterator it = s[i].lower_bound(x);
	  int r = (*it);
	  int l = (*(--it));
	  int p = rand() % (r-l-1);
	  if(t[i][r] > t[i][l] + here[i][l] && p<t[i][r]-t[i][l]-here[i][l]) {
	      s[i].insert(x);
	      if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	      else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - 1 - here[i][l]) * (x - l - 1) / (r - l - 2));
	      g[index] = pii(x-t[i][x]-1, num[i-1]-(x-t[i][x]-1));
	      here[i][x] = 1;
	      // cout<<g[index].X<<"--1--"<<g[index].Y<<endl;
	      return g[index];
	    }
	  else {
	    tmp_place.push_back(x);
	    s[i].insert(x);
	    if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	    else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - here[i][l]) * (x - l - 1) / (r - l - 2));
	    x -= t[i][x];
	  }
	}
      for(int i = 0;i<(int)tmp_place.size();i++)
	  s[max_rank-i].erase(tmp_place[i]);
      x=index;
      for(int i = max_rank; i > 1; i--)
	{
	  set<int>:: iterator it = s[i].lower_bound(x);
	  int r = (*it);
	  int l = (*(--it));
	  if(t[i][r] > t[i][l] + here[i][l]) {
	    s[i].insert(x);
	    if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	    else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - 1 - here[i][l]) * (x - l - 1) / (r - l - 2));
	    g[index] = pii(x-t[i][x]-1, num[i-1]-(x-t[i][x]-1));
	    here[i][x] = 1;
	    //cout<<g[index].X<<"--2--"<<g[index].Y<<endl;
	    return g[index];
	  }
	  else {
	    s[i].insert(x);
	    if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	    else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - here[i][l]) * (x - l - 1) / (r - l - 2));
	    x -= t[i][x];
	  }
	}
      g[index] = pii(0, 0);
      //cout<<g[index].X<<"--3--"<<g[index].Y<<endl;
      return g[index];
    }
    virtual bool isBest(int index) {
      pii tmp = ask(index);
      return (tmp.X + tmp.Y == 0);
    }
    virtual vector<int> get_levels(){
      vector<int> ret;
      ret.resize(n);
      for(int i=0;i<n;i++)
	{
	  pii tmp=ask(i);
	  for(int j=1;j<=max_rank;j++)
	    if(tmp.X+tmp.Y==num[j-1])
	      ret[i]=j;
	}
      return ret;
    }
};

struct ManagerStrategy_AdversaryAntiRandom : public ManagerStrategy {
  int max_rank;
  vector<int>num, tmp_place;
  set<int>s[maxgen+1];
  vector<vector<int> >t, here;
  vector<pii> g;
  virtual void read_input(istream& cin) {
      cin >> n >> max_rank;
      g.resize(n+1,pii(-1,-1));
      num.resize(max_rank+1, 0);
        for (int i = 1; i <=max_rank ; i++){
	  cin>>num[i];
	  num[i]+=num[i-1];
	}
      t.resize(max_rank + 1, vector<int>(n + 2, 0));
      here.resize(max_rank + 1, vector<int>(n + 2, 0));
      for(int i=2;i<=max_rank;i++){
	s[i].insert(0);
	s[i].insert(num[i]+1);
	t[i][num[i]+1]=num[i]-num[i-1];
      }
    }
    virtual pii ask(int x) {
      x++;
      int index=x;
      if(g[x]!=pii(-1,-1)) return g[x];
      tmp_place.clear();
      for(int i = max_rank; i > 1; i--)
	{
	  set<int>:: iterator it = s[i].lower_bound(x);
	  int r = (*it);
	  int l = (*(--it));
	  int p = 0;
	  if(i == max_rank)
	    p = r-l-2;
	  if(t[i][r] > t[i][l] + here[i][l] && p<t[i][r]-t[i][l]-here[i][l]) {
	      s[i].insert(x);
	      if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	      else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - 1 - here[i][l]) * (x - l - 1) / (r - l - 2));
	      g[index] = pii(x-t[i][x]-1, num[i-1]-(x-t[i][x]-1));
	      here[i][x] = 1;
	      return g[index];
	    }
	  else {
	    tmp_place.push_back(x);
	    s[i].insert(x);
	    if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	    else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - here[i][l]) * (x - l - 1) / (r - l - 2));
	    x -= t[i][x];
	  }
	}
      for(int i = 0;i<(int)tmp_place.size();i++)
	  s[max_rank-i].erase(tmp_place[i]);
      x=index;
      for(int i = max_rank; i > 1; i--)
	{
	  set<int>:: iterator it = s[i].lower_bound(x);
	  int r = (*it);
	  int l = (*(--it));
	  if(t[i][r] > t[i][l] + here[i][l]) {
	    s[i].insert(x);
	    if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	    else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - 1 - here[i][l]) * (x - l - 1) / (r - l - 2));
	    g[index] = pii(x-t[i][x]-1, num[i-1]-(x-t[i][x]-1));
	    here[i][x] = 1;
	    return g[index];
	  }
	  else {
	    s[i].insert(x);
	    if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];
	    else t[i][x] = t[i][l] + here[i][l] + round(((double)t[i][r] - t[i][l] - here[i][l]) * (x - l - 1) / (r - l - 2));
	    x -= t[i][x];
	  }
	}
      g[index] = pii(0, 0);
      return g[index];
    }
    virtual bool isBest(int index) {
      pii tmp = ask(index);
      return (tmp.X + tmp.Y == 0);
    }
    virtual vector<int> get_levels(){
      vector<int> ret;
      ret.resize(n);
      for(int i=0;i<n;i++)
	{
	  pii tmp=ask(i);
	  for(int j=1;j<=max_rank;j++)
	    if(tmp.X+tmp.Y==num[j-1])
	      ret[i]=j;
	}
      return ret;
    }
};

struct ManagerStrategy_AdversaryBetterAntiRandom : public ManagerStrategy {
  int max_rank, num[6],sumnum[6];
  vector<pii>g;
  vector<int>gen2,vec,mark;
  vector<vector<int> >t;
  set<int>s[maxgen+1];
  virtual void read_input(istream& cin) {
    int seed_rand;
    cin>>seed_rand;
    srand(seed_rand);
    cin >> n >> max_rank;
    for(int i=1;i<=max_rank;i++){
      cin>>num[i];
      sumnum[i]=sumnum[i-1]+num[i];
    }
    mark.resize(n,-1);
    g.resize(n,pii(-1,-1));
    while(vec.size()<sumnum[max_rank-2])
      {
	int tmp=rand()%n;
	if(mark[tmp] == -1){
	  mark[tmp]=0;
	  vec.push_back(tmp);
	}
      }
    sort(vec.begin(),vec.end());
    for(int i=0;i<vec.size();i++) mark[vec[i]]=i+1;
    t.resize(max_rank - 1, vector<int>(sumnum[max_rank-2] + 2, 0));
    for(int i=2;i<=max_rank-2;i++){
      s[i].insert(0);
      s[i].insert(sumnum[i]+1);
      t[i][sumnum[i]+1]=num[i]+1;
    }
  }
  virtual pii ask(int x) {
    if(g[x].X!=-1) return g[x];
    int index = x;

    if(mark[x] != -1){
      x = mark[x];
      for(int i = max_rank-2; i > 1; i--)
	{
	  set<int>:: iterator it = s[i].lower_bound(x);
	  int r = (*it);
	  int l = (*(--it));
	  if(r == x) return pii(x-t[i][x], sumnum[i-1]-(x-t[i][x]));
	  if(t[i][r] > t[i][l] + 1) {
	      s[i].insert(x);
	      if(r-l-2==0) t[i][x] = t[i][l] + 1;
	      else t[i][x] = t[i][l] + 1 + round(((double)t[i][r]-t[i][l]-2)*(x-l-1)/(r-l-2));
	      return g[index] = pii(x-t[i][x], sumnum[i-1]-(x-t[i][x]));
	    }
	  else {
	    x -= t[i][l];
	  }
	}
      return g[index] = pii(0,0);
    }

    if(gen2.size()<num[max_rank-1]){
      gen2.push_back(x);
      if(gen2.size() == num[max_rank-1]) sort(gen2.begin(),gen2.end());
      int less_than = lower_bound(vec.begin(),vec.end(),x) - vec.begin();
      return g[x]=pii(less_than, sumnum[max_rank-2] - less_than);
    }

    int tmp = lower_bound(gen2.begin(),gen2.end(),x)-gen2.begin();
    tmp += lower_bound(vec.begin(),vec.end(),x) - vec.begin();
    return g[x]=pii(tmp, sumnum[max_rank-1]-tmp);
  }
  virtual bool isBest(int index) {
    pii tmp = ask(index);
    return (tmp.X + tmp.Y == 0);
  }
  virtual vector<int> get_levels(){
    vector<int> ret;
    ret.resize(n);
    for(int i=0;i<n;i++)
      {
	pii tmp=ask(i);
	for(int j=1;j<=max_rank;j++)
	  if(tmp.X+tmp.Y==sumnum[j-1])
	    ret[i]=j;
      }
    return ret;
  }
};

int main(int argc, char **argv) {
    fout = fopen(argv[2], "a");
    fin = fopen(argv[1], "r");

    string subtask_type, strategy_type;
    cin >> subtask_type >> strategy_type;
    if (strategy_type == "plain") {
        strategy = new ManagerStrategy_Plain();
    } else if (strategy_type == "adversary") {
        strategy = new ManagerStrategy_Adversary();
    } else if (strategy_type == "adversary_random") {
        strategy = new ManagerStrategy_AdversaryRandom();
    } else if (strategy_type == "adversary_antirandom") {
        strategy = new ManagerStrategy_AdversaryAntiRandom();
    } else if (strategy_type == "adversary_betterantirandom") {
        strategy = new ManagerStrategy_AdversaryBetterAntiRandom();
    } else {
        doubleWrite(FAIL, "invalid strategy type: "+strategy_type);
        exit(0);
    }

    strategy->read_input(cin);

    fprintf(fout, "%d\n", n);
    fflush(fout);

    int qcount = 0;
    while (true) {
        char tmp[1000];
        if (fscanf(fin, "%999s", tmp) != 1) {
	  die(WA, "io error, could not read command", false);
        }
        string cmd(tmp);
        if (cmd=="A") {//query
	  int index = readValidIndex("A",true);
            qcount++;
            if (qcount>maxq) {
	      die(WA, "query limit exceeded", true);
            }
            pii ans = strategy->ask(index);
            fprintf(fout, "%d %d\n", ans.first, ans.second);
            fflush(fout);
#ifdef ERRLOG
	    cerr << ans.first << " " << ans.second << endl;
#endif
	    queries.push_back(MP(index,ans) );
        } else if (cmd=="B") {//answer
	  int index = readValidIndex("B",false);
	    answer = index;
            bool ok = strategy->isBest(index);
            if (ok) {
	        cout << OK << endl;
#ifdef ERRLOG
                cerr << OK << endl;
#endif
	    } else {
	        doubleWrite(WA, "answer is not correct");
            }
	    finish();
            exit(0);
        } else {
	  die(WA, "io error, invalid command", false);
        }
    }
    return 0;
}

#include <vector>

int find_best(int n);
std::vector<int> ask(int i);

prize

The Big Prize

Frogs, The Big Prize