Aisha and Basma are two friends who correspond with each other. Aisha has a message $M$, which is a sequence of $S$ bits (i.e., zeroes or ones), that she would like to send to Basma. Aisha communicates with Basma by sending her packets. A packet is a sequence of $31$ bits indexed from $0$ to $30$. Aisha would like to send the message $M$ to Basma by sending her some number of packets.

Unfortunately, Cleopatra compromised the communication between Aisha and Basma and is able to taint the packets. That is, in each packet Cleopatra can modify bits on exactly $15$ indices. Specifically, there is an array $C$ of length $31$, in which every element is either $0$ or $1$, with the following meaning:

* $C[i] = 1$ indicates that the bit with index $i$ can be changed by Cleopatra. We call these indices controlled by Cleopatra.
* $C[i] = 0$ indicates that bit with index $i$ cannot be changed by Cleopatra.

The array $C$ contains precisely $15$ ones and $16$ zeroes. While sending the message $M$ , the set of indices controlled by Cleopatra stays the same for all packets. Aisha knows precisely which $15$ indices are controlled by Cleopatra. Basma only knows that $15$ indices are controlled by Cleopatra, but she does not know which indices.

Let $A$ be a packet that Aisha decides to send (which we call the original packet). Let $B$ be the packet that is received by Basma (which we call the tainted packet). For each $i$, such that $0 \le i < 31$:

* if Cleopatra does not control the bit with index $i$ ($C[i] = 0$), Basma receives bit $i$ as sent by Aisha ($B[i] = A[i]$),
* otherwise, if Cleopatra controls the bit with index $i$ ($C[i] = 1$), the value of $B[i]$ is decided by Cleopatra.

Immediately after sending each packet, Aisha learns what the corresponding tainted packet is.

After Aisha sends all the packets, Basma receives all the tainted packets in the order they were sent and has to reconstruct the original message $M$.

Your task is to devise and implement a strategy that would allow Aisha to send the message $M$ to Basma, so that Basma can recover $M$ from the tainted packets. Specifically, you should implement two procedures. The first procedure performs the actions of Aisha. It is given a message $M$ and the array $C$, and should send some packets to transfer the message to Basma. The second procedure performs the actions of Basma. It is given the tainted packets and should recover the original message $M$.

Implementation Details

The first procedure you should implement is:

void send\_message(std::vector<bool> M, std::vector<bool> C)

* $M$: an array of length $S$ describing the message that Aisha wants to send to Basma.
* $C$: an array of length $31$ indicating the indices of bits controlled by Cleopatra.
* This procedure may be called at most 2100 times in each test case.

This procedure should call the following procedure to send a packet:

std::vector<bool> send\_packet(std::vector<bool> A)

* $A$: an original packet (an array of length $31$) representing the bits sent by Aisha.
* This procedure returns a tainted packet $B$ representing the bits that will be received by Basma.
* This procedure can be called at most $100$ times in each invocation of send\_message.

The second procedure you should implement is:

std::vector<bool> receive\_message(std::vector<std::vector<bool» R)

* $R$: an array describing the tainted packets. The packets originate from packets sent by Aisha in one send\_message call and are given in the order they were sent by Aisha. Each element of $R$ is an array of length $31$, representing a tainted packet.
* This procedure should return an array of $S$ bits that is equal to the original message $M$.
* This procedure may be called multiple times in each test case, exactly once for each corresponding send\_message call. The order of receive\_message procedure calls is not necessarily the same as the order of the corresponding send\_message calls.

Note that in the grading system the send\_message and receive\_message procedures are called in two separate programs.

Input

The sample grader is not adaptive. Instead, Cleopatra fills consecutive bits she controls with alternating $0$ and $1$ bits, as described in the example above.

The first line of the input contains an integer $T$, specifying the number of scenarios. $T$ scenarios follow. Each of them is provided in the following format:

* line $1$: $S$ ($1\le S \le 1024$)
* line $2$: $M[0]\; M[1]\ldots M[S-1]$
* line $3$: $C[0]\; C[1]\ldots C[30]$

$C$ has exactly $31$ elements, out of which $16$ are equal to $0$ and $15$ are equal to $1$.

Output

The sample grader writes the result of each of the $T$ scenarios in the same order as they are provided in the input in the following format:

* line $1$: $K$ $L$
* line $2$: $D[0]\; D[1]\; \ldots D[L-1]$

Here, $K$ is the number of calls to send\_packet, $D$ is the message returned by receive\_message and $L$ is its length.

Scoring

If in any of the test cases, the calls to the procedure send\_packet do not conform to the rules mentioned above, or the return value of any of the calls to procedure receive\_message is incorrect, the score of your solution for that test case will be $0$.

Otherwise, let $Q$ be the maximum number of calls to the procedure send\_packet among all invocations of send\_message over all test cases. Also let $X$ be equal to:

* 1, if $Q \le 66$
* $0.95^{Q-66}$, if $66 < Q \le 100$

Then, the score is calculated as follows:

|  |  |  |
| --- | --- | --- |
| Subtask | Score | Additional Constraints |
| 1 | $10 \cdot X$ | $S \le 64$ |
| 2 | $90 \cdot X$ | No additional constraints. |

Note that in some cases the behaviour of the grader can be adaptive. This means that the values returned by send\_packet may depend not just on its input arguments but also on many other things, including the inputs and return values of the prior calls to this procedure and pseudo- random numbers generated by the grader. The grader is deterministic in the sense that if you run it twice and in both runs you send the same packets, it will make the same changes to them.

Note

Consider the following call.

```
send_message([0, 1, 1, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
```

The message that Aisha tries to send to Basma is $[0,\; 1,\; 1,\; 0]$. The bits with indices from $0$ to $15$ cannot be changed by Cleopatra, while the bits with indices from $16$ to $30$ can be changed by Cleopatra.

For the sake of this example, let us assume that Cleopatra fills consecutive bits she controls with alternating $0$ and $1$, i.e. she assigns $0$ to the first index she controls (index $16$ in our case), $1$ to the second index she controls (index $17$), $0$ to the third index she controls (index $18$), and so on.

Aisha can decide to send two bits from the original message in one packet as follows: she will send the first bit at the first $8$ indices she controls and the second bit at the following $8$ indices she controls.

Aisha then chooses to send the following packet:

```
send_packet([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
```

Note that Cleopatra can change bits with the last $15$ indices, so Aisha can set them arbitrarily, as they might be overwritten. With the assumed strategy of Cleopatra, the procedure returns: $[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]$. Aisha decides to send the last two bits of $M$ in the second packet in a similar way as before:

```
send_packet([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
```

With the assumed strategy of Cleopatra, the procedure returns: [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0].

Aisha can send more packets, but she chooses not to.

The grader then makes the following procedure call:

```
receive_message([[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
                  0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
                 [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
                  0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]])
```

Basma recovers message $M$ as follows. From each packet she takes the first bit that occurs twice in a row, and the last bit that occurs twice in a row. That is, from the first packet, she takes bits $[0,\; 1]$, and from the second packet she takes bits $[1,\; 0]$. By putting them together, she recovers the message $[0,\; 1,\; 1,\; 0]$, which is the correct return value for this call to receive\_message.

It can be shown that with the assumed strategy of Cleopatra and for messages of length $4$, this approach of Basma correctly recovers $M$, regardless of the value of $C$. However, it is not correct in the general case.

#include "testlib.h"
#include <csignal>
#include <random>

using namespace std;

/******************************** Begin testlib-related material ********************************/

inline FILE* openFile(const char* name, const char* mode) {
	FILE* file = fopen(name, mode);
	if (!file)
		quitf(_fail, "Could not open file '%s' with mode '%s'.", name, mode);
	closeOnHalt(file);
	return file;
}

vector<FILE*> mgr2sol, sol2mgr;
FILE* log_file = nullptr;

void nullifyFile(int idx) {
	mgr2sol[idx] = sol2mgr[idx] = nullptr;
}

#ifdef __GNUC__
__attribute__ ((format (printf, 1, 2)))
#endif
void log_printf(const char* fmt, ...) {
	if (log_file) {
		FMT_TO_RESULT(fmt, fmt, message);
		fprintf(log_file, "%s", message.c_str());
		fflush(log_file);
	}
}

void registerManager(std::string probName, int num_processes, int argc, char* argv[]) {
	setName("manager for problem %s", probName.c_str());
	__testlib_ensuresPreconditions();
	testlibMode = _checker;
	random_t::version = 1; // Random generator version
	__testlib_set_binary(stdin);
	ouf.mode = _output;

	{//Keep alive on broken pipes
		//signal(SIGPIPE, SIG_IGN);
		struct sigaction sa;
		sa.sa_handler = SIG_IGN;
		sigaction(SIGPIPE, &sa, NULL);
	}

	int required_args = 1 + 2 * num_processes;
	if (argc < required_args || required_args+1 < argc) {
		string usage = format("'%s'", argv[0]);
		for (int i = 0; i < num_processes; i++)
			usage += format(" sol%d-to-mgr mgr-to-sol%d", i, i);
		usage += " [mgr_log] < input-file";
		quitf(_fail,
			"Manager for problem %s:\n"
			"Invalid number of arguments: %d\n"
			"Usage: %s",
			probName.c_str(), argc-1, usage.c_str());
	}

	inf.init(stdin, _input);
	closeOnHalt(stdout);
	closeOnHalt(stderr);

	mgr2sol.resize(num_processes);
	sol2mgr.resize(num_processes);
	for (int i = 0; i < num_processes; i++) {
		mgr2sol[i] = openFile(argv[1 + 2*i + 1], "a");
		sol2mgr[i] = openFile(argv[1 + 2*i + 0], "r");
	}

	if (argc > required_args) {
		log_file = openFile(argv[required_args], "w");
	} else {
		log_file = nullptr;
	}
}
/********************************* End testlib-related material *********************************/

// utils

#define rep(i, n) for(int i = 0, i##__n = (int)(n); i < i##__n; ++i)

template<class C> int sz(const C& c) { return std::size(c); }

// grader/manager protocol

const int secret_g2m = 0x647FB390;
const int secret_m2g = 0xB107D5C0;
const int code_mask  = 0x0000000F;

const int M2G_CODE__OK = 0;
const int M2G_CODE__DIE = 1;

const int G2M_CODE__OK = 0;
const int G2M_CODE__OK_END_OF_PACKETS = 1;
const int G2M_CODE__PACKET_SIZE_INCORRECT = 2;
const int G2M_CODE__RETURN_MESSAGE_TOO_LARGE = 3;
const int G2M_CODE__PV_CALL_EXIT = 13;
const int G2M_CODE__PV_TAMPER_M2G = 14;
const int G2M_CODE__SILENT = 15;

int fifo_idx = 0;
bool mode_end_of_packets;

void out_flush() {
	fflush(mgr2sol[fifo_idx]);
}

void write_int(int x) {
	FILE* fout = mgr2sol[fifo_idx];
	if (1 != fwrite(&x, sizeof(x), 1, fout)) {
		nullifyFile(fifo_idx);
		log_printf("Could not write int to mgr2sol[%d]\n", fifo_idx);
	}
}

void write_int_array(const int* arr, int len) {
	FILE* fout = mgr2sol[fifo_idx];
	if (int ret = fwrite(arr, sizeof(int), len, fout); len != ret) {
		nullifyFile(fifo_idx);
		log_printf("Could not write int array of size %d to mgr2sol[%d], fwrite returned %d\n", len, fifo_idx, ret);
	}
}

void write_int_vector(const vector<int>& v) {
	write_int_array(v.data(), sz(v));
}

void write_secret(int m2g_code = M2G_CODE__OK) {
	write_int(secret_m2g | m2g_code);
}

#ifdef __GNUC__
__attribute__ ((format (printf, 2, 3)))
#endif
NORETURN void die(TResult result, const char* format, ...) {
	FMT_TO_RESULT(format, format, message);
	log_printf("Dying with message '%s'\n", message.c_str());
	rep(i, sz(mgr2sol))
		if(mgr2sol[i] != nullptr) {
			fifo_idx = i;
			log_printf("Sending secret with code DIE to mgr2sol[%d]\n", fifo_idx);
			write_secret(M2G_CODE__DIE);
			out_flush();
		}
	log_printf("Quitting with result code %d\n", int(result));
	quit(result, message);
}

NORETURN void die_invalid_argument(const string &msg) {
	RESULT_MESSAGE_WRONG += ": Invalid argument";
	die(_wa, "%s", msg.c_str());
}

NORETURN void die_too_many_calls(const string &msg) {
	RESULT_MESSAGE_WRONG += ": Too many calls";
	die(_wa, "%s", msg.c_str());
}

int read_int() {
	FILE* fin = sol2mgr[fifo_idx];
	int x;
	if (1 != fread(&x, sizeof(x), 1, fin)) {
		nullifyFile(fifo_idx);
		die(_fail, "Could not read int from sol2mgr[%d]", fifo_idx);
	}
	return x;
}

void read_int_array(int* arr, int len) {
	FILE* fin = sol2mgr[fifo_idx];
	if (int ret = fread(arr, sizeof(int), len, fin); len != ret) {
		nullifyFile(fifo_idx);
		die(_fail, "Could not read int array of size %d from sol2mgr[%d], fread returned %d", len, fifo_idx, ret);
	}
}

void read_secret() {
	int secret = read_int();
	if((secret & ~code_mask) != secret_g2m)
		die(_pv, "Possible tampering with sol2mgr[%d]", fifo_idx);
	int g2m_code = secret & code_mask;
	mode_end_of_packets = false;
	switch (g2m_code) {
		case G2M_CODE__OK:
			return;
		case G2M_CODE__OK_END_OF_PACKETS:
			mode_end_of_packets = true;
			return;
		case G2M_CODE__SILENT:
			die(_fail, "Unexpected g2m_code SILENT from sol2mgr[%d]", fifo_idx);
		case G2M_CODE__PV_TAMPER_M2G:
			die(_pv, "Possible tampering with mgr2sol[%d]", fifo_idx);
		case G2M_CODE__PV_CALL_EXIT:
			die(_pv, "Solution[%d] called exit()", fifo_idx);
		case G2M_CODE__PACKET_SIZE_INCORRECT:
			die_invalid_argument("Packet size is incorrect");
		case G2M_CODE__RETURN_MESSAGE_TOO_LARGE:
			die(_wa, "Returned message's length is too large.");
		default:
			die(_fail, "Unknown g2m_code %d from sol2mgr[%d]", g2m_code, fifo_idx);
	}
}

const int PACKET_SIZE = 31;
const int CALLS_CNT_LIMIT = 100;

//mt19937 rng(15061994);
//auto rnd1 =  bind(uniform_int_distribution<int>(0, (1 << 1) - 1), rng);
//auto rnd4 =  bind(uniform_int_distribution<int>(0, (1 << 4) - 1), rng);
//auto rnd31 = bind(uniform_int_distribution<int>(0, (1U << 31) - 1), rng);
int used_days, max_used_days = 0;

int compressed_len(int len) { return (len+31) / 32; }

string vi2binStr(const vector<int>& arr, int len) {
	string str(len, '*');
	rep(i, len) str[i] = (arr[i / 32] >> (i & 31) & 1) + '0';
	return str;
}

enum Strategy {
	BEGIN,
	kExampleStrategy,
	kRandom,
	kJustOnes,
	kJustZeroes,
	kMimicAllButOneRound0,
	kMimicAllButOneRound1,
	kMimicAllButOneRound2,
	kMimicAllButOneRound3,
	kMimicAllButOneRound4,
	kInvertAllButOneRound0,
	kInvertAllButOneRound1,
	kInvertAllButOneRound2,
	kInvertAllButOneRound3,
	kInvertAllButOneRound4,
	kMinimizeDiffOfZeroesAndOnes,
	kEchoPreviousResponses,
	kEchoPreviousResponsesShuffled,
	kSame,
	kFlip,
	kMimicClosestOnLeft,
	kMimicClosestOnRight,
	END
};

struct BaseTestCase {
	const int S;
	const vector<int> M_f;
	const int C_f;
};

struct EncoderTestCase {
	const BaseTestCase *base;
	Strategy strategy;
};

struct DecoderTestCase {
	const BaseTestCase *base;
	vector<int> R_f;
};

vector<BaseTestCase> ReadBaseTestCases() {
	int T = inf.readInt();
	vector<BaseTestCase> base_tests;
	for(int _ = 0; _ < T; _++) {
		int S = inf.readInt();
		vector<int> M_f(compressed_len(S), 0);
		for(int i = 0; i < S; i++) {
			int bit = inf.readInt(0, 1);
			M_f[i / 32] |= bit << (i & 31);
		}

		int C_f = 0;
		for(int i = 0; i < PACKET_SIZE; i++) {
			int ally = inf.readInt(0, PACKET_SIZE-1);
			C_f |= ally << i;
		}

		base_tests.push_back(BaseTestCase{
				.S = S,
				.M_f = M_f,
				.C_f = C_f});
	}
	fclose(stdin);
	return base_tests;
}

vector<EncoderTestCase> GenerateEncoderTests(const vector<BaseTestCase> &base_tests) {
	vector<EncoderTestCase> encoder_tests;
	if(base_tests.size() <= 3) { // This is the example test
		for(const auto &base_test : base_tests)
			encoder_tests.push_back(EncoderTestCase{
					.base = &base_test,
					.strategy = Strategy::kExampleStrategy});
	}
	else {
		for(const auto &base_test : base_tests)
			for(int strategy = Strategy::BEGIN + 1; strategy < Strategy::END; strategy++)
				encoder_tests.push_back(EncoderTestCase{
						.base = &base_test,
						.strategy = static_cast<Strategy>(strategy)});
	}

	shuffle(encoder_tests.begin(), encoder_tests.end());
	return encoder_tests;
}

void setbit(int &x, int i, int b) { b == 1 ? x |= (1 << i) : x &= ~(1 << i); }

int ApplyStrategy(const Strategy strategy, const int C_f, int used_days,
		const vector<int>& previous_answers, const vector<int>& who_to_mimic,
		const vector<int>& non_mimic_index, int x) {
	if(strategy == Strategy::kExampleStrategy) {
		int bit = 0;
		for(int i = 0; i < PACKET_SIZE; i++)
			if(C_f >> i & 1) {
				setbit(x, i, bit);
				bit ^= 1;
			}
		return x;
	}

	if(strategy == Strategy::kSame)
		return x;
	if(strategy == Strategy::kFlip)
		return x ^ C_f;
	if(strategy == Strategy::kMimicClosestOnLeft) {
		int st = __builtin_ctz(~C_f);
		int pbit = (x >> st) & 1;
		for(int dis = 1; dis < PACKET_SIZE; dis++) {
			int i = (st + dis) % PACKET_SIZE;
			if(C_f >> i & 1)
				setbit(x, i, pbit);
			pbit = (x >> i) & 1;
		}
		return x;
	}
	if(strategy == Strategy::kMimicClosestOnRight) {
		int st = __builtin_ctz(~C_f);
		int pbit = (x >> st) & 1;
		for(int dis = 1; dis < PACKET_SIZE; dis++) {
			int i = (st - dis + PACKET_SIZE) % PACKET_SIZE;
			if(C_f >> i & 1)
				setbit(x, i, pbit);
			pbit = (x >> i) & 1;
		}
		return x;
	}

	if(strategy == Strategy::kRandom)
		return x ^ (rnd.next(0U, (1U << 31) - 1) & C_f);
	if(strategy == Strategy::kJustOnes)
		return x | C_f;
	if(strategy == Strategy::kJustZeroes)
		return x & ~C_f;

	vector<char> their_choices;
	for(int i = 0; i < PACKET_SIZE; i++)
		if(!(C_f >> i & 1))
			their_choices.push_back(x >> i & 1);

	if(kMimicAllButOneRound0 <= strategy and strategy <= kInvertAllButOneRound4) {
		int id = strategy - kMimicAllButOneRound0;
		if(kInvertAllButOneRound0 <= strategy)
			id = strategy - kInvertAllButOneRound0;
		if(used_days == non_mimic_index[id]) {
			for(int i = 0; i < PACKET_SIZE; i++)
				if(C_f >> i & 1) {
					if(kMimicAllButOneRound0 <= strategy and strategy <= kMimicAllButOneRound4)
						setbit(x, i, x >> who_to_mimic[i] & 1);
					else
						setbit(x, i, (x >> who_to_mimic[i] & 1) ^ 1);
				}
			return x;
		}
		else
			return x ^ (rnd.next(0U, (1U << 31) - 1) & C_f);
	}

	if(strategy == Strategy::kMinimizeDiffOfZeroesAndOnes) {
		int zeroes_count = 0, ones_count = 0;
		for(int previous_answer: previous_answers) {
			for(int i = 0; i < PACKET_SIZE; i++)
				if((previous_answer >> i & 1) == 0)
					zeroes_count++;
				else
					ones_count++;
		}
		for(int i = 0; i < PACKET_SIZE; i++) {
			if(!(C_f >> i & 1)) {
				if((x >> i & 1) == 0)
					zeroes_count++;
				else
					ones_count++;
			}
		}
		vector<int> my_choices;
		for(int i = 0; i < (PACKET_SIZE - 1) / 2; i++) {
			int choice = rnd.next(0, 1);
			if(zeroes_count > ones_count)
				choice = 1;
			if(zeroes_count < ones_count)
				choice = 0;
			if(choice == 0)
				zeroes_count++;
			if(choice == 1)
				ones_count++;
			my_choices.push_back(choice);
		}
		shuffle(my_choices.begin(), my_choices.end());
		int ix = 0;
		for(int i = 0; i < PACKET_SIZE; i++)
			if(C_f >> i & 1)
				setbit(x, i, my_choices[ix++]);
		return x;
	}

	if(strategy == Strategy::kEchoPreviousResponses or
			strategy == Strategy::kEchoPreviousResponsesShuffled) {
		if(used_days == 1) {
			for(int i = 0; i < PACKET_SIZE; i++)
				if(C_f >> i & 1)
					setbit(x, i, rnd.next(0, 1));
		}
		else {
			int previous_response = previous_answers.back();
			vector<int> my_response;
			for(int i = 0; i < PACKET_SIZE; i++)
				if(!(C_f >> i & 1))
					my_response.push_back(previous_response >> i & 1);
			if(strategy == Strategy::kEchoPreviousResponsesShuffled)
				shuffle(my_response.begin(), my_response.end());
			int ix = 0;
			for(int i = 0; i < PACKET_SIZE; i++)
				if(C_f >> i & 1)
					setbit(x, i, my_response[ix++]);
		}
		return x;
	}

	die(_fail, "Unknown strategy!");
}

vector<int> CalculateMimicyMap(int C_f) {
	vector<int> their_indices;
	for(int i = 0; i < PACKET_SIZE; i++) {
		if(!(C_f >> i & 1))
			their_indices.push_back(i);
	}
//	shuffle(their_indices.begin(), their_indices.end(), rng);
	their_indices.erase(their_indices.begin() + rnd.next(16));

	vector<int> who_to_mimic(PACKET_SIZE, -1);
	int ix = 0;
	for(int i = 0; i < PACKET_SIZE; i++)
		if(C_f >> i & 1)
			who_to_mimic[i] = their_indices[ix++];
	return who_to_mimic;
}

vector<DecoderTestCase> RunEncoder(vector<EncoderTestCase> &encoder_tests) {
	int test_cases = encoder_tests.size();

	vector<DecoderTestCase> decoder_tests;

	for(int _ = 0; _ < test_cases; _++) {
		const EncoderTestCase &test = encoder_tests[_];

		write_secret();
		write_int(test.base->S);
		write_int_vector(test.base->M_f);
		write_int(test.base->C_f);
		out_flush();

		auto who_to_mimic = CalculateMimicyMap(test.base->C_f);
		vector<int> non_mimic_index(5);
		non_mimic_index[1] = rnd.next(0, 7);
		non_mimic_index[0] = rnd.next(8, 19);
		non_mimic_index[2] = rnd.next(20, 44);
		non_mimic_index[3] = rnd.next(45, 66);
		non_mimic_index[4] = rnd.next(67, 100);

		used_days = 0;
		vector<int> R_f;
		while(true) {
			read_secret();
			if(mode_end_of_packets == true) break;

			int A_f = read_int();

			if(++used_days > CALLS_CNT_LIMIT)
				die_too_many_calls("Used too many days");

			int B_f = ApplyStrategy(test.strategy, test.base->C_f, used_days, R_f, who_to_mimic, non_mimic_index, A_f);

			ensuref(((B_f ^ A_f) | test.base->C_f) == test.base->C_f, "ApplyStrategy should not edit uncontrolled bits");

			R_f.push_back(B_f);

			write_secret();
			write_int(B_f);
			out_flush();
		}
		decoder_tests.push_back(DecoderTestCase{
				.base = test.base,
				.R_f = R_f,
				});
		max_used_days = max(max_used_days, used_days);
	}

	write_secret();
	write_int(-1);
	out_flush();

	return decoder_tests;
}

void RunDecoder(const vector<DecoderTestCase> &decoder_tests) {
	int test_cases = decoder_tests.size();
	for(int _ = 0; _ < test_cases; _++) {
		const DecoderTestCase &test = decoder_tests[_];

		write_secret();
		write_int(sz(test.R_f));
		write_int_vector(test.R_f);
		out_flush();

		read_secret();
		int L = read_int();
		vector<int> D_f(compressed_len(L), 0);
		read_int_array(D_f.data(), sz(D_f));

		if(L != test.base->S || D_f != test.base->M_f) {
			log_printf(
					"WA:\n"
					"original message:\n"
					"'%s'\n"
					"decoded message:\n"
					"'%s'\n",
					vi2binStr(test.base->M_f, test.base->S).c_str(),
					vi2binStr(D_f, L).c_str());
	       	die(_wa, "decoded message is incorrect");
		}
	}

	write_secret();
	write_int(-1);
	out_flush();
}

int main(int argc, char **argv) {
	registerManager("message", 2, argc, argv);

	fifo_idx = 0; // Mode: Encoder
	vector<BaseTestCase> base_tests = ReadBaseTestCases();
	vector<EncoderTestCase> encoder_tests = GenerateEncoderTests(base_tests);
	vector<DecoderTestCase> decoder_tests = RunEncoder(encoder_tests);
	nullifyFile(fifo_idx);

	shuffle(decoder_tests.begin(), decoder_tests.end());

	fifo_idx = 1; // Mode: Decoder
	RunDecoder(decoder_tests);
	nullifyFile(fifo_idx);

	// scoring
	const int days_threshold = 66;
	if(max_used_days <= days_threshold)
		quitf(_ok, "Used %d days", max_used_days);
	else if(max_used_days <= CALLS_CNT_LIMIT)
		quitp(pow(0.95, max_used_days - days_threshold), "Used %d days", max_used_days);

	die(_fail, "Reached an unreachable code!!!");

	return 0;
}

#include "message.h"
#include <csignal>
#include <cstdlib>
#include <cstdio>
#include <string>

using namespace std;

namespace {

/******************************** Begin testlib-related material ********************************/
#ifdef _MSC_VER
#   define NORETURN __declspec(noreturn)
#elif defined __GNUC__
#   define NORETURN __attribute__ ((noreturn))
#else
#   define NORETURN
#endif
/********************************* End testlib-related material *********************************/

// utils

#define rep(i, n) for(int i = 0, i##__n = (int)(n); i < i##__n; ++i)

template<class C> int sz(const C& c) { return std::size(c); }

// grader/manager protocol

const int secret_g2m = 0x647FB390;
const int secret_m2g = 0xB107D5C0;
const int code_mask  = 0x0000000F;

const int M2G_CODE__OK = 0;

const int G2M_CODE__OK = 0;
const int G2M_CODE__OK_END_OF_PACKETS = 1;
const int G2M_CODE__PACKET_SIZE_INCORRECT = 2;
const int G2M_CODE__RETURN_MESSAGE_TOO_LARGE = 3;
const int G2M_CODE__PV_CALL_EXIT = 13;
const int G2M_CODE__PV_TAMPER_M2G = 14;
const int G2M_CODE__SILENT = 15;

bool exit_allowed = false;

NORETURN void authorized_exit(int exit_code) {
  exit_allowed = true;
  exit(exit_code);
}

FILE* fin = stdin;
FILE* fout = stdout;

void out_flush() {
	fflush(fout);
}

void write_int(int x) {
	if (1 != fwrite(&x, sizeof(x), 1, fout)) {
		fprintf(stderr, "Could not write int to fout\n");
		authorized_exit(3);
	}
}

void write_int_array(const int* arr, int len) {
	if (int ret = fwrite(arr, sizeof(int), len, fout); len != ret) {
		fprintf(stderr, "Could not write int array of size %d to fout, fwrite returned %d\n", len, ret);
		authorized_exit(3);
	}
}

void write_secret(int g2m_code = G2M_CODE__OK) {
	write_int(secret_g2m | g2m_code);
}

NORETURN void die(int g2m_code) {
	if(g2m_code == G2M_CODE__OK) {
		fprintf(stderr, "Shall not die with code OK\n");
		authorized_exit(5);
	}
	fprintf(stderr, "Dying with code %d\n", g2m_code);
	if(g2m_code != G2M_CODE__SILENT)
		write_secret(g2m_code);
	fclose(fin);
	fclose(fout);
	authorized_exit(0);
}

int read_int() {
	int x;
	if (1 != fread(&x, sizeof(x), 1, fin)) {
		fprintf(stderr, "Could not read int from fin\n");
		authorized_exit(3);
	}
	return x;
}

void read_int_array(int* arr, int len) {
	if (int ret = fread(arr, sizeof(int), len, fin); len != ret) {
		fprintf(stderr, "Could not read int array of size %d from fin, fread returned %d\n", len, ret);
		authorized_exit(3);
	}
}

void read_secret() {
	int secret = read_int();
	if((secret & ~code_mask) != secret_m2g)
		die(G2M_CODE__PV_TAMPER_M2G);
	int m2g_code = secret & code_mask;
	if(m2g_code != M2G_CODE__OK)
		die(G2M_CODE__SILENT);
}

void check_exit_protocol() {
  if (!exit_allowed)
    die(G2M_CODE__PV_CALL_EXIT);
}

// problem utils

int vb2int(const vector<bool> &v) {
	int r = 0;
	rep(i, sz(v)) r |= ((v[i] ? 1 : 0) << i);
	return r;
}

vector<bool> int2vb(int x, int len) {
	vector<bool> v(len);
	rep(i, sz(v)) v[i] = (x >> i & 1) ? true : false;
	return v;
}

void arr2vb(int* arr, int len, vector<bool> &r) {
	r.resize(len);
	rep(i, len) r[i] = (arr[i / 32] >> (i & 31) & 1) ? true : false;
}

int compressed_len(int len) { return (len+31) / 32; }

void vb2arr(vector<bool> v, int* arr, int len) {
	len = sz(v);
	rep(i, compressed_len(len)) arr[i] = 0;
	rep(i, len) arr[i / 32] |= (v[i] ? 1 : 0) << (i & 31);
}

// grader logic

const int PACKET_SIZE = 31;
const int MAX_MESSAGE_SIZE = 1024;
const int MESSAGE_SIZE_LIMIT = 2 * MAX_MESSAGE_SIZE;

NORETURN void run_encoder() {
	for(int S; read_secret(), (S = read_int()) != -1; ) {
		int M_f[(MAX_MESSAGE_SIZE + 32 - 1) / 32];
		read_int_array(M_f, compressed_len(S));
		int C_f = read_int();

		vector<bool> M;
		arr2vb(M_f, S, M);
		vector<bool> C = int2vb(C_f, PACKET_SIZE);

		send_message(M, C);

		write_secret(G2M_CODE__OK_END_OF_PACKETS);
		out_flush();
	}
	die(G2M_CODE__SILENT);
}

NORETURN void run_decoder() {
	for(int K; read_secret(), (K = read_int()) != -1; ) {
		vector<int> R_f(K, 0);
		read_int_array(R_f.data(), K);

		vector<vector<bool>> R(K);
		rep(i, K) R[i] = int2vb(R_f[i], PACKET_SIZE);
		vector<bool> D = receive_message(R);
		int L = sz(D);

		if(L < 0 || L > MESSAGE_SIZE_LIMIT) die(G2M_CODE__RETURN_MESSAGE_TOO_LARGE);

		int D_f[(MESSAGE_SIZE_LIMIT + 32 - 1) / 32];
		vb2arr(D, D_f, L);

		write_secret();
		write_int(L);
		write_int_array(D_f, compressed_len(L));
		out_flush();
	}
	die(G2M_CODE__SILENT);
}

} // namespace

vector<bool> send_packet(vector<bool> A) {
	if(sz(A) != PACKET_SIZE) die(G2M_CODE__PACKET_SIZE_INCORRECT);

	int A_f = vb2int(A);

	write_secret();
	write_int(A_f);
	out_flush();

	read_secret();
	int B_f = read_int();
	return int2vb(B_f, PACKET_SIZE);
}

int main(int argc, char **argv) {
	signal(SIGPIPE, SIG_IGN);
	atexit(check_exit_protocol);
	at_quick_exit(check_exit_protocol);

	if(argc < 2) {
		fprintf(stderr, "invalid args\n");
		authorized_exit(1);
	}

	string grader_id = argv[1];
	if (grader_id == "0")
		run_encoder();

	if (grader_id == "1")
		run_decoder();

	fprintf(stderr, "invalid grader id: '%s'\n", grader_id.c_str());
	authorized_exit(1);
}

#include <vector>

void send_message(std::vector<bool> M, std::vector<bool> C);

std::vector<bool> send_packet(std::vector<bool> A);

std::vector<bool> receive_message(std::vector<std::vector<bool>> R);


This problem was reconstructed to fullfill the interactive problem environment. It differs from the judging system that was available on IOI.

We consider a two-player game. The players are given an $x \times y$ rectangle (where $x$ and $y$ are positive integers). The players take turns moving. A move consists of dividing a rectangle into two rectangles with a single vertical or horizontal cut. The resulting rectangles must have positive integer dimensions.

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

After each cut, the smaller rectangle (that is the one with smaller area) is discarded and the other one is passed to the other player. If the rectangle is cut into two equal halves, then one half is discarded. The player who receives a $1 \times 1$ rectangle, and therefore is not able to make a move, loses the game.

Your task is to write a program to play and win the rectangle game. Initial rectangle sizes are from $1$ to $100\,000\,000$. At least on of them is greater than 1.

Interaction

Before first move and after each oponent's move your program will receive two integers on standard input — current rectangle sizes. When game is end, you will receive two -1.

In respond, you should print your move. Move description contains of symbol «H» or «V» and id of horizontal or vertical cut correspondent.

You can assume that for the test data, there always exists a winning strategy for your program.

Scoring

In 50% of test cases, the dimensions do not exceed 25.

Example

Input

```
4 3

3 2

2 1

-1 -1
```

Output

```
V 1

H 1

V 1
```

// IOI05_E (rec) - Rectangle Game Interactor
#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

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

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 main(int argc, char* argv[]) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    inf.readLong();  // seed (unused)
    int x = inf.readInt();
    int y = inf.readInt();

    log_metrics();

    cout << x << " " << y << endl;
    cout.flush();

    while (x > 1 || y > 1) {
        char dir;
        int pos;
        if (!(cin >> dir >> pos)) {
            finish(_pe, "Invalid input format");
        }

        queries++;
        if (queries > query_limit) {
            finish(_wa, "Too many moves");
        }

        if (dir == 'V' || dir == 'v') {
            if (pos <= 0 || pos >= x) {
                finish(_wa, "Invalid vertical cut");
            }
            x = max(pos, x - pos);
        } else if (dir == 'H' || dir == 'h') {
            if (pos <= 0 || pos >= y) {
                finish(_wa, "Invalid horizontal cut");
            }
            y = max(pos, y - pos);
        } else {
            finish(_pe, "Invalid direction");
        }

        cout << x << " " << y << endl;
        cout.flush();
    }

    finish(_ok, "Correct");
    return 0;
}

// IOI05_E (rec) - Rectangle Game Interactor
// Opponent strategy: always keep the larger piece
#include <bits/stdc++.h>
using namespace std;

int x, y;
int moves = 0;
const int MAX_MOVES = 100000;

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

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");
    }

    long long seed;
    fscanf(fin, "%lld %d %d", &seed, &x, &y);
    fclose(fin);

    // Send initial dimensions
    printf("%d %d\n", x, y);
    fflush(stdout);

    while (x > 1 || y > 1) {
        char dir;
        int pos;
        if (scanf(" %c %d", &dir, &pos) != 2) {
            finish(2, "PE: Invalid input format");
        }

        moves++;
        if (moves > MAX_MOVES) {
            finish(1, "WA: Too many moves");
        }

        if (dir == 'V' || dir == 'v') {
            if (pos <= 0 || pos >= x) {
                finish(1, "WA: Invalid vertical cut position");
            }
            x = max(pos, x - pos);
        } else if (dir == 'H' || dir == 'h') {
            if (pos <= 0 || pos >= y) {
                finish(1, "WA: Invalid horizontal cut position");
            }
            y = max(pos, y - pos);
        } else {
            finish(2, "PE: Invalid direction");
        }

        printf("%d %d\n", x, y);
        fflush(stdout);
    }

    finish(0, "OK");
    return 0;
}


In Japan, cities are connected by a network of highways. This network consists of $N$ cities and $M$ highways. Each highway connects a pair of distinct cities. No two highways connect the same pair of cities. Cities are numbered from $0$ through $N-1,$ and highways are numbered from $0$ through $M-1.$ You can drive on any highway in both directions. You can travel from any city to any other city by using the highways.

A toll is charged for driving on each highway. The toll for a highway depends on the traffic condition on the highway. The traffic is either light or heavy. When the traffic is light, the toll is $A$ yen (Japanese currency). When the traffic is heavy, the toll is $B$ yen. It's guaranteed that $A < B.$ Note that you know the values of $A$ and $B.$

You have a machine which, given the traffic conditions of all highways, computes the smallest total toll that one has to pay to travel between the pair of cities $S$ and $T (S \neq T),$ under the specified traffic conditions.

However, the machine is just a prototype. The values of $S$ and $T$ are fixed (i.e., hardcoded in the machine) and not known to you. You would like to determine $S$ and $T.$ In order to do so, you plan to specify several traffic conditions to the machine, and use the toll values that it outputs to deduce $S$ and $T.$ Since specifying the traffic conditions is costly, you don't want to use the machine many times.

Implementation details

You should implement the following procedure:

find\_pair(int N, int[] U, int[] V, int A, int B)

* $N$: the number of cities.
* $U$ and $V$: arrays of length $M,$ where $M$ is the number of highways connecting cities. For each $i : 0 \le i \le M-1,$ the highway $i$ connects the cities $U[i]$ and $V[i].$
* $A$: the toll for a highway when the traffic is light.
* $B$: the toll for a highway when the traffic is heavy.
* This procedure is called exactly once for each test case.
* Note that the value of $M$ is the lengths of the arrays, and can be obtained as indicated in the implementation notice.

int64 ask(int[] w)

* The length of $w$ must be $M.$ The array $w$ describes the traffic conditions.
* For each $i: 0 \le i \le M-1, w[i]$ gives the traffic condition on the highway $i.$ The value of $w[i]$ must be either $0$ or $1.$
  + $w[i] = 0$ means the traffic of the highway $i$ is light.
  + $w[i] = 1$ means the traffic of the highway $i$ is heavy.
* This function returns the smallest total toll for travelling between the cities $S$ and $T,$ under the traffic conditions specified by $w.$
* This function can be called at most $100$ times (for each test case).

find\_pair should call the following procedure to report the answer:

answer(int s, int t)

* s and t must be the pair $S$ and $T$ (the order does not matter).
* This procedure must be called exactly once.

If some of the above conditions are not satisfied, your program is judged as Wrong Answer. Otherwise, your program is judged as Accepted and your score is calculated by the number of calls to ask (see Subtasks).

Constraints

* $2 \le N \le 90\,000$
* $1 \le M \le 130\,000$
* $1 \le A < B \le 1\,000\,000\,000$
* For each $i: 0 \le i M-1$
  + $0 \le U[i] \le N-1$
  + $0 \le V[i] \le N-1$
  + $U[i] \neq V[i]$
* $(U[i], V[i]) \neq (U[j], V[j])$ and $(U[i], V[j]) \neq (V[j], U[j])$ for all $i,j: 0 \le i < j \le M-1$
* You can travel from any city to any other city by using the highways.
* $0 \le S \le N-1$
* $0 \le T \le N-1$
* $S \neq T$

In this problem, the grader is NOT adaptive. This means that $S$ and $T$ are fixed at the beginning of the running of the grader and they do not depend on the queries asked by your solution.

Sample grader

The sample grader reads the input in the following format:

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| line | $1$ | : | $N$ $M$ $A$ $B$ $S$ $T$ |  |
| line | $2+i$ | : | $U[i]$ $V[i]$ | $(0 \le i \le M-1)$ |

If your program is judged as Accepted, the sample grader prints Accepted: q, with $q$ the number of calls to ask.

If your program is judged as Wrong Answer, it prints Wrong Answer: MSG, where MSG is one of:

* answered not exactly once: The procedure answer was not called exactly once.
* w is invalid: The length of $w$ given to ask is not $M$ or $w[i]$ is neither $0$ nor $1$ for some $i: 0 \le i \le M-1.$
* more than 100 calls to ask: The function ask is called more than $100$ times.
* {s, t} is wrong: The procedure answer is called with an incorrect pair $s$ and $t.$

Scoring

Subtasks

|  |  |  |
| --- | --- | --- |
| Subtask | Points (max) | Additional constraints |
| $1$ | $5$ | $M=N-1,$ one of $S$ or $T$ is $0,$ $N \le 100$ |
| $2$ | $7$ | $M=N-1,$ one of $S$ or $T$ is $0$ |
| $3$ | $6$ | $M=N-1,$ $U[i] = i,$ $V[i] = i+1$ for all $i: 0\le i \le M-1$ |
| $4$ | $33$ | $M=N-1$ |
| $5$ | $18$ | $A=1,$ $B=2$ |
| $6$ | $31$ | No |

Assume your program is judged as Accepted, and makes $X$ calls to ask. Then your score for $P$ the test case, depending on its subtask number, is calculated as follows:

|  |  |  |  |
| --- | --- | --- | --- |
| Subtask 1 | $P=5$ |  |  |
| Subtask 2 | If $X \le 60,$ | $P=7.$ | Otherwise $P=0.$ |
| Subtask 3 | If $X \le 60,$ | $P=6.$ | Otherwise $P=0.$ |
| Subtask 4 | If $X \le 60,$ | $P=33.$ | Otherwise $P=0.$ |
| Subtask 5 | If $X \le 52,$ | $P=18.$ | Otherwise $P=0.$ |
| Subtask 6 | If $X \le 50,$ | $P=31.$ | If $51\le X\le 52, P=21.$ |
|  |  |  | Otherwise $P=0.$ |

Note that your score for each subtask is the minimum of the scores for the test cases in the subtask.

Note

Example

Let $N=4,$ $M=4,$ $U=[0,0,0,1],$ $V=[1,2,3,2],$ $A=1,$ $B=3,$ $S=1,$ and $T=3.$

The grader calls find\_pair(4, [0, 0, 0, 1], [1, 2, 3, 2], 1, 3).

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

In the figure above, the edge with number i corresponds to the highway i. Some possible calls to ask and the corresponding return values are listed below:

|  |  |
| --- | --- |
| Call | Return |
| ask([0, 0, 0, 0]) | $2$ |
| ask([0, 1, 1, 0]) | $4$ |
| ask([1, 0, 1, 0]) | $5$ |
| ask([1, 1, 1, 1]) | $6$ |

For the function call ask([0, 0, 0, 0]), the traffic of each highway is light and the toll for each highway is $1.$ The cheapest route from $S=1$ to $T=3$ is $1 \rightarrow 0 \rightarrow 3.$ The total toll for this route is $2.$ Thus, this function returns $2.$

For a correct answer, the procedure find\_pair should call answer(1, 3) or answer(3, 1).

The file sample-01-in.txt in the zipped attachment package corresponds to this example. Other sample inputs are also available in the package.

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <utility>
#include <vector>
#include "highway.h"

namespace {

constexpr int MAX_NUM_CALLS = 100;
constexpr long long INF = 1LL << 61;

int N, M, A, B, S, T;
std::vector<int> U, V;
std::vector<std::vector<std::pair<int, int>>> graph;

bool answered, wrong_pair;
int num_calls;

int read_int() {
  int x;
  if (scanf("%d", &x) != 1) {
    fprintf(stderr, "Error while reading input\n");
    exit(1);
  }
  return x;
}

void wrong_answer(const char *MSG) {
  printf("Wrong Answer: %s\n", MSG);
  exit(0);
}

}  // namespace

long long ask(const std::vector<int> &w) {
  if (++num_calls > MAX_NUM_CALLS) {
    wrong_answer("more than 100 calls to ask");
  }
  if (w.size() != (size_t)M) {
    wrong_answer("w is invalid");
  }
  for (size_t i = 0; i < w.size(); ++i) {
    if (!(w[i] == 0 || w[i] == 1)) {
      wrong_answer("w is invalid");
    }
  }

  std::vector<bool> visited(N, false);
  std::vector<long long> current_dist(N, INF);
  std::queue<int> qa, qb;
  qa.push(S);
  current_dist[S] = 0;
  while (!qa.empty() || !qb.empty()) {
    int v;
    if (qb.empty() ||
        (!qa.empty() && current_dist[qa.front()] <= current_dist[qb.front()])) {
      v = qa.front();
      qa.pop();
    } else {
      v = qb.front();
      qb.pop();
    }
    if (visited[v]) {
      continue;
    }
    visited[v] = true;
    long long d = current_dist[v];
    if (v == T) {
      return d;
    }
    for (auto e : graph[v]) {
      int vv = e.first;
      int ei = e.second;
      if (!visited[vv]) {
        if (w[ei] == 0) {
          if (current_dist[vv] > d + A) {
            current_dist[vv] = d + A;
            qa.push(vv);
          }
        } else {
          if (current_dist[vv] > d + B) {
            current_dist[vv] = d + B;
            qb.push(vv);
          }
        }
      }
    }
  }
  return -1;
}

void answer(int s, int t) {
  if (answered) {
    wrong_answer("answered not exactly once");
  }

  if (!((s == S && t == T) || (s == T && t == S))) {
    wrong_pair = true;
  }

  answered = true;
}

int main() {
  N = read_int();
  M = read_int();
  A = read_int();
  B = read_int();
  S = read_int();
  T = read_int();
  U.resize(M);
  V.resize(M);
  graph.assign(N, std::vector<std::pair<int, int>>());
  for (int i = 0; i < M; ++i) {
    U[i] = read_int();
    V[i] = read_int();
    graph[U[i]].push_back({V[i], i});
    graph[V[i]].push_back({U[i], i});
  }

  answered = false;
  wrong_pair = false;
  num_calls = 0;
  find_pair(N, U, V, A, B);
  if (!answered) {
    wrong_answer("answered not exactly once");
  }
  if (wrong_pair) {
    wrong_answer("{s, t} is wrong");
  }
  printf("Accepted: %d\n", num_calls);
  return 0;
}

#include "highway.h"

void find_pair(int N, std::vector<int> U, std::vector<int> V, int A, int B) {
  int M = U.size();
  for (int j = 0; j < 50; ++j) {
    std::vector<int> w(M);
    for (int i = 0; i < M; ++i) {
      w[i] = 0;
    }
    long long toll = ask(w);
  }
  answer(0, N - 1);
}

#include <vector>

void find_pair(int N, std::vector<int> U, std::vector<int> V, int A, int B);

long long ask(const std::vector<int> &w);
void answer(int s, int t);


You are to write an interactive program that, given a sequence of Wikipedia excerpts (see example below), guesses the language of each, in turn. After each guess, your program is given the correct answer, so that it may learn to make better guesses the longer it plays.

Each language is represented by a number L between $0$ and $55$. Each excerpt has exactly $100$ symbols, represented as an array $E$ of $100$ integers between $1$ and $65\,535$. These integers between $1$ and $65\,535$ have been assigned arbitrarily, and do not correspond to any standard encoding.

You are to implement the procedure excerpt(E) where $E$ is an array of $100$ numbers representing a Wikipedia excerpt as described above. Your implementation must call language(L) once, where $L$ is its guess of the language of the Wikipedia edition from which $E$ was extracted. The grading server implements language(L), which scores your guess and returns the correct language. That is, the guess was correct if language(L) = L.

The grading server calls excerpt(E) $10\,000$ times, once for each excerpt in its input file. Your implementation's accuracy is the fraction of excerpts for which excerpt(E) guessed the correct language.

You may use any method you wish to solve this problem. Rocchio's method is an approach that will yield accuracy of approximately $0.4$. Rocchio's method computes the similarity of $E$ to each language $L$ seen so far, and chooses the language that is most similar. Similarity is defined as the total number of distinct symbols in E that appear anywhere among the previous excerpts from language L.

Note that the input data have been downloaded from real Wikipedia articles, and that there may be a few malformed characters or fragments of text. This is to be expected, and forms part of the task.

For illustration only, we show the textual representation of excerpts from 56 language-specific editions of Wikipedia.

1. Yshokkie word meestal in Kanada , die noorde van die VSA en in Europa gespeel. Dit is bekend as 'n b

2. وهو المنتج الذي يجعل المنظم ال يكسب ربحا وال يخسر ويحصل على ، Producer Marginal المنتج الحدي دخل يكف

3. "BAKILI" Futbol Klubu 1995-ci ildə Misir Səttаr oğlu Əbilov tərəfindən yаrаdılmış və həvəskаr futbol

4. Квинт Фулвий Флак (Quintus Fulvius Flaccus; † 205 пр.н.е. ) e политик и генерал на Римската републик

5. ইন্ডিয়ান ইনস্টিটিউি অফ স ়াশ্য়াল ওযযলযফয়ার অয়াি স্টিজযন ম্য়াযনজযম্ন্ট ( ংযেযে আইআইএ ডস্টিউস্টিএম্ )

6. 5. juni ( lipanj ) ( 5.6. ) je 156. dan godine po gregorijanskom kalendaru (157. u prestupnoj godini

7. La Caunette és un municipi francès , situat al departament de l' Erau i a la regió de Llenguadoc-Ros

8. Praha je malé městečko v Texasu , které leží cca 85 km na jihozápad od Austinu . Bylo založeno

9. Graeme Allen Brown (født 9. april 1979 i Darwin , Northern Territory , Australien ) er en australsk

10. Der Plattiger Habach ( 3.214 m ü. A. , nach anderen Angaben nur 3.207 m [1] )

11. Το Νησί Γκρέιτ Μπάρριερ ( Αγγλικά : Great Barrier Island , Μαορί : Motu Aotea ) είναι νησί στα βόρει

12. Sid Bernstein Presents... is a 2010 feature-length documentary film by directors Jason Ressler and E

13. El término latino lex loci celebrationis aplicado al derecho internacional privado quiere decir: "le

14. Apollo 5 oli kosmoselaev , mis sooritas Apollo programmi teise mehitamata lennu. Lennu käigus testit

15. هزار و سیصد و پنجاهمین سیارک( TAنامگذاری :1934 ، Rosselia به انگلیسی : 1350 (سیارک ۱۳۵۰ کشف شدهاس

16. V. I. Beretti (myös Vikenty Ivanovitš Beretti , alk. Vincent Beretti ; 1781 Milano Italia – 18. elok

17. Le 5 e bataillon de parachutistes vietnamiens (ou 5 e BPVN ou encore 5 e Bawouan ) est une unité par

18. Amina Sarauniyar Zazzau,, wadda ta rayu daga shekarar 1533 zuwa 1610, ɗaya ce daga cikin 'ya'ya biyu

ב מתמטיקה , השערת רימן היא השערה שהציע בשנת 1859 ה מתמטיקאי ברנרד רימן , מגדולי .19 המתמטיקאים של אותה ע

20. Sudski proces Doe protiv Boltona je sudski proces iz 1973 . godine kojim je američki Vrhovni sud uki

21. Owen Cunningham Wilson ( 1968 . november 18. , Dallas , Texas , Egyesült Államok ) amerikai színész

22. Հայ Կաթողիկե Եկեղեցին պատկանում է Արևելյան Կաթոլիկ Եկեղեցիներին և այսպիսով ենթարկվում է Հռոմի Պապի ա

23. Dionysios dari Halicarnassus ( Bahasa Yunani : Διονύσιος Ἀλεξάνδρου Ἀλικαρνᾱσσεύς , Dionysios putra

24. Nnamdi "Zik" Azikiwe , bu onye isi-ala izizi Nijiria nwere. Ochichi ya bidolu na afo 1954 welu ruo n

25. La Riserva naturale orientata Serre della Pizzuta è un'area protetta del dipartimento Regionale di S

26. 石橋和義 （いしばし かずよし/まさよし、生没年不詳）は、 �詳。 石橋氏 初 代当主。初名氏義。 尾張 三郎を通称とし、官途は、 左近将監 → 三河守 → 左 衛門佐 。 足利直義

27. კორბინ ბლიუ ( ინგლ. Corbin Bleu ; დ. 21 თებერვალი , 1989 , დაბადების ადგილი ბრუკლინი , ნიუ-იორკი , ა

28. Та́рья Ка́арина Ха́лонен (Tarja Kaarina Halonen)); 24 желтоқсан , 1943 , Каллио , Хельсинки , Финлан

29. 딜롱 ( Dilong )은 중국 랴오닝(Liaoning) 지방의 익시안층(Yixian Formation)에서 온전한 4구의 화석으로 발견되었다. 이 공룡은 가장 원시적인 초기의 티

30. Сүймөнкул Чокморов - советтик актёр. Жетинин айынын 9 (ноябрь) 1939-жылы, Фрунзе шаарын жанындагы Чо

31. D' Mirjam vun Abellin war eng Nonn a Mystikerin , och " Maria vum gekräizegte Jesus " genannt. Si as

32. Panopea abrupta ( angl. Geoduck ) - jūrinių dvigeldžių moliuskų rūšis, priklausanti Hiatellidae šeim

33. "Dzimis Latvijā" ir Liepājas dueta Fomins & Kleins 2004 . gada 23. februārī izdotais otrais albu

34. I Ludwik Lejzer Zamenhof dia dokotera mpijery maso nipetraka any Polonia . Fantantsika izy ankehitri

35. Седумстотини милиони малечки алвеоли во белите дробови , всушност се шупливи чаури - алвеоли прекрие

36. Энэхүү шувуу нь Бутан , Хятад , Гонконг , Энэтхэг , Пакистан , Иран , Япон , Казакстан , Солонгос ,

37. भारतातील महाराष्ट्रराज्याच्या नागपूर पासुन २१६ कि.मी. दू र असलेलेएि गाव. तेवैनगंगा नदीच्या िाठावर

38. De Slotervaart was oorspronkelijk de waterweg die sinds de Middeleeuwen het dorp Sloten verbond met

39. Macierz S (macierz rozpraszania, od ang. scattering matrix ) jest centralnym elementem w mechanice k

40. A Hora do Rush 3 ( Rush Hour 3 , no original) é o terceiro filme da franquia Rush Hour . Dirigido po

41. Coordonate : 51°34′0″N 12°3′0″E / 51.56667 , 12.05 Brachstedt este o comună din landul Saxonia-A

42. Гробницы императоров династии Мин и Цин — памятник Всемирного наследия ЮНЕСКО , состоящий из несколь

43. Kovalentni radijus atoma - ponekad se naziva i valentni radijus. Kovalentni radijus je srednje rasto

44. Koniecpol je mesto v Poľsku v Sliezskom vojvodstve v okrese Powiat częstochowski v rovnomennej gmine

45. Hoxhë Vokrri vije nga Shqipëria ishte një klerik shqiptar i cili luftonte për Çështjën Kombëtare . A

46. Гурдијеље је насеље у општини Тутин у Рашком округу . Према попису из 2002. било је 93 становника (п

47. Underhållsstöd betalas ut av Försäkringskassan (FK) till en förälder som är vårdnadshavare och bor e

48. இந்தியாவின் தேசிய நநடுஞ்சாலைகள் நடுவண் அரசின் தேசிய நநடுஞ்சாலைே்துலையாை் பராமரிக்கப்படுகின் ைன. நபரு

49. Дар он зиндаги .маишат ,фаолияти мехнати,муборизаи ичтимои, русуму омол, хислат ва эхсосоти халк ифо

50. ไฟทอฟธอรา อินเฟสทันส ( อังกฤษ : Phytophthora infestans ) คอืเชือ้ ราโอโอไมซีท หรือ ราน ้า ที ่ เป็นสาเห

51. ABUL FAWARIS BERRANY - 11. asyrda Orta Aziýadaky oguz taýpalarynyň berrany dinastiýasynyň wekili. Ol

52. Egemenlik ya da hâkimiyet , bir toprak parçası ya da mekan üzerindeki kural koyma gücü ve hukuk yara

53. Темне фентезі (від англ. Dark Fantasy - темне, похмуре фентезі ) - піджанр літератури, який включає

54. Paris By Night 84: In Atlanta - Passport to Music & Fashion (Âm nhạc và Thời trang) là chương tr

55. ISO 3166-2:GU ni akoole ninu ISO 3166-2 , apa opagun ISO 3166 ti International Organization for Stan

56. 下卡姆斯克 （ 俄文 ： Нижнека́мск ； 韃靼語 ： Түбəн Кама/Tübän Kama ）是 俄 羅斯 韃靼斯坦共和國 東北部的一個城市，位於 卡馬河 南岸。 2002年 人口22

The sample input, you can download with grader archive, contains 10 000 such examples. The 56 languages are those listed as "mother tongue" in the IOI 2010 registration data. The language for each excerpt is chosen at random from these 56 languages, and each excerpt is taken from the first paragraph of an article chosen at random from the corresponding Wikipedia edition. Each line of the file contains:

* The two-letter ISO code for the Wikipedia language edition;
* 100 numbers between 1 and 65 535, representing the first 100 symbols, in sequence, of the first paragraph of the article;

The official grader uses 10 000 different excerpts, selected in the same way from the same 56 Wikipedia editions. However, the grader assigns a different number between 0 and 55 to each language, and a different number between 1 and 65 535 to each symbol.

Scoring

Subtask 1 [30 points] Your submission must achieve accuracy of $0.3$ or better on the grading server.

Subtask 2 [up to 80 points] Your score will be $114\cdot (\alpha - 0.3)$, rounded to the nearest integer, where $\alpha$ is the accuracy of your submission.

You would be tested on both example and secret test. You can receive at most $110$ points on secret test. Because of technical reasons, we can't set $0$ points for public test. So, you can receive $0.01$ points for public test. Don't be surprised much by this.

#include "grader.h"
#include "lang.h"

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>

#define N 100

static char lang[20], lan[100][20];
static int lnum, i,j,k,n,nl, uni[N], right, tot;
int language(int L) {
   if (L < 0 || L >= 56) exit(92);
   right += (L == lnum);
   tot++;
   return lnum;
}

int main(){
   for (n=0; 1 == scanf("%s",lang); n++) {
      for (i=0;i<nl && strcmp(lang,lan[i]);i++);
      strcpy(lan[i],lang);
      if (i == nl) {
         nl++;
      }
      lnum = i;
      for (i=0;i<N;i++) scanf("%d,",&uni[i]);
      scanf("%*[^\n]");
      excerpt(uni);
   }
   printf("OK %0.2lf%%\n",100.0*right/tot);
   return 0;
}

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

#include "grader.h"
#include "lang.h"

#define SZ 100

int prev[1100000];

void excerpt(int *E) {
   prev[E[0]] = language(prev[E[0]]);
}


There are $N$ small towns in Kazakhstan, numbered from $0$ through $N - 1$. There is also an unknown number of large cities. The small towns and large cities of Kazakhstan are jointly called settlements.

All the settlements of Kazakhstan are connected by a single network of bidirectional highways. Each highway connects two distinct settlements, and each pair of settlements is directly connected by at most one highway. For each pair of settlements $a$ and $b$ there is a unique way in which one can go from $a$ to $b$ using the highways, as long as no highway is used more than once.

It is known that each small town is directly connected to a single other settlement, and each large city is directly connected to three or more settlements.

The following figure shows a network of 11 small towns and 7 large cities. Small towns are depicted as circles and labeled by integers, large cities are depicted as squares and labeled by letters.

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

Every highway has a positive integer length. The distance between two settlements is the minimum sum of the lengths of the highways one needs to travel in order to get from one settlement to the other.

For each large city $C$ we can measure the distance $r(C)$ to the small town that is the farthest away from that city. A large city $C$ is a hub if the distance $r(C)$ is the smallest among all large cities. The distance between a hub and a small town that is farthest away from the hub will be denoted by $R$. Thus, $R$ is the smallest of all values $r(C)$.

In the above example the farthest small town from city $a$ is town 8, and the distance between them is $r(a) = 1 + 4 + 12 = 17$. For city $g$ we also have $r(g) = 17$. (One of the small towns that are farthest away from $g$ is town 6.) The only hub in the above example is city $f$, with $r(f) = 16$. Hence, in the above example $R$ is 16.

Removing a hub divides the network into multiple connected pieces. A hub is balanced if each of those pieces contains at most $\lfloor \frac{N}{2} \rfloor$ small towns. (We stress that we do not count the large cities.) Note that $\lfloor x \rfloor$ denotes the largest integer which is not greater than $x$.

In our example, city $f$ is a hub. If we remove city $f$, the network will break into four connected pieces. These four pieces consist of the following sets of small towns: {$0, 1, 10$}, {$2, 3$}, {$4,5,6,7$}, and {$8, 9$}. None of these pieces has more than $\lfloor \frac{11}{2} \rfloor = 5$ small towns, hence city $f$ is a balanced hub.

Task

Initially, the only information you have about the network of settlements and highways is the number $N$ of small towns. You do not know the number of large cities. You also do not know anything about the layout of highways in the country. You can only obtain new information by asking queries about distances between pairs of small towns.

Your task is to determine:

* In all subtasks: the distance $R$.
* In subtasks $3$ to $6$: whether there is a balanced hub in the network.

You need to implement the function hubDistance. The grader will evaluate multiple test cases in a single run. The number of test cases per run is at most 40. For each test case the grader will call your function hubDistance exactly once. Make sure that your function initializes all necessary variables every time it is called.

* int hubDistance(int N, int sub)
  + $N$: the number of small towns.
  + $sub$: the subtask number (explained in the Scoring section).
  + If $sub$ is 1 or 2, the function can return either $R$ or $-R$.
  + if $sub$ is greater than 2, if there exists a balanced hub then the function must return $R$, otherwise it must return $-R$.

Your function hubDistance can obtain information about the network of highways by calling the grader function getDistance(i, j). This function returns the distance between the small towns $i$ and $j$. Note that if $i$ and $j$ are equal, the function returns 0. It also returns 0 when the arguments are invalid.

Input

The sample grader reads the input in the following format:

* line 1: Subtask number and the number of test cases.
* line 2: $N_1$, the number of small towns in the first test case.
* following $N_1$ lines: The $j$-th number $(1\le j \le N_1)$ in the $i$-th of these lines $(1 \le i \le N_1)$ is the distance between small towns $i - 1$ and $j - 1$.
* The next test cases follow. They are given in the same format as the first test case.

Output

For each test case, the sample grader prints the return value of hubDistance and the number of calls made on separate lines.

Scoring

In each test case:

* $N$ is between $6$ and $110$ inclusive.
* The distance between any two distinct small towns is between $1$ and $1\,000\,000$ inclusive.

The number of queries your program may make is limited. The limit varies by subtask, as given in the table below. If your program tries to exceed the limit on the number of queries, it will be terminated and it will be assumed to have given an incorrect answer.

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Subtask | Points | Number of queries | Find balanced hub | Additional constraints |
| 1 | 13 | $\frac{N(N-1)}{2}$ | NO | — |
| 2 | 12 | $\lceil \frac{7N}{2} \rceil$ | NO | — |
| 3 | 13 | $\frac{N(N-1)}{2}$ | YES | — |
| 4 | 10 | $\lceil \frac{7N}{2} \rceil$ | YES | Each large city is connected to exactly three settlements |
| 5 | 13 | $5n$ | YES | — |
| 6 | 39 | $\lceil \frac{7N}{2} \rceil$ | YES | — |

Note that $\lceil x \rceil$ denotes the smallest integer which is greater than or equal to $x$.

Note

Note that the subtask number is a part of the input. The sample grader changes its behavior according to the subtask number.

The input file corresponding to the example above is:

```
1 1
11
0 17 18 20 17 12 20 16 23 20 11
17 0 23 25 22 17 25 21 28 25 16
18 23 0 12 21 16 24 20 27 24 17
20 25 12 0 23 18 26 22 29 26 19
17 22 21 23 0 9 21 17 26 23 16
12 17 16 18 9 0 16 12 21 18 11
20 25 24 26 21 16 0 10 29 26 19
16 21 20 22 17 12 10 0 25 22 15
23 28 27 29 26 21 29 25 0 21 22
20 25 24 26 23 18 26 22 21 0 19
11 16 17 19 16 11 19 15 22 19 0
```

This format is quite different from specifying the list of highways. Note that you are allowed to modify sample graders, so that they use a different input format.

#include "towns.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "graderlib.c"

int main() {
    FILE *f;
    f = freopen("towns.in","r",stdin);
    assert(f != NULL);
    f = freopen("towns.out","w",stdout);
    assert(f != NULL);
    int ncase, R, N;
    int subtask;
    int ret;
    ret = scanf("%d%d",&subtask,&ncase);
    assert(ret == 2);
    for (int i = 0; i < ncase; i++) {
        ret = scanf("%d",&N);
	assert(ret == 1);
        _ini_query(N,subtask);
        R=hubDistance(N,subtask);
        printf("%d\n",R);
    }
    return 0;
}

#include "towns.h"

int hubDistance(int N, int sub) {
	int R = getDistance(0,1);
	return R;
}

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

static int _N;
static int _dist[110][110];
static int _quota, _user_query;

void _ini_query(int N, int k) {
    int ret;
    _N = N;
    for (int i = 0; i < _N; i++)
        for (int j = 0; j < _N; j++)  {
	    ret = scanf("%d", &_dist[i][j]);
            assert(ret == 1);
        }
    if (k == 1 || k == 3) _quota = _N * (_N - 1) / 2;
    else if (k == 2 || k == 4 || k == 6) _quota = (7 * _N + 1) / 2;
    else _quota = 5 * _N;
    _user_query = 0;
}

int getDistance(int i, int j) {
    _user_query++;
    if (_user_query > _quota) {
        printf("0\n");
        exit(0);
    }
    if (i < 0 || i >= _N) return 0;
    if (j < 0 || j >= _N) return 0;
    return _dist[i][j];
}

#ifndef towns_h
#define towns_h

int getDistance(int i, int j);
int hubDistance(int N, int sub);

#endif

printf("%d\n", (subtask == 1 || subtask == 2) ? abs(R) : R);