{"problem_id": "ioi06_f", "cate": ["graph", "search"], "difficulty": "medium", "cpu_time_limit_ms": 15000, "memory_limit_mb": 256, "description": "This task uses a 15 second time limit and provides a grader interface for interacting with the black box.\n\nThe 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.\n\nThe 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.\n\n ![](https://ioi.contest.codeforces.com/espresso/ff98996d1f014917d9047397f1ac94be98d14b72.png) \n\nA 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.\n\n ![](https://ioi.contest.codeforces.com/espresso/0aed97ae1bb4bf5d5068d49c4255efda2bca9128.png) \n\n1. A ball is thrown through a hole; it hits a deflector and changes direction.\n2. 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.\n3. The deflector toggles every time it is hit.\n\nWhenever 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.\n\nYou will be provided with an interface to black box via grader. You must determine the internals of the box as best as possible .\n\n$1 \\le n \\le 30$\n\nInput\n\nYou are given a grader that provides the following functions\n\n```\nint throwBall(int holeIn, int sideIn, int &holeOut, int &sideOut);\n```\n\nThrows 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.\n\n```\nvoid ResetBox();\n```\n\nResets every deflector in the box to its initial position.\n\n```\nvoid ToggleDeflectors();\n```\n\nToggles every deflector in the box.\n\nYou need to implement function\n\n```\nvoid solve(vector& ans);\n```\n\nThis 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 ?\n\nA sample interaction for the box in the previous figure could be:\n\nthrowBall(3, 4, holeOut, sideOut);\n\nA 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.\n\nGrader will read input in following format:\n\nLINE 1: Contains n, the number of holes on each side.\n\nn 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).\n\n* \".\" means that the square is empty.\n* \"/\" means the square contains a deflector with initial position \"/\"\n* \"\\\" means the square contains a deflector with initial position \"\\\"\n\nInput for test 01 can be found in problem graders archive. Solving it will not be rewarded by any points.\n\nScoring\n\nIf your submission has a '.\", \"/\" or \"\\\" character in an incorrect position, you'll get zero points for that box.\n\nLet $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}$.", "interactor_files": {"grader.cpp": "#include \"blackbox.h\"\n#include \n#include \n#include \n#include \n\n#define N 32\n#define K (N * N)\n\nstatic char F[N][N];\nstatic char _F[N][N];\n\nstatic int _x[K], _y[K];\nstatic char _v[K];\nstatic int pt = 0;\n\nstatic int n;\n\nvoid ToggleDeflectors() {\n int i;\n for (i = 0; i < pt; i++)\n F[_y[i]][_x[i]] ^= '/' ^ '\\\\';\n}\n\nvoid ResetBox() {\n int i;\n for (i = 0; i < pt; i++)\n F[_y[i]][_x[i]] = _v[i];\n}\n\nstatic void internal_init() {\n int i, j;\n scanf(\"%s\", F[0]);\n n = strlen(F[0]);\n for (i = 1; i < n; i++)\n scanf(\"%s\", F[i]);\n memcpy(_F, F, sizeof(F));\n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++)\n if (F[i][j] != '.')\n _x[pt] = j, _y[pt] = i, _v[pt] = F[i][j], pt++;\n}\n\nstatic int vy[] = {1, 0, -1, 0};\nstatic int vx[] = {0, -1, 0, 1};\n\n// 0 - down, 1 - left, 2 - up, 3 - right\n\nint throwBall(int h, int s, int &newh, int &news) {\n if (!(1 <= s && s <= 4)) {\n printf(\"Invalid side : %d\\n\", s);\n exit(0);\n }\n if (!(1 <= h && h <= n)) {\n printf(\"Invalid hole : %d\\n\", h);\n exit(0);\n }\n --s;\n --h;\n int x, y;\n if (s % 2)\n y = h, x = (s == 1) * (n - 1);\n else\n x = h, y = (s == 2) * (n - 1);\n int v = s;\n int count = 0;\n while (1) {\n if (F[y][x] != '.') {\n v = ((F[y][x] == '/') ?\n // 0 - 1, 2 - 3\n 1 ^ v\n :\n // 0 - 3, 1 - 2\n 3 ^ v);\n count++;\n F[y][x] ^= ('/' ^ '\\\\');\n }\n y += vy[v];\n x += vx[v];\n if (y < 0 || x < 0 || y >= n || x >= n)\n break;\n }\n h = (v % 2) ? y : x;\n h++;\n s = 2 ^ v;\n s++;\n news = s;\n newh = h;\n return count;\n}\n\nstatic int notFound;\n\nstatic void CheckAnswer(std::vector pans) {\n int i, j;\n ResetBox();\n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++) {\n if (pans[i][j] != F[i][j] && pans[i][j] != '?') {\n printf(\"Position (%d,%d) doesn't match\", i + 1, j + 1);\n exit(0);\n } else if (pans[i][j] == '?')\n notFound++;\n }\n}\n\nint main() {\n internal_init();\n std::vector pans(n, std::string(n, '?'));\n solve(pans);\n CheckAnswer(pans);\n printf(\"OK %d cells not found\\n\", notFound);\n return 0;\n}\n", "blackbox.h": "#pragma once\n\n#include \n#include \n\nvoid ToggleDeflectors();\nvoid ResetBox();\nint throwBall(int sideIn, int holeIn, int& sideOut, int& holeOut);\nvoid solve(std::vector &ans);\n"}} {"problem_id": "ioi14_c", "cate": ["graph", "game"], "difficulty": "easy", "cpu_time_limit_ms": 1000, "memory_limit_mb": 256, "description": "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.\n\nMei-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.\n\nIn 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\n\nTask\n\nPlease 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.\n\n* void initialize(int n) — We will call your initialize first. The parameter $n$ is the number of cities.\n* 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.\n\nInput\n\nThe sample grader reads the input in the following format:\n\n* line 1: $n$\n* the following $r$ lines: each line contains two integers $u$ and $v$ that describe a question regarding cities $u$ and $v$.\n\nOutput\n\nFor each request the sample grader will return 1 if hasEdge return $1$ for and 0 otherwise.\n\nScoring\n\nEach subtask consists of several games. You will only get points for a subtask if your program wins all of the games for Jian-Jia.\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | $n$ |\n| 1 | 15 | $n = 4$ |\n| 2 | 27 | $4 \\le n \\le 80$ |\n| 3 | 58 | $4 \\le n \\le 1500$ |\n\nExamples\n\nInput\n\n```\n4\n0 1\n3 0\n1 2\n0 2\n3 1\n2 3\n```\n\nOutput\n\n```\n100101\n```\n\nInput\n\n```\n4\n0 3\n2 0\n0 1\n1 2\n1 3\n2 3\n```\n\nOutput\n\n```\n001101\n```\n\nInput\n\n```\n4\n0 3\n1 0\n0 2\n3 1\n1 2\n2 3\n```\n\nOutput\n\n```\n010011\n```\n\nNote\n\nWe explain the game rules with three examples. Each example has $n = 4$ cities and $r = 6$ rounds of question and answer.\n\nIn 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.\n\n| | | |\n| --- | --- | --- |\n| Round | Question | Answer |\n| 1 | 0, 1 | yes |\n| 2 | 3, 0 | yes |\n| 3 | 1, 2 | no |\n| 4 | 0, 2 | yes |\n| — | — | — |\n| 5 | 3, 1 | no |\n| 6 | 2, 3 | no |\n\nIn 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.\n\n| | | |\n| --- | --- | --- |\n| Round | Question | Answer |\n| 1 | 0, 3 | no |\n| 2 | 2, 0 | no |\n| 3 | 0, 1 | no |\n| — | — | — |\n| 4 | 1, 2 | yes |\n| 5 | 1, 3 | yes |\n| 6 | 2, 3 | yes |\n\nIn 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.\n\n| | | |\n| --- | --- | --- |\n| Round | Question | Answer |\n| 1 | 0, 3 | no |\n| 2 | 1, 0 | yes |\n| 3 | 0, 2 | no |\n| 4 | 3, 1 | yes |\n| 5 | 1, 2 | no |\n| 6 | 2, 3 | yes |", "interactor_files": {"game.cpp": "#include \"game.h\"\n\nvoid initialize(int n) {\n\n}\n\nint hasEdge(int u, int v) {\n return 1;\n}\n", "grader.cpp": "#include \n#include \n#include \"game.h\"\n\nint read_int() {\n int x;\n assert(scanf(\"%d\", &x) == 1);\n return x;\n}\n\nint main() {\n int n, u, v;\n n = read_int();\n initialize(n);\n for (int i = 0; i < n * (n - 1) / 2; i++) {\n u = read_int();\n v = read_int();\n printf(\"%d\\n\", hasEdge(u, v));\n }\n return 0;\n}\n", "game.h": "#ifndef _GAME_H\n#define _GAME_H\n\nvoid initialize(int n);\nint hasEdge(int u, int v);\n\n#endif\n"}} {"problem_id": "ioi10_e", "cate": ["data structures"], "difficulty": "easy", "cpu_time_limit_ms": 1000, "memory_limit_mb": 256, "description": "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.\n\nJack 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.\n\nYou 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$.\n\nAfter every second call to faceup, the grader automatically turns both cards face down again.\n\nYour 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.\n\nThe following is one possible sequence of calls your procedure play could make, with explanations.\n\n| | | |\n| --- | --- | --- |\n| Call | Returned value | Explanation |\n| faceup(1) | 'B' | Card $1$ contains B. |\n| faceup(7) | 'X' | Card $7$ contains X. The letters are not equal. The grader automatically turns cards $1$ and $7$ face down. |\n| faceup(7) | 'X' | Card $7$ contains X. |\n| faceup(15) | 'O' | Card $15$ contains O. The letters are not equal. The grader automatically turns cards $7$ and $15$ face down. |\n| faceup(50) | 'X' | Card $50$ contains X. |\n| faceup(7) | 'X' | Card $7$ contains X. Jack gets his first candy. The grader automatically turns cards $50$ and $7$ face down. |\n| faceup(7) | 'X' | Card $7$ contains X. |\n| faceup(50) | 'X' | Card $50$ contains X. Equal letters, but Jack gets no candy. The grader automatically turns cards $7$ and $50$ face down. |\n| faceup(2) | 'B' | Card $2$ contains B. |\n| ... | ... | Some function calls were omitted |\n| faceup(1) | 'B' | Card $1$ contains B. |\n| faceup(2) | 'B' | Card $2$ contains B. Jack gets his 25th candy. |\n\nScoring\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 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). |\n| 2 | 50 | Implement a strategy that finishes any possible game with at most $100$ calls to faceup(C). |", "interactor_files": {"grader.cpp": "#include \"memory.h\"\n#include \"grader.h\"\n#include \n#include \n\nstatic char card[51];\nstatic int up[2], is_up[51], candy[25], candies, moves;\n\nchar faceup(int C){\n int c0, c1;\n if (C < 1 || C > 50 || is_up[C]) {\n exit(92);\n }\n is_up[C] = 1;\n up[moves%2] = C;\n moves++;\n if (moves%2 == 0) {\n c0 = card[ up[0] ] - 'A';\n c1 = card[ up[1] ] - 'A';\n if (c0==c1 && !candy[c0]) {\n candy[c0] = 1;\n ++candies;\n }\n is_up[ up[0] ] = is_up[ up[1] ] = 0;\n }\n return card[C];\n}\n\nvoid playgame(){\n int i;\n for (i=1;i<=50;i++) {\n card[i] = getchar();\n }\n moves = candies = 0;\n play();\n if (candies != 25) {\n exit(91);\n }\n}\n\nint main(){\n playgame();\n printf(\"OK %d\\n\",moves);\n return 0;\n}\n", "memory.cpp": "#include \"grader.h\"\n#include \"memory.h\"\n\nvoid play() {\n int i;\n char a, b;\n for (i=0; i<10; ++i) {\n a = faceup(42);\n b = faceup(47);\n }\n}\n", "grader.h": "char faceup(int C);\n", "memory.h": "void play();\n"}} {"problem_id": "ioi10_a", "cate": ["search"], "difficulty": "easy", "cpu_time_limit_ms": 1000, "memory_limit_mb": 256, "description": "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.\n\nFor illustration only, we show the names of the possible murderers, locations and weapons. The names are not required to solve the task.\n\n| | | |\n| --- | --- | --- |\n| Murderer | Location | Weapon |\n| 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  — |\n\nJill 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.\n\nYou 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.\n\nExample\n\nAs 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.\n\n| | | |\n| --- | --- | --- |\n| Call | Returned value | Explanation |\n| Theory(1, 1, 1) | 1, or 2, or 3 | All three are wrong |\n| Theory(3, 3, 3) | 1, or 3 | Only the location is correct |\n| Theory(5, 3, 4) | 1 | Only the murderer is wrong |\n| Theory(2, 3, 4) | 0 | All are correct |\n\nScoring\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 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. |\n| 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. |", "interactor_files": {"cluedo.cpp": "#include \"grader.h\"\n#include \"cluedo.h\"\n\nvoid Solve(){\n int r;\n r = Theory(1,2,3);\n if (r == 0) return;\n r = Theory(3,2,1);\n if (r == 0) return;\n r = Theory(4,4,4);\n if (r == 0) return;\n}\n", "grader.cpp": "#include \n#include \n#include \n#include \"grader.h\"\n#include \"cluedo.h\"\n\nstatic int M,L,W,gotit,cnt,maxcnt;\n\nint Theory(int m, int l, int w) {\n ++cnt;\n if (m < 1 || m > 6 || l < 1 || l > 10 || w < 1 || w > 6) exit(92);\n if (rand()%2 && m != M) return 1;\n else if (rand()%2 && l != L) return 2;\n else if (rand()%2 && w != W) return 3;\n else if (m != M) return 1;\n else if (l != L) return 2;\n else if (w != W) return 3;\n gotit = 1;\n return 0;\n}\n\nint main(){\n while (3 == scanf(\"%d%d%d\",&M,&L,&W)) {\n cnt = gotit = 0;\n Solve();\n if (cnt > maxcnt) maxcnt = cnt;\n if (!gotit) {\n printf(\"NO\\n\");\n return 91;\n }\n }\n printf(\"OK %d\\n\",maxcnt);\n return 0;\n}\n", "cluedo.h": "void Solve();\n", "grader.h": "int Theory(int M, int L, int W);\n"}} {"problem_id": "ioi13_d", "cate": ["search"], "difficulty": "medium", "cpu_time_limit_ms": 2000, "memory_limit_mb": 32, "description": "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.\n\n![](https://ioi.contest.codeforces.com/espresso/1f7aed863559e3e0a541816cc2d8c998e32b4473.png)\n\nThe 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.\n\nThe 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.\n\nYou 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.\n\nYou 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.\n\nYou 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.\n\nGrader Function tryCombination():\n\nint tryCombination(int S[]);\n\nThe 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$.\n\nThis function may be called at most $70\\,000$ times.\n\nParameters:\n\n* $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.\n* Returns: The number of the first door that is closed, or ­$-1$ if all doors are open.\n\nGrader Procedure answer():\n\nvoid answer(int S[], int D[]);\n\nCall this procedure when you have identified the combination of switches to open all doors, and the door to which each switch is connected.\n\nParameters:\n\n* $S$: An array of length $N$, indicating the correct position of each switch. The format matches that of the function tryCombination() described above.\n* $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.\n* Returns: This procedure does not return, but will cause the program to exit.\n\nYour Procedure exploreCave():\n\nvoid exploreCave(int N);\n\nYour submission must implement this procedure.\n\nThis 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.\n\nParameters:\n\n* $N$: The number of switches and doors in the cave.\n\nInput\n\nThe sample grader reads input in the following format:\n\n* line $1$: $N$\n* line $2$: $S[0]\\ S[1]\\dots S[N­ - 1]$\n* line $3$: $D[0]\\ D[1]\\dots D[N­ - 1]$\n\nHere $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.\n\nScoring\n\nFull constraints: $1 \\leq N \\leq 5\\,000$\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 1 | 12 | For each $i$, switch $i$ is connected to door $i$. Your task is simply to determine the correct combination. |\n| 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. |\n| 3 | 21 | $N \\leq 100$ |\n| 4 | 30 | $N \\leq 2\\,000$ |\n| 5 | 24 | (None) |\n\nExample\n\nInput\n\n```\n4\n1 1 1 0\n3 1 0 2\n```\n\nOutput\n\nNote\n\nSuppose the doors and switches are arranged as in the picture above:\n\n| | | |\n| --- | --- | --- |\n| Function Call | Returns | Explanation |\n| 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. |\n| tryCombination([0, 1, 1, 0]) | 3 | Doors $0$, $1$ and $2$ are all opened, while door $3$ is closed. |\n| tryCombination([1, ­1, 1, 0]) | $-1$ | Moving switch $0$ down causes all doors to be opened, indicated by the return value of ­$-1$. |\n| 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. |", "interactor_files": {"cave.cpp": "#include \"cave.h\"\n\nvoid exploreCave(int N) {\n /* ... */\n}\n", "cave.h": "#ifndef __CAVE_H__\n#define __CAVE_H__\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nint tryCombination(int S[]);\nvoid answer(int S[], int D[]);\nvoid exploreCave(int N);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __CAVE_H__ */\n", "grader.c": "#include \"graderlib.c\"\n\nint main() {\n int N;\n\tN = init();\n\texploreCave(N);\n printf(\"INCORRECT\\nYour solution did not call answer().\\n\");\n\treturn 0;\n}\n", "graderlib.c": "#include \n#include \n#include \"cave.h\"\n\n#define MAX_N 5000\n#define MAX_CALLS 70000\n\n#define fail(s, x...) do { \\\n\t\tfprintf(stderr, s \"\\n\", ## x); \\\n\t\texit(1); \\\n\t} while(0)\n\n/* Symbol obfuscation */\n#define N koala\n#define realS kangaroo\n#define realD possum\n#define inv platypus\n#define num_calls echidna\n\nstatic int N;\nstatic int realS[MAX_N];\nstatic int realD[MAX_N];\nstatic int inv[MAX_N];\nstatic int num_calls;\n\nvoid answer(int S[], int D[]) {\n int i;\n int correct = 1;\n for (i = 0; i < N; ++i)\n if (S[i] != realS[i] || D[i] != realD[i]) {\n correct = 0;\n break;\n }\n\n if (correct)\n printf(\"CORRECT\\n\");\n else\n printf(\"INCORRECT\\n\");\n\n for (i = 0; i < N; ++i) {\n if (i > 0)\n printf(\" \");\n printf(\"%d\", S[i]);\n }\n printf(\"\\n\");\n\n for (i = 0; i < N; ++i) {\n if (i > 0)\n printf(\" \");\n printf(\"%d\", D[i]);\n }\n printf(\"\\n\");\n\n exit(0);\n}\n\nint tryCombination(int S[]) {\n int i;\n\n if (num_calls >= MAX_CALLS) {\n printf(\"INCORRECT\\nToo many calls to tryCombination().\\n\");\n exit(0);\n }\n ++num_calls;\n\n for (i = 0; i < N; ++i)\n if (S[inv[i]] != realS[inv[i]])\n return i;\n return -1;\n}\n\nint init() {\n int i, res;\n\n\tres = scanf(\"%d\", &N);\n\n for (i = 0; i < N; ++i) {\n res = scanf(\"%d\", &realS[i]);\n }\n for (i = 0; i < N; ++i) {\n res = scanf(\"%d\", &realD[i]);\n inv[realD[i]] = i;\n }\n\n num_calls = 0;\n return N;\n}\n\n"}} {"problem_id": "ioi03_d", "cate": ["search", "bit"], "difficulty": "easy", "cpu_time_limit_ms": 1000, "memory_limit_mb": 64, "description": "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.\n\nCows 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.\n\nWrite 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$?\n\nTry to ask as few questions as possible to determine the cow.\n\nInteraction\n\nThe first line of the input file contains two space-separated integers, $N$ and $P$.\n\nEach 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.\n\nYour 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.\n\nAfter 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.\n\nThe 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.\n\nScoring\n\nCorrectness: 30% of points\n\nPrograms 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.\n\nQuestion count: 70% of points\n\nThe 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.\n\nExample\n\nInput\n\n```\n4 2\nX Z\nX Y\nY X\nY Y\n\n0\n\n1\n```\n\nOutput\n\n```\nQ 1 X Z\n\nQ 2 Y\n\nC 4\n```", "interactor_files": {"guess_interactor.cpp": "// IOI03_D (guess) - Guess Which Cow Interactor\n#include \nusing namespace std;\n\nint N, P;\nint target; // target cow (1-indexed)\nvector> cows;\nint queries = 0;\nint MAX_QUERIES;\n\nvoid finish(int code, const char* msg) {\n fprintf(stderr, \"%s\\n\", msg);\n FILE* tout = fopen(\"tout.txt\", \"w\");\n if (tout) {\n fprintf(tout, \"queries=%d\\n\", queries);\n fprintf(tout, \"query_limit=%d\\n\", MAX_QUERIES);\n fclose(tout);\n }\n exit(code);\n}\n\nint main(int argc, char* argv[]) {\n if (argc < 3) {\n finish(2, \"Usage: interactor \");\n }\n\n // Read input\n FILE* fin = fopen(argv[1], \"r\");\n if (!fin) finish(2, \"Cannot open input file\");\n\n fscanf(fin, \"%d %d\", &N, &P);\n cows.resize(N, vector(P));\n\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < P; j++) {\n char c;\n fscanf(fin, \" %c\", &c);\n cows[i][j] = c;\n }\n }\n fclose(fin);\n\n // Read answer (target cow)\n FILE* fans = fopen(argv[2], \"r\");\n if (!fans) finish(2, \"Cannot open answer file\");\n fscanf(fans, \"%d\", &target);\n fclose(fans);\n\n // Query limit based on problem constraints\n MAX_QUERIES = 3 * N;\n\n // Send N and P to solver\n printf(\"%d %d\\n\", N, P);\n // Send cow properties\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < P; j++) {\n printf(\"%c%c\", cows[i][j], j == P-1 ? '\\n' : ' ');\n }\n }\n fflush(stdout);\n\n char cmd[10];\n while (scanf(\"%s\", cmd) == 1) {\n if (cmd[0] == 'Q') {\n int prop;\n scanf(\"%d\", &prop);\n\n queries++;\n if (queries > MAX_QUERIES) {\n finish(1, \"WA: Query limit exceeded\");\n }\n\n if (prop < 1 || prop > P) {\n finish(1, \"WA: Invalid property\");\n }\n\n // Read values until newline\n set values;\n char c;\n while ((c = getchar()) != '\\n' && c != EOF) {\n if (c != ' ') values.insert(c);\n }\n\n // Check if target cow's property is in values\n char target_val = cows[target - 1][prop - 1];\n printf(\"%d\\n\", values.count(target_val) ? 1 : 0);\n fflush(stdout);\n\n } else if (cmd[0] == 'C') {\n int guess;\n scanf(\"%d\", &guess);\n\n if (guess == target) {\n finish(0, \"OK\");\n } else {\n finish(1, \"WA: Wrong cow\");\n }\n } else {\n finish(2, \"PE: Unknown command\");\n }\n }\n\n finish(2, \"PE: No guess provided\");\n return 0;\n}\n", "non_adaptive.cpp": "// IOI03_D (guess) - Guess Which Cow Interactor\n#include \"testlib.h\"\n#include \nusing namespace std;\n\nstatic int queries = 0;\nstatic int query_limit = 0;\n\nvoid log_metrics() {\n tout << \"queries=\" << queries << endl;\n tout << \"query_limit=\" << query_limit << endl;\n}\n\nvoid finish(TResult verdict, const string& msg) {\n log_metrics();\n quitf(verdict, \"%s\", msg.c_str());\n}\n\nint read_target_from_ans(const string& in_path) {\n string ans_path = in_path;\n size_t pos = ans_path.rfind(\".in\");\n if (pos != string::npos) {\n ans_path.replace(pos, 3, \".out\");\n }\n ifstream ans(ans_path);\n int target = 1;\n if (ans) ans >> target;\n return target;\n}\n\nint main(int argc, char* argv[]) {\n registerInteraction(argc, argv);\n atexit(log_metrics);\n\n int target = read_target_from_ans(argv[1]);\n\n int N = inf.readInt();\n int P = inf.readInt();\n\n vector> cows(N, vector(P));\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < P; j++) {\n cows[i][j] = inf.readChar();\n if (cows[i][j] == ' ' || cows[i][j] == '\\n') {\n j--;\n continue;\n }\n }\n }\n\n query_limit = 3 * N;\n log_metrics();\n\n cout << N << \" \" << P << endl;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < P; j++) {\n cout << cows[i][j] << (j == P-1 ? '\\n' : ' ');\n }\n }\n cout.flush();\n\n string cmd;\n while (cin >> cmd) {\n if (cmd == \"Q\") {\n int prop;\n if (!(cin >> prop)) {\n finish(_wa, \"EOF after Q\");\n }\n\n queries++;\n if (queries > query_limit) {\n finish(_wa, \"Query limit exceeded\");\n }\n\n if (prop < 1 || prop > P) {\n finish(_wa, \"Invalid property index\");\n }\n\n string line;\n getline(cin, line);\n set values;\n for (char c : line) {\n if (c != ' ') values.insert(c);\n }\n\n char target_val = cows[target - 1][prop - 1];\n cout << (values.count(target_val) ? 1 : 0) << endl;\n cout.flush();\n\n } else if (cmd == \"C\") {\n int guess;\n if (!(cin >> guess)) {\n finish(_wa, \"EOF after C\");\n }\n\n if (guess == target) {\n finish(_ok, \"Correct\");\n } else {\n finish(_wa, \"Wrong cow\");\n }\n } else {\n finish(_pe, \"Unknown command\");\n }\n }\n\n finish(_pe, \"No guess provided\");\n return 0;\n}\n"}} {"problem_id": "ioi07_a", "cate": ["search", "math"], "difficulty": "easy", "cpu_time_limit_ms": 1000, "memory_limit_mb": 64, "description": "Mirko is a big fan of crop circles, geometrical formations of flattened crops that are supposedly of alien origin.\n\nOne 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.\n\n![](https://ioi.contest.codeforces.com/espresso/08818a0e55bc586b67034b4c4fa314f49d8f0e57.png)\n\nThe 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)$.\n\nMirko 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.\n\n![](https://ioi.contest.codeforces.com/espresso/6856cf1ac83cbecbb3180c112fd11dedcc5d750e.png)\n\nExample 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.\n\nAfter 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.\n\nThe 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.\n\nWrite 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.\n\nThe device may be used at most $300$ times in one test run.\n\nInteraction\n\nThis 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.\n\n* 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.\n* 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.\n* 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.\n* 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.\n\nIn order to interact properly with the grader, your program needs to flush the standard output after every write operation.\n\nScoring\n\nIn 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.\n\nExample\n\nInput\n\n```\n19 7 4\n\ntrue\n\nfalse\n\nfalse\n\ntrue\n```\n\nOutput\n\n```\nexamine 11 2\n\nexamine 2 5\n\nexamine 9 14\n\nexamine 18 3\n\nsolution 12 9\n```", "interactor_files": {"aliens_interactor.cpp": "// IOI07_A (aliens) - Interactor\n// Check if point is inside circle\n#include \nusing namespace std;\n\nint N, R;\nint cx, cy; // circle center\nint known_x, known_y; // known flattened point\nint queries = 0;\nconst int MAX_QUERIES = 300;\n\nvoid finish(int code, const char* msg) {\n fprintf(stderr, \"%s\\n\", msg);\n FILE* tout = fopen(\"tout.txt\", \"w\");\n if (tout) {\n fprintf(tout, \"queries=%d\\n\", queries);\n fprintf(tout, \"query_limit=%d\\n\", MAX_QUERIES);\n fclose(tout);\n }\n exit(code);\n}\n\nbool inside_circle(int x, int y) {\n long long dx = x - cx;\n long long dy = y - cy;\n return dx * dx + dy * dy <= (long long)R * R;\n}\n\nint main(int argc, char* argv[]) {\n if (argc < 2) {\n finish(2, \"Usage: interactor \");\n }\n\n FILE* fin = fopen(argv[1], \"r\");\n if (!fin) {\n finish(2, \"Cannot open input file\");\n }\n\n fscanf(fin, \"%d %d\", &N, &R);\n fscanf(fin, \"%d %d\", &cx, &cy);\n fscanf(fin, \"%d %d\", &known_x, &known_y);\n fclose(fin);\n\n // Send initial info: N, known_x, known_y\n printf(\"%d %d %d\\n\", N, known_x, known_y);\n fflush(stdout);\n\n char cmd[20];\n while (scanf(\"%s\", cmd) == 1) {\n if (strcmp(cmd, \"examine\") == 0) {\n int x, y;\n if (scanf(\"%d %d\", &x, &y) != 2) {\n finish(2, \"PE: Invalid examine format\");\n }\n\n queries++;\n if (queries > MAX_QUERIES) {\n finish(1, \"WA: Query limit exceeded\");\n }\n\n if (x < 1 || x > N || y < 1 || y > N) {\n finish(1, \"WA: Point out of bounds\");\n }\n\n printf(\"%s\\n\", inside_circle(x, y) ? \"true\" : \"false\");\n fflush(stdout);\n\n } else if (strcmp(cmd, \"solution\") == 0) {\n int sx, sy;\n if (scanf(\"%d %d\", &sx, &sy) != 2) {\n finish(2, \"PE: Invalid solution format\");\n }\n\n if (sx == cx && sy == cy) {\n finish(0, \"OK\");\n } else {\n finish(1, \"WA: Wrong center\");\n }\n } else {\n finish(2, \"PE: Unknown command\");\n }\n }\n\n finish(2, \"PE: No solution provided\");\n return 0;\n}\n", "non_adaptive.cpp": "// IOI07_A (aliens) - Croatian Coat of Arms Interactor\n#include \"testlib.h\"\n#include \nusing namespace std;\n\nstatic int queries = 0;\nstatic int query_limit = 300;\nstatic long long N, M, cx, cy;\n\nvoid log_metrics() {\n tout << \"queries=\" << queries << endl;\n tout << \"query_limit=\" << query_limit << endl;\n}\n\nvoid finish(TResult verdict, const string& msg) {\n log_metrics();\n quitf(verdict, \"%s\", msg.c_str());\n}\n\nbool is_flattened(long long x, long long y) {\n // Check if (x,y) is within the 5x5 chessboard pattern centered at (cx,cy)\n // Each square is M×M, total size is 5M×5M\n long long half = (5 * M) / 2; // 2.5 * M, but M is odd so 5M is odd\n\n // Bounds of the chessboard\n long long left = cx - half;\n long long right = cx + half;\n long long bottom = cy - half;\n long long top = cy + half;\n\n if (x < left || x > right || y < bottom || y > top) {\n return false;\n }\n\n // Determine which square (i, j) the point is in (0-indexed, 0-4)\n // Square (0,0) is bottom-left, (4,4) is top-right\n long long dx = x - left;\n long long dy = y - bottom;\n int i = dx / M; // column (0-4)\n int j = dy / M; // row (0-4)\n\n if (i < 0 || i > 4 || j < 0 || j > 4) {\n return false;\n }\n\n // Red squares: (i + j) % 2 == 0\n // Pattern (j from top to bottom, i from left to right):\n // R W R W R (j=4)\n // W R W R W (j=3)\n // R W R W R (j=2)\n // W R W R W (j=1)\n // R W R W R (j=0)\n return (i + j) % 2 == 0;\n}\n\nint main(int argc, char* argv[]) {\n registerInteraction(argc, argv);\n atexit(log_metrics);\n\n N = inf.readLong();\n M = inf.readLong();\n long long x0 = inf.readLong();\n long long y0 = inf.readLong();\n cx = inf.readLong();\n cy = inf.readLong();\n\n log_metrics();\n\n cout << N << \" \" << x0 << \" \" << y0 << endl;\n cout.flush();\n\n string cmd;\n while (cin >> cmd) {\n if (cmd == \"examine\") {\n long long x, y;\n if (!(cin >> x >> y)) {\n finish(_pe, \"Invalid examine format\");\n }\n\n queries++;\n if (queries > query_limit) {\n finish(_wa, \"Query limit exceeded\");\n }\n\n if (x < 1 || x > N || y < 1 || y > N) {\n finish(_wa, \"Point out of bounds\");\n }\n\n cout << (is_flattened(x, y) ? \"true\" : \"false\") << endl;\n cout.flush();\n\n } else if (cmd == \"solution\") {\n long long sx, sy;\n if (!(cin >> sx >> sy)) {\n finish(_pe, \"Invalid solution format\");\n }\n\n if (sx == cx && sy == cy) {\n finish(_ok, \"Correct\");\n } else {\n finish(_wa, \"Wrong center\");\n }\n } else {\n finish(_pe, \"Unknown command\");\n }\n }\n\n finish(_pe, \"No solution provided\");\n return 0;\n}\n"}} {"problem_id": "ioi17_d", "cate": ["search"], "difficulty": "medium", "cpu_time_limit_ms": 1000, "memory_limit_mb": 256, "description": "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.\n\nThe 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$.\n\nYour 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:\n\n* 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$.\n* 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$.\n\nFor 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:\n\n* Exactly one of the boxes $0$ and $1$ contains a prize more expensive than the one in box $2$.\n* Exactly two of the boxes $3, 4, \\ldots, 7$ contain a prize more expensive than the one in box $2$.\n\nYour task is to find the box containing the diamond by asking a small number of questions.\n\nImplementation details\n\nYou should implement the following procedure:\n\n* int find\\_best(int n)\n + This procedure is called exactly once by the grader.\n + $n$: the number of boxes.\n + 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$.\n\nThe above procedure can make calls to the following procedure:\n\n* int[] ask(int i)\n + $i$: label of the box that you choose to ask about. The value of $i$ must be between $0$ and $n - 1$, inclusive.\n + 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$.\n\nInput\n\nThe 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:\n\n* line 1: $n$ ($3 \\leq n \\leq 200\\,000$)\n* line 2: $p[0], p[1], \\ldots, p[n - 1]$\n\nThe type of the prize in each box is between $1$ and $v$, inclusive.\n\nThere is exactly one prize of type $1$.\n\nFor 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$.\n\nOutput\n\nThe sample grader prints a single line containing the return value of find\\_best and the number of calls to the procedure ask.\n\nScoring\n\nIn 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.\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 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 |\n| 2 | 80 | No additional constraints |\n\nIn 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:\n\n| | |\n| --- | --- |\n| Questions | Score |\n| $10\\,000 \\textless q$ | $0$ (reported in CMS as 'Wrong Answer') |\n| $6000 \\textless q \\leq 10\\,000$ | $70$ |\n| $5000 \\textless q \\leq 6000$ | $80 - (q-5000)/100$ |\n| $q \\leq 5000$ | $80$ |\n\nNote\n\nThe grader makes the following procedure call:\n\nfind\\_best(8)\n\nThere 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.\n\n* 'ask(0)' returns $[0, 3]$\n* 'ask(1)' returns $[0, 1]$\n* 'ask(2)' returns $[1, 2]$\n* 'ask(3)' returns $[0, 0]$\n* 'ask(4)' returns $[2, 1]$\n* 'ask(5)' returns $[2, 1]$\n* 'ask(6)' returns $[1, 0]$\n* 'ask(7)' returns $[3, 0]$\n\nIn this example, the diamond is in box $3$. So the procedure find\\_best should return $3$.\n\n![](https://ioi.contest.codeforces.com/espresso/d687edca56d5f86f2c4caa309615bf72cc5ce0dc.png)\n\nThe 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$.", "interactor_files": {"grader.cpp": "#include \"prize.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstatic FILE *fin;\nstatic FILE *fout;\n\nvector ask(int i) {\n fprintf(fout, \"A %d\\n\", i);\n fflush(fout);\n vector result(2);\n if (fscanf(fin, \"%d %d\", &result[0], &result[1]) != 2) {\n cerr << \"tester error\" << endl;\n cerr << \"could not read query response\" << endl;\n exit(0);\n }\n if (result[0] < 0) {\n exit(0);\n }\n return result;\n}\n\nint main(int argc, char **argv) {\n if(argc!=3) {\n cerr << \"grader error\" << endl;\n cerr << \"number of argument isn't 3\" << endl;\n exit(0);\n }\n fin = fopen(argv[1], \"r11\");\n fout = fopen(argv[2], \"a\");\n\n int n;\n if (fscanf(fin, \"%d\", &n) != 1) {\n cerr << \"tester error\" << endl;\n cerr << \"could not read 'n'\" << endl;\n exit(0);\n }\n\n int result = find_best(n);\n fprintf(fout, \"B %d\\n\", result);\n fflush(fout);\n return 0;\n}\n", "manager.cpp": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define forv(i, v) for (int i=0; i pii;\nFILE *fin;\nFILE *fout;\n\nvector > queries;\nint n, answer=-1;\nconst int maxq=10000, maxgen=5;\n\nstruct ManagerStrategy {\n virtual void read_input(istream& in)=0;\n virtual pii ask(int index)=0;\n virtual bool isBest(int index)=0;\n virtual vector get_levels()=0;\n} *strategy;\n\ninline void finish() {\n cout << n << \" \" << queries.size() << \" \" << answer << endl;\n vector levels = strategy->get_levels();\n forv(i, levels)\n cout << (i>0?\" \":\"\") << levels[i];\n cout << endl;\n forv(i, queries)\n cout << queries[i].X << \" \" << queries[i].Y.X << \" \" << queries[i].Y.Y << endl;\n cout.flush();\n}\n\ninline void doubleWrite(string code, string msg) {\n cout << code << endl << msg << endl;\n#ifdef ERRLOG\n cerr << code << endl << msg << endl;\n#endif\n}\n\ninline void die(string code, string msg, bool sendDie) {\n if (sendDie) {\n fprintf(fout, \"%d %d\\n\", -1, -1);\n fflush(fout);\n }\n doubleWrite(code, msg);\n finish();\n exit(0);\n}\n\nconst string OK =\"OK\";\nconst string WA = \"WA\";\nconst string FAIL = \"FAIL\";\n\ninline int readValidIndex(string cmd, bool sendDie) {\n int index;\n if (fscanf(fin, \"%d\", &index) != 1) {\n die(WA, \"io error, could not read index\", sendDie);\n }\n#ifdef ERRLOG\n cerr << cmd << \" \" << index << endl;\n#endif\n if (index < 0 || index>=n) {\n die(WA, \"invalid index\" , sendDie);\n }\n return index;\n}\n\nstruct ManagerStrategy_Plain : public ManagerStrategy {\n vector g;\n vector > rank_count;\n\n virtual void read_input(istream& cin) {\n cin >> n ;\n\n g.resize(n);\n for (int i = 0; i < n; i++) {\n cin >> g[i];\n }\n\n int max_rank = *max_element(g.begin(), g.end());\n rank_count.resize(max_rank + 1, vector(n + 1, 0));\n for (int r = 0; r <= max_rank; r++) {\n for (int i = 1; i <= n; i++) {\n rank_count[r][i] = rank_count[r][i - 1] + int(g[i - 1] == r);\n }\n }\n\n for (int i = 0; i <= n; i++) {\n for (int r = 1; r <= max_rank; r++) {\n rank_count[r][i] += rank_count[r - 1][i];\n }\n }\n }\n virtual pii ask(int i) {\n pii result;\n result.first = rank_count[g[i] - 1][i + 1];\n result.second = rank_count[g[i] - 1][n] - result.first;\n return result;\n }\n virtual bool isBest(int index) {\n return g[index] == 1;\n }\n virtual vector get_levels(){\n return g;\n }\n};\n\nstruct ManagerStrategy_Adversary : public ManagerStrategy {\n int max_rank;\n vectornum;\n sets[maxgen+1];\n vector >t;\n virtual void read_input(istream& cin) {\n cin >> n >> max_rank;\n num.resize(max_rank+1, 0);\n for (int i = 1; i <=max_rank ; i++){\n\t cin>>num[i];\n\t num[i]+=num[i-1];\n\t}\n t.resize(max_rank + 1, vector(n + 2, 0));\n for(int i=2;i<=max_rank;i++){\n\ts[i].insert(0);\n\ts[i].insert(num[i]+1);\n\tt[i][num[i]+1]=num[i]-num[i-1]+1;\n }\n }\n virtual pii ask(int x) {\n x++;\n for(int i = max_rank; i > 1; i--)\n\t{\n\t set:: iterator it = s[i].lower_bound(x);\n\t int r = (*it);\n\t int l = (*(--it));\n\t if(r == x) return pii(x-t[i][x], num[i-1]-(x-t[i][x]));\n\t if(t[i][r] > t[i][l] + 1) {\n\t s[i].insert(x);\n\t if(r-l-2==0) t[i][x] = t[i][l] + 1;\n\t else t[i][x] = t[i][l] + 1 + round(((double)t[i][r]-t[i][l]-2)*(x-l-1)/(r-l-2));\n\t return pii(x-t[i][x], num[i-1]-(x-t[i][x]));\n\t }\n\t else {\n\t x -= t[i][l];\n\t }\n\t}\n return pii(0,0);\n }\n virtual bool isBest(int index) {\n pii tmp = ask(index);\n return (tmp.X + tmp.Y == 0);\n }\n virtual vector get_levels(){\n vector ret;\n ret.resize(n);\n for(int i=0;inum, tmp_place;\n sets[maxgen+1];\n vector >t, here;\n vector g;\n virtual void read_input(istream& cin) {\n int seed_rand;\n cin>>seed_rand;\n srand(seed_rand);\n cin >> n >> max_rank;\n g.resize(n+1,pii(-1,-1));\n num.resize(max_rank+1, 0);\n for (int i = 1; i <=max_rank ; i++){\n\t cin>>num[i];\n\t num[i]+=num[i-1];\n\t}\n t.resize(max_rank + 1, vector(n + 2, 0));\n here.resize(max_rank + 1, vector(n + 2, 0));\n for(int i=2;i<=max_rank;i++){\n\ts[i].insert(0);\n\ts[i].insert(num[i]+1);\n\tt[i][num[i]+1]=num[i]-num[i-1];\n }\n }\n virtual pii ask(int x) {\n x++;\n //cout< 1; i--)\n\t{\n\t set:: iterator it = s[i].lower_bound(x);\n\t int r = (*it);\n\t int l = (*(--it));\n\t int p = rand() % (r-l-1);\n\t if(t[i][r] > t[i][l] + here[i][l] && p 1; i--)\n\t{\n\t set:: iterator it = s[i].lower_bound(x);\n\t int r = (*it);\n\t int l = (*(--it));\n\t if(t[i][r] > t[i][l] + here[i][l]) {\n\t s[i].insert(x);\n\t if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];\n\t 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));\n\t g[index] = pii(x-t[i][x]-1, num[i-1]-(x-t[i][x]-1));\n\t here[i][x] = 1;\n\t //cout< get_levels(){\n vector ret;\n ret.resize(n);\n for(int i=0;inum, tmp_place;\n sets[maxgen+1];\n vector >t, here;\n vector g;\n virtual void read_input(istream& cin) {\n cin >> n >> max_rank;\n g.resize(n+1,pii(-1,-1));\n num.resize(max_rank+1, 0);\n for (int i = 1; i <=max_rank ; i++){\n\t cin>>num[i];\n\t num[i]+=num[i-1];\n\t}\n t.resize(max_rank + 1, vector(n + 2, 0));\n here.resize(max_rank + 1, vector(n + 2, 0));\n for(int i=2;i<=max_rank;i++){\n\ts[i].insert(0);\n\ts[i].insert(num[i]+1);\n\tt[i][num[i]+1]=num[i]-num[i-1];\n }\n }\n virtual pii ask(int x) {\n x++;\n int index=x;\n if(g[x]!=pii(-1,-1)) return g[x];\n tmp_place.clear();\n for(int i = max_rank; i > 1; i--)\n\t{\n\t set:: iterator it = s[i].lower_bound(x);\n\t int r = (*it);\n\t int l = (*(--it));\n\t int p = 0;\n\t if(i == max_rank)\n\t p = r-l-2;\n\t if(t[i][r] > t[i][l] + here[i][l] && p 1; i--)\n\t{\n\t set:: iterator it = s[i].lower_bound(x);\n\t int r = (*it);\n\t int l = (*(--it));\n\t if(t[i][r] > t[i][l] + here[i][l]) {\n\t s[i].insert(x);\n\t if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];\n\t 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));\n\t g[index] = pii(x-t[i][x]-1, num[i-1]-(x-t[i][x]-1));\n\t here[i][x] = 1;\n\t return g[index];\n\t }\n\t else {\n\t s[i].insert(x);\n\t if(r-l-2 == 0) t[i][x] = t[i][l] + here[i][l];\n\t 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));\n\t x -= t[i][x];\n\t }\n\t}\n g[index] = pii(0, 0);\n return g[index];\n }\n virtual bool isBest(int index) {\n pii tmp = ask(index);\n return (tmp.X + tmp.Y == 0);\n }\n virtual vector get_levels(){\n vector ret;\n ret.resize(n);\n for(int i=0;ig;\n vectorgen2,vec,mark;\n vector >t;\n sets[maxgen+1];\n virtual void read_input(istream& cin) {\n int seed_rand;\n cin>>seed_rand;\n srand(seed_rand);\n cin >> n >> max_rank;\n for(int i=1;i<=max_rank;i++){\n cin>>num[i];\n sumnum[i]=sumnum[i-1]+num[i];\n }\n mark.resize(n,-1);\n g.resize(n,pii(-1,-1));\n while(vec.size()(sumnum[max_rank-2] + 2, 0));\n for(int i=2;i<=max_rank-2;i++){\n s[i].insert(0);\n s[i].insert(sumnum[i]+1);\n t[i][sumnum[i]+1]=num[i]+1;\n }\n }\n virtual pii ask(int x) {\n if(g[x].X!=-1) return g[x];\n int index = x;\n \n if(mark[x] != -1){\n x = mark[x];\n for(int i = max_rank-2; i > 1; i--)\n\t{\n\t set:: iterator it = s[i].lower_bound(x);\n\t int r = (*it);\n\t int l = (*(--it));\n\t if(r == x) return pii(x-t[i][x], sumnum[i-1]-(x-t[i][x]));\n\t if(t[i][r] > t[i][l] + 1) {\n\t s[i].insert(x);\n\t if(r-l-2==0) t[i][x] = t[i][l] + 1;\n\t else t[i][x] = t[i][l] + 1 + round(((double)t[i][r]-t[i][l]-2)*(x-l-1)/(r-l-2));\n\t return g[index] = pii(x-t[i][x], sumnum[i-1]-(x-t[i][x]));\n\t }\n\t else {\n\t x -= t[i][l];\n\t }\n\t}\n return g[index] = pii(0,0);\n }\n \n if(gen2.size() get_levels(){\n vector ret;\n ret.resize(n);\n for(int i=0;i> subtask_type >> strategy_type;\n if (strategy_type == \"plain\") {\n strategy = new ManagerStrategy_Plain();\n } else if (strategy_type == \"adversary\") {\n strategy = new ManagerStrategy_Adversary();\n } else if (strategy_type == \"adversary_random\") {\n strategy = new ManagerStrategy_AdversaryRandom();\n } else if (strategy_type == \"adversary_antirandom\") {\n strategy = new ManagerStrategy_AdversaryAntiRandom();\n } else if (strategy_type == \"adversary_betterantirandom\") {\n strategy = new ManagerStrategy_AdversaryBetterAntiRandom();\n } else {\n doubleWrite(FAIL, \"invalid strategy type: \"+strategy_type);\n exit(0);\n }\n\n strategy->read_input(cin);\n\n fprintf(fout, \"%d\\n\", n);\n fflush(fout);\n\n int qcount = 0;\n while (true) {\n char tmp[1000];\n if (fscanf(fin, \"%999s\", tmp) != 1) {\n\t die(WA, \"io error, could not read command\", false);\n }\n string cmd(tmp);\n if (cmd==\"A\") {//query\n\t int index = readValidIndex(\"A\",true);\n qcount++;\n if (qcount>maxq) {\n\t die(WA, \"query limit exceeded\", true);\n }\n pii ans = strategy->ask(index);\n fprintf(fout, \"%d %d\\n\", ans.first, ans.second);\n fflush(fout);\n#ifdef ERRLOG\n\t cerr << ans.first << \" \" << ans.second << endl;\n#endif\n\t queries.push_back(MP(index,ans) );\n } else if (cmd==\"B\") {//answer\n\t int index = readValidIndex(\"B\",false);\n\t answer = index;\n bool ok = strategy->isBest(index);\n if (ok) {\n\t cout << OK << endl;\n#ifdef ERRLOG\n cerr << OK << endl;\n#endif\n\t } else {\n\t doubleWrite(WA, \"answer is not correct\");\n }\n\t finish();\n exit(0);\n } else {\n\t die(WA, \"io error, invalid command\", false);\n }\n }\n return 0;\n}\n", "prize.h": "#include \n\nint find_best(int n);\nstd::vector ask(int i);\n"}, "problem_json": {"name": "prize", "code": "prize", "title": "The Big Prize", "type": "Communication", "time_limit": 1.0, "memory_limit": 1024, "description": "Frogs, The Big Prize"}} {"problem_id": "ioi23_b", "cate": ["graph", "search"], "difficulty": "easy", "cpu_time_limit_ms": 1000, "memory_limit_mb": 1024, "description": "The IOI 2023 organizers are in big trouble! They forgot to plan the trip to Ópusztaszer for the upcoming day. But maybe it is not yet too late ...\n\nThere are $N$ landmarks at Ópusztaszer indexed from $0$ to $N-1$. Some pairs of these landmarks are connected by bidirectional roads. Each pair of landmarks is connected by at most one road. The organizers don't know which landmarks are connected by roads.\n\nWe say that the density of the road network at Ópusztaszer is at least $\\delta$ if every $3$ distinct landmarks have at least $\\delta$ roads among them. In other words, for each triplet of landmarks $(u, v, w)$ such that $0 \\le u < v < w < N$, among the pairs of landmarks $(u,v), (v,w)$ and $(u,w)$ at least $\\delta$ pairs are connected by a road.\n\nThe organizers know a positive integer $D$ such that the density of the road network is at least $D$. Note that the value of $D$ cannot be greater than $3$.\n\nThe organizers can make calls to the phone dispatcher at Ópusztaszer to gather information about the road connections between certain landmarks. In each call, two nonempty arrays of landmarks $[A[0], \\ldots, A[P-1]]$ and $[B[0], \\ldots, B[R-1]]$ must be specified. The landmarks must be pairwise distinct, that is,\n\n* $A[i] \\neq A[j]$ for each $i$ and $j$ such that $0 \\le i < j < P$;\n* $B[i] \\neq B[j]$ for each $i$ and $j$ such that $0 \\le i < j < R$;\n* $A[i] \\neq B[j]$ for each $i$ and $j$ such that $0 \\le i < P$ and $0\\le j < R$.\n\nFor each call, the dispatcher reports whether there is a road connecting a landmark from $A$ and a landmark from $B$. More precisely, the dispatcher iterates over all pairs $i$ and $j$ such that $0 \\le i < P$ and $0\\le j < R$. If, for any of them, the landmarks $A[i]$ and $B[j]$ are connected by a road, the dispatcher returns true. Otherwise, the dispatcher returns false.\n\nA trip of length $l$ is a sequence of distinct landmarks $t[0], t[1], \\ldots, t[l-1]$, where for each $i$ between $0$ and $l-2$, inclusive, landmark $t[i]$ and landmark $t[i+1]$ are connected by a road. A trip of length $l$ is called a longest trip if there does not exist any trip of length at least $l+1$.\n\nYour task is to help the organizers to find a longest trip at Ópusztaszer by making calls to the dispatcher.\n\nImplementation Details\n\nYou should implement the following procedure:\n\nint[] longest\\_trip(int N, int D)\n\n* $N$: the number of landmarks at Ópusztaszer.\n* $D$: the guaranteed minimum density of the road network.\n* This procedure should return an array $t = [t[0], t[1], \\ldots, t[l-1]]$, representing a longest trip.\n* This procedure may be called multiple times in each test case.\n\nThe above procedure can make calls to the following procedure:\n\nbool are\\_connected(int[] A, int[] B)\n\n* $A$: a nonempty array of distinct landmarks.\n* $B$: a nonempty array of distinct landmarks.\n* $A$ and $B$ should be disjoint.\n* This procedure returns true if there is a landmark from $A$ and a landmark from $B$ connected by a road. Otherwise, it returns false.\n* This procedure can be called at most $32\\,640$ times in each invocation of longest\\_trip, and at most $150\\,000$ times in total.\n* The total length of arrays $A$ and $B$ passed to this procedure over all of its invocations cannot exceed $1\\,500\\,000$.\n\nThe grader is not adaptive. Each submission is graded on the same set of test cases. That is, the values of $N$ and $D$, as well as the pairs of landmarks connected by roads, are fixed for each call of longest\\_trip within each test case.\n\nInput\n\nLet $C$ denote the number of scenarios, that is, the number of calls to longest\\_trip. The sample grader reads the input in the following format:\n\n* line $1$: $C$\n\nThe descriptions of $C$ scenarios follow.\n\nThe sample grader reads the description of each scenario in the following format:\n\n* line $1$: $N \\; D$ ($3 \\le N \\le 256$, $1 \\le D \\le 3$)\n* line $1 + i$ ($1 \\le i < N$): $U_i[0] \\; U_i[1] \\; \\ldots \\; U_i[i-1]$\n\nThe sum of $N$ over all calls to longest\\_trip does not exceed $1\\,024$ in each test case.\n\nHere, each $U_i$ ($1 \\le i < N$) is an array of size $i$, describing which pairs of landmarks are connected by a road. For each $i$ and $j$ such that $1 \\le i < N$ and $0 \\le j < i$:\n\n* if landmarks $j$ and $i$ are connected by a road, then the value of $U_i[j]$ should be $1$;\n* if there is no road connecting landmarks $j$ and $i$, then the value of $U_i[j]$ should be $0$.\n\nOutput\n\nIn each scenario, before calling longest\\_trip, the sample grader checks whether the density of the road network is at least $D$. If this condition is not met, it prints the message Insufficient Density and terminates.\n\nIf the sample grader detects a protocol violation, the output of the sample grader is Protocol Violation: , where is one of the following error messages:\n\n* invalid array: in a call to are\\_connected, at least one of arrays $A$ and $B$\n + is empty, or\n + contains an element that is not an integer between $0$ and $N-1$, inclusive, or\n + contains the same element at least twice.\n* non-disjoint arrays: in a call to are\\_connected, arrays $A$ and $B$ are not disjoint.\n* too many calls: the number of calls made to are\\_connected exceeds $32\\,640$ over the current invocation of longest trip, or exceeds $150\\,000$ in total.\n* too many elements: the total number of landmarks passed to are\\_connected over all calls exceeds $1\\,500\\,000$.\n\nOtherwise, let the elements of the array returned by longest\\_trip in a scenario be $t[0], t[1], \\ldots, t[l - 1]$ for some nonnegative $l$. The sample grader prints three lines for this scenario in the following format:\n\n* line $1$: $l$\n* line $2$: $t[0] \\; t[1] \\; \\ldots \\; t[l-1]$\n* line $3$: the number of calls to are\\_connected over this scenario\n\nFinally, the sample grader prints:\n\n* line $1 + 3 \\cdot C$: the maximum number of calls to are\\_connected over all calls to longest\\_trip\n\nScoring\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 1 | 5 | $D = 3$ |\n| 2 | 10 | $D = 2$ |\n| 3 | 25 | $D = 1$. Let $l^\\star$ denote the length of a longest trip. Procedure longest\\_trip does not have to return a trip of length $l^\\star$. Instead, it should return a trip of length at least $\\left\\lceil \\frac{l^\\star}{2} \\right\\rceil$. |\n| 4 | 60 | $D = 1$ |\n\nIn subtask 4 your score is determined based on the number of calls to procedure are\\_connected over a single invocation of longest\\_trip. Let $q$ be the maximum number of calls among all invocations of longest\\_trip over every test case of the subtask. Your score for this subtask is calculated according to the following table:\n\n| | |\n| --- | --- |\n| Condition | Points |\n| $2\\,750 < q \\le 32\\,640$ | $20$ |\n| $550 < q \\le 2\\,750$ | $30$ |\n| $400 < q \\le 550$ | $45$ |\n| $q \\le 400$ | $60$ |\n\nIf, in any of the test cases, the calls to the procedure are\\_connected do not conform to the constraints described in Implementation Details, or the array returned by longest\\_trip is incorrect, the score of your solution for that subtask will be $0$.\n\nNote\n\nExample 1\n\nConsider a scenario in which $N = 5$, $D = 1$, and the road connections are as shown in the following figure:\n\n![](https://ioi.contest.codeforces.com/espresso/f4bf83607a9d69bfd64c93118342b7976b37cf4d.png)\n\nThe procedure longest\\_trip is called in the following way:\n\nlongest\\_trip(5, 1)\n\nThe procedure may make calls to are\\_connected as follows.\n\n| | | |\n| --- | --- | --- |\n| Call | Pairs connected by a road | Return value |\n| are\\_connected([0], [1, 2, 4, 3]) | $(0,1)$ and $(0,2)$ | true |\n| are\\_connected([2], [0]) | $(2,0)$ | true |\n| are\\_connected([2], [3]) | $(2,3)$ | true |\n| are\\_connected([1, 0], [4, 3]) | none | false |\n\nAfter the fourth call, it turns out that none of the pairs $(1,4)$, $(0,4)$, $(1,3)$ and $(0,3)$ is connected by a road. As the density of the network is at least $D = 1$, we see that from the triplet $(0, 3, 4)$, the pair $(3,4)$ must be connected by a road. Similarly to this, landmarks $0$ and $1$ must be connected.\n\nAt this point, it can be concluded that $t = [1, 0, 2, 3, 4]$ is a trip of length $5$, and that there does not exist a trip of length greater than $5$. Therefore, the procedure longest\\_trip may return $[1, 0, 2, 3, 4]$.\n\nConsider another scenario in which $N = 4$, $D = 1$, and the roads between the landmarks are as shown in the following figure:\n\n![](https://ioi.contest.codeforces.com/espresso/2e5b1767682f740de7b8f1faee2c50bfec482746.png)\n\nThe procedure longest\\_trip is called in the following way: longest\\_trip(4, 1)\n\nIn this scenario, the length of a longest trip is $2$. Therefore, after a few calls to procedure are\\_connected, the procedure longest\\_trip may return one of $[0, 1]$, $[1, 0]$, $[2, 3]$ or $[3, 2]$.\n\nExample 2\n\nSubtask 0 contains an additional example test case with $N=256$ landmarks. This test case is included in the attachment package that you can download from the contest system.", "interactor_files": {"manager.cpp": "#include \"testlib.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\ninline FILE *openFile(const char *name, const char *mode)\n{\n FILE *file = fopen(name, mode);\n if (!file)\n {\n quitf(_fail, \"Could not open file '%s' with mode '%s'\", name, mode);\n }\n return file;\n}\n\nstatic inline constexpr int maxNumberOfCalls = 32640;\nstatic inline constexpr int maxTotalNumberOfCalls = 150000;\nstatic inline constexpr int maxTotalNumberOfLandmarksInCalls = 1500000;\nstatic int call_counter = 0;\nstatic int total_call_counter = 0;\nstatic int landmark_counter = 0;\n\nint calculateLMax(int N, const std::vector> &U)\n{\n std::deque line1;\n line1.clear();\n std::deque line2;\n line2.clear();\n\n line1.push_back(0);\n\n for (int i = 1; i < N; i++)\n {\n if (U[i][line1.back()] == 1)\n {\n line1.push_back(i);\n }\n else if (!line2.empty() && U[i][line2.back()])\n {\n line2.push_back(i);\n }\n else\n {\n while (!line2.empty())\n {\n line1.push_back(line2.back());\n line2.pop_back();\n }\n line2.push_back(i);\n }\n }\n\n if (line1.size() < line2.size())\n swap(line1, line2);\n\n for (int i : line1)\n {\n for (int j : line2)\n {\n if (U[std::max(i, j)][std::min(i, j)] == 1)\n return N;\n }\n }\n return line1.size();\n}\n\nint main(int argc, char *argv[])\n{\n testlibMode = _checker;\n ouf.mode = _output;\n\n if (argc < 3)\n {\n quit(_fail, \"Insufficient number of args for manager of 'longesttrip'\");\n }\n\n { // Keep alive on broken pipes\n struct sigaction sa;\n sa.sa_handler = SIG_IGN;\n sigaction(SIGPIPE, &sa, NULL);\n }\n\n FILE *fout = openFile(argv[2], \"a\");\n FILE *fin = openFile(argv[1], \"r\");\n\n char subtask[10];\n int C;\n assert(2 == scanf(\"%s %d\", subtask, &C));\n\n fprintf(fout, \"%d\\n\", C);\n fflush(fout);\n\n int maximumCalls = 0;\n for (int c = 0; c < C; ++c)\n {\n int N, D;\n assert(2 == scanf(\"%d %d\", &N, &D));\n\n std::vector present(N, false);\n std::vector> U(N);\n for (int i = 1; i < N; ++i)\n {\n U[i].resize(i);\n for (int j = 0; j < i; ++j)\n {\n assert(1 == scanf(\"%d\", &U[i][j]));\n }\n }\n\n int lMax = calculateLMax(N, U);\n\n fprintf(fout, \"%d %d\\n\", N, D);\n fflush(fout);\n\n while (true)\n {\n {\n std::string input_secret = \"3kC2Ia2048BfyJVGojMUKKtilctlZKcB\";\n char secret[1000];\n if (fscanf(fin, \"%s\", secret) != 1)\n {\n quit(_pv, \"Could not read secret (possibly, an unexpected termination\"\n \" of the program).\");\n }\n if (std::string(secret) != input_secret)\n {\n quit(_pv, \"Secret mismatch (possible tampering with the output).\");\n }\n }\n\n int op;\n if (fscanf(fin, \"%d\", &op) != 1)\n {\n quit(_fail, \"Could not read op.\");\n }\n\n if (op == 0)\n {\n ++call_counter, ++total_call_counter;\n if (call_counter > maxNumberOfCalls || total_call_counter > maxTotalNumberOfCalls)\n {\n quit(_pv, \"too many calls\");\n }\n\n int nA, nB;\n if (fscanf(fin, \"%d %d\", &nA, &nB) != 2)\n {\n quit(_fail, \"Could not read arrays.\");\n }\n\n landmark_counter += nA + nB;\n if (landmark_counter > maxTotalNumberOfLandmarksInCalls)\n {\n quit(_pv, \"too many elements\");\n }\n\n if (nA <= 0 || nB <= 0 || nA + nB > N)\n {\n quit(_pv, \"invalid array\");\n }\n\n std::vector A(nA);\n for (int i = 0; i < nA; ++i)\n {\n if (fscanf(fin, \"%d\", &A[i]) != 1)\n {\n quit(_fail, \"Could not read array A.\");\n }\n if (A[i] < 0 || N <= A[i])\n {\n quit(_pv, \"invalid array\");\n }\n if (present[A[i]])\n {\n quit(_pv, \"invalid array\");\n }\n present[A[i]] = true;\n }\n for (int i = 0; i < nA; ++i)\n {\n present[A[i]] = false;\n }\n std::vector B(nB);\n for (int i = 0; i < nB; ++i)\n {\n if (fscanf(fin, \"%d\", &B[i]) != 1)\n {\n quit(_fail, \"Could not read array B.\");\n }\n if (B[i] < 0 || N <= B[i])\n {\n quit(_pv, \"invalid array\");\n }\n if (present[B[i]])\n {\n quit(_pv, \"invalid array\");\n }\n present[B[i]] = true;\n }\n for (int i = 0; i < nB; ++i)\n {\n present[B[i]] = false;\n }\n\n for (int i = 0; i < nA; ++i)\n {\n for (int j = 0; j < nB; ++j)\n {\n if (A[i] == B[j])\n {\n quit(_pv, \"non-disjoint arrays\");\n }\n }\n }\n\n bool connected = false;\n for (int i = 0; i < nA && !connected; ++i)\n {\n for (int j = 0; j < nB && !connected; ++j)\n {\n if (U[std::max(A[i], B[j])][std::min(A[i], B[j])] == 1)\n {\n connected = true;\n }\n }\n }\n\n fprintf(fout, \"%d\\n\", connected);\n fflush(fout);\n }\n else if (op == 1)\n {\n int l;\n if (fscanf(fin, \"%d\", &l) != 1)\n {\n quit(_fail, \"Could not read answer.\");\n }\n\n if (l < 0 || N < l)\n {\n quit(_wa);\n }\n\n std::vector answer(l);\n for (int i = 0; i < l; ++i)\n {\n if (fscanf(fin, \"%d\", &answer[i]) != 1)\n {\n quit(_fail, \"Could not read answer.\");\n }\n if (answer[i] < 0 || answer[i] >= N)\n {\n quit(_wa);\n }\n for (int j = 0; j < i; ++j)\n {\n if (answer[i] == answer[j])\n {\n quit(_wa);\n }\n }\n if (i > 0 && U[std::max(answer[i], answer[i - 1])][std::min(answer[i], answer[i - 1])] == 0)\n {\n quit(_wa);\n }\n }\n\n if (std::string(subtask) == \"D1Half\")\n {\n if (l < (lMax + 1) / 2)\n quit(_wa);\n }\n else\n {\n if (l < lMax)\n quit(_wa);\n }\n\n maximumCalls = std::max(maximumCalls, call_counter);\n call_counter = 0;\n\n int continueWithNextCall = 1;\n fprintf(fout, \"%d\\n\", continueWithNextCall);\n fflush(fout);\n\n break;\n }\n else\n {\n quit(_fail, \"Invalid op.\");\n }\n }\n }\n\n if (std::string(subtask) == \"D1\")\n {\n if (maximumCalls <= 400)\n {\n quit(_ok);\n }\n else if (maximumCalls <= 550)\n {\n quitp(0.75);\n }\n else if (maximumCalls <= 2750)\n {\n quitp(0.5);\n }\n else\n {\n quitp(1.0 / 3.0);\n }\n }\n else\n {\n quit(_ok);\n }\n\n return 0;\n}\n", "stub.cpp": "#include \"longesttrip.h\"\n\n#include \n#include \n#include \n#include \n\nbool are_connected(std::vector A, std::vector B)\n{\n {\n const std::string output_secret = \"3kC2Ia2048BfyJVGojMUKKtilctlZKcB\";\n printf(\"%s\\n\", output_secret.c_str());\n }\n int nA = A.size(), nB = B.size();\n printf(\"0 %d %d\", nA, nB);\n for (int x : A)\n {\n printf(\" %d\", x);\n }\n for (int x : B)\n {\n printf(\" %d\", x);\n }\n printf(\"\\n\");\n fflush(stdout);\n\n int connected;\n if (scanf(\"%d\", &connected) != 1)\n {\n exit(0);\n }\n return connected == 1;\n}\n\nint main(int argc, char *argv[])\n{\n assert(argc >= 3);\n stdin = fopen(argv[1], \"r\");\n stdout = fopen(argv[2], \"a\");\n\n int C;\n assert(1 == scanf(\"%d\", &C));\n\n for (int k = 0; k < C; ++k)\n {\n int N, D;\n assert(2 == scanf(\"%d %d\", &N, &D));\n\n std::vector answer = longest_trip(N, D);\n {\n const std::string output_secret = \"3kC2Ia2048BfyJVGojMUKKtilctlZKcB\";\n printf(\"%s\\n\", output_secret.c_str());\n }\n int l = answer.size();\n printf(\"1 %d\", l);\n for (int x : answer)\n {\n printf(\" %d\", x);\n }\n printf(\"\\n\");\n fflush(stdout);\n int continueWithNextCall = 0;\n if (scanf(\"%d\", &continueWithNextCall) != 1)\n {\n exit(0);\n }\n }\n\n return 0;\n}\n", "longesttrip.h": "#include \n\nstd::vector longest_trip(int N, int D);\n\nbool are_connected(std::vector A, std::vector B);\n", "testlib.h": "/*\n * It is strictly recommended to include \"testlib.h\" before any other include\n * in your code. In this case testlib overrides compiler specific \"random()\".\n *\n * If you can't compile your code and compiler outputs something about\n * ambiguous call of \"random_shuffle\", \"rand\" or \"srand\" it means that\n * you shouldn't use them. Use \"shuffle\", and \"rnd.next()\" instead of them\n * because these calls produce stable result for any C++ compiler. Read\n * sample generator sources for clarification.\n *\n * Please read the documentation for class \"random_t\" and use \"rnd\" instance in\n * generators. Probably, these sample calls will be usefull for you:\n * rnd.next(); rnd.next(100); rnd.next(1, 2);\n * rnd.next(3.14); rnd.next(\"[a-z]{1,100}\").\n *\n * Also read about wnext() to generate off-center random distribution.\n *\n * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker.\n */\n\n#ifndef _TESTLIB_H_\n#define _TESTLIB_H_\n\n/*\n * Copyright (c) 2005-2018\n */\n\n#define VERSION \"0.9.21\"\n\n/*\n * Mike Mirzayanov\n *\n * This material is provided \"as is\", with absolutely no warranty expressed\n * or implied. Any use is at your own risk.\n *\n * Permission to use or copy this software for any purpose is hereby granted\n * without fee, provided the above notices are retained on all copies.\n * Permission to modify the code and to distribute modified code is granted,\n * provided the above notices are retained, and a notice that the code was\n * modified is included with the above copyright notice.\n *\n */\n\n/*\n * Kian Mirjalali:\n *\n * Modified to be compatible with CMS & requirements for preparing IOI tasks\n *\n * * defined FOR_LINUX in order to force linux-based line endings in validators.\n *\n * * Changed the ordering of checker arguments\n * from \n * to \n *\n * * Added \"Security Violation\" & \"Protocol Violation\" as new result types.\n *\n * * Changed checker quit behaviors to make it compliant with CMS.\n *\n * * The checker exit codes should always be 0 in CMS.\n *\n * * For partial scoring, forced quitp() functions to accept only scores in the range [0,1].\n * If the partial score is less than 1e-5, it becomes 1e-5, because 0 grades are considered wrong in CMS.\n * Grades in range [1e-5, 0.0001) are printed exactly (to prevent rounding to zero).\n * Grades in [0.0001, 1] are printed with 4 digits after decimal point.\n *\n * * Added the following utility types/variables/functions/methods:\n * type HaltListener (as a function with no parameters or return values)\n * vector __haltListeners\n * void registerHaltListener(HaltListener haltListener)\n * void callHaltListeners() (which is called in quit)\n * void closeOnHalt(FILE* file)\n * void closeOnHalt(F& f) (template using f.close())\n * void InStream::readSecret(string secret, TResult mismatchResult, string mismatchMessage)\n * void InStream::readGraderResult()\n * +supporting conversion of graderResult to CMS result\n * void quitp(double), quitp(int)\n * void registerChecker(string probName, argc, argv)\n * void readBothSecrets(string secret)\n * void readBothGraderResults()\n * void quit(TResult)\n * bool compareTokens(string a, string b, char separator=' ')\n * void compareRemainingLines(int lineNo=1)\n * void skip_ok()\n *\n */\n\n/* NOTE: This file contains testlib library for C++.\n *\n * Check, using testlib running format:\n * check.exe [ [-appes]],\n * If result file is specified it will contain results.\n *\n * Validator, using testlib running format:\n * validator.exe < input.txt,\n * It will return non-zero exit code and writes message to standard output.\n *\n * Generator, using testlib running format:\n * gen.exe [parameter-1] [parameter-2] [... paramerter-n]\n * You can write generated test(s) into standard output or into the file(s).\n *\n * Interactor, using testlib running format:\n * interactor.exe [ [ [-appes]]],\n * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],\n * can be judged by checker later), reads program output from ouf (mapped to stdin),\n * writes output to program via stdout (use cout, printf, etc).\n */\n\nconst char *latestFeatures[] = {\n \"Fixed stringstream repeated usage issue\",\n \"Fixed compilation in g++ (for std=c++03)\",\n \"Batch of println functions (support collections, iterator ranges)\",\n \"Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation\",\n \"Allow any whitespace in readInts-like functions for non-validators\",\n \"Ignore 4+ command line arguments ifdef EJUDGE\",\n \"Speed up of vtos\",\n \"Show line number in validators in case of incorrect format\",\n \"Truncate huge checker/validator/interactor message\",\n \"Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type\",\n \"Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type\",\n \"Fixed compilation in VS 2015+\",\n \"Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines\",\n \"Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals\",\n \"Introduced split/tokenize functions to separate string by given char\",\n \"Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters\",\n \"Supported --testOverviewLogFileName for validator: bounds hits + features\",\n \"Fixed UB (sequence points) in random_t\",\n \"POINTS_EXIT_CODE returned back to 7 (instead of 0)\",\n \"Removed disable buffers for interactive problems, because it works unexpectedly in wine\",\n \"InStream over string: constructor of InStream from base InStream to inherit policies and std::string\",\n \"Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \\\"[n=%d,m=%d]\\\", n, m)\",\n \"Fixed incorrect interval parsing in patterns\",\n \"Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)\",\n \"Introduced disableFinalizeGuard() to switch off finalization checkings\",\n \"Use join() functions to format a range of items as a single string (separated by spaces or other separators)\",\n \"Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors\",\n \"Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7\",\n \"Fixed bug with nan in stringToDouble\",\n \"Fixed issue around overloads for size_t on x64\",\n \"Added attribute 'points' to the XML output in case of result=_points\",\n \"Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14\",\n \"Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading\",\n \"Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()\",\n \"Manual buffer in InStreams, some IO speed improvements\",\n \"Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true\",\n \"Introduced guard against missed quitf() in checker or readEof() in validators\",\n \"Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers\",\n \"Supported registerInteraction(argc, argv)\",\n \"Print checker message to the stderr instead of stdout\",\n \"Supported TResult _points to output calculated score, use quitp(...) functions\",\n \"Fixed to be compilable on Mac\",\n \"PC_BASE_EXIT_CODE=50 in case of defined TESTSYS\",\n \"Fixed issues 19-21, added __attribute__ format printf\",\n \"Some bug fixes\",\n \"ouf.readInt(1, 100) and similar calls return WA\",\n \"Modified random_t to avoid integer overflow\",\n \"Truncated checker output [patch by Stepan Gatilov]\",\n \"Renamed class random -> class random_t\",\n \"Supported name parameter for read-and-validation methods, like readInt(1, 2, \\\"n\\\")\",\n \"Fixed bug in readDouble()\",\n \"Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()\",\n \"Supported \\\"partially correct\\\", example: quitf(_pc(13), \\\"result=%d\\\", result)\",\n \"Added shuffle(begin, end), use it instead of random_shuffle(begin, end)\",\n \"Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode\",\n \"Package extended with samples of generators and validators\",\n \"Written the documentation for classes and public methods in testlib.h\",\n \"Implemented random routine to support generators, use registerGen() to switch it on\",\n \"Implemented strict mode to validate tests, use registerValidation() to switch it on\",\n \"Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output\",\n \"Added InStream::readLong() and removed InStream::readLongint()\",\n \"Now no footer added to each report by default (use directive FOOTER to switch on)\",\n \"Now every checker has a name, use setName(const char* format, ...) to set it\",\n \"Now it is compatible with TTS (by Kittens Computing)\",\n \"Added \\'ensure(condition, message = \\\"\\\")\\' feature, it works like assert()\",\n \"Fixed compatibility with MS C++ 7.1\",\n \"Added footer with exit code information\",\n \"Added compatibility with EJUDGE (compile with EJUDGE directive)\",\n \"Added compatibility with Contester (compile with CONTESTER directive)\"};\n\n#define FOR_LINUX\n\n#ifdef _MSC_VER\n#define _CRT_SECURE_NO_DEPRECATE\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_NO_VA_START_VALIDATION\n#endif\n\n/* Overrides random() for Borland C++. */\n#define random __random_deprecated\n#include \n#include \n#include \n#include \n#undef random\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if (_WIN32 || __WIN32__ || _WIN64 || __WIN64__ || __CYGWIN__)\n#if !defined(_MSC_VER) || _MSC_VER > 1400\n#define NOMINMAX 1\n#include \n#else\n#define WORD unsigned short\n#include \n#endif\n#include \n#define ON_WINDOWS\n#if defined(_MSC_VER) && _MSC_VER > 1400\n#pragma warning(disable : 4127)\n#pragma warning(disable : 4146)\n#pragma warning(disable : 4458)\n#endif\n#else\n#define WORD unsigned short\n#include \n#endif\n\n#if defined(FOR_WINDOWS) && defined(FOR_LINUX)\n#error Only one target system is allowed\n#endif\n\n#ifndef LLONG_MIN\n#define LLONG_MIN (-9223372036854775807LL - 1)\n#endif\n\n#ifndef ULLONG_MAX\n#define ULLONG_MAX (18446744073709551615)\n#endif\n\n#define LF ((char)10)\n#define CR ((char)13)\n#define TAB ((char)9)\n#define SPACE ((char)' ')\n#define EOFC (255)\n\n#ifndef OK_EXIT_CODE\n#ifdef CONTESTER\n#define OK_EXIT_CODE 0xAC\n#else\n#define OK_EXIT_CODE 0\n#endif\n#endif\n\n#ifndef WA_EXIT_CODE\n#ifdef EJUDGE\n#define WA_EXIT_CODE 5\n#elif defined(CONTESTER)\n#define WA_EXIT_CODE 0xAB\n#else\n#define WA_EXIT_CODE 1\n#endif\n#endif\n\n#ifndef PE_EXIT_CODE\n#ifdef EJUDGE\n#define PE_EXIT_CODE 4\n#elif defined(CONTESTER)\n#define PE_EXIT_CODE 0xAA\n#else\n#define PE_EXIT_CODE 2\n#endif\n#endif\n\n#ifndef FAIL_EXIT_CODE\n#ifdef EJUDGE\n#define FAIL_EXIT_CODE 6\n#elif defined(CONTESTER)\n#define FAIL_EXIT_CODE 0xA3\n#else\n#define FAIL_EXIT_CODE 3\n#endif\n#endif\n\n#ifndef DIRT_EXIT_CODE\n#ifdef EJUDGE\n#define DIRT_EXIT_CODE 6\n#else\n#define DIRT_EXIT_CODE 4\n#endif\n#endif\n\n#ifndef POINTS_EXIT_CODE\n#define POINTS_EXIT_CODE 7\n#endif\n\n#ifndef UNEXPECTED_EOF_EXIT_CODE\n#define UNEXPECTED_EOF_EXIT_CODE 8\n#endif\n\n#ifndef SV_EXIT_CODE\n#define SV_EXIT_CODE 20\n#endif\n\n#ifndef PV_EXIT_CODE\n#define PV_EXIT_CODE 21\n#endif\n\n#ifndef PC_BASE_EXIT_CODE\n#ifdef TESTSYS\n#define PC_BASE_EXIT_CODE 50\n#else\n#define PC_BASE_EXIT_CODE 0\n#endif\n#endif\n\n#ifdef __GNUC__\n#define __TESTLIB_STATIC_ASSERT(condition) typedef void *__testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))\n#else\n#define __TESTLIB_STATIC_ASSERT(condition) typedef void *__testlib_static_assert_type[(condition) ? 1 : -1]\n#endif\n\n#ifdef ON_WINDOWS\n#define I64 \"%I64d\"\n#define U64 \"%I64u\"\n#else\n#define I64 \"%lld\"\n#define U64 \"%llu\"\n#endif\n\n#ifdef _MSC_VER\n#define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n#define NORETURN __attribute__((noreturn))\n#else\n#define NORETURN\n#endif\n\n/**************** HaltListener material ****************/\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntypedef std::function HaltListener;\n#else\ntypedef void (*HaltListener)();\n#endif\n\nstd::vector __haltListeners;\n\ninline void registerHaltListener(HaltListener haltListener)\n{\n __haltListeners.push_back(haltListener);\n}\n\ninline void callHaltListeners()\n{\n // Removing and calling haltListeners in reverse order.\n while (!__haltListeners.empty())\n {\n HaltListener haltListener = __haltListeners.back();\n __haltListeners.pop_back();\n haltListener();\n }\n}\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ninline void closeOnHalt(FILE *file)\n{\n registerHaltListener([file]\n { fclose(file); });\n}\ntemplate \ninline void closeOnHalt(F &f)\n{\n registerHaltListener([&f]\n { f.close(); });\n}\n#endif\n/*******************************************************/\n\nstatic char __testlib_format_buffer[16777216];\nstatic int __testlib_format_buffer_usage_count = 0;\n\n#define FMT_TO_RESULT(fmt, cstr, result) \\\n std::string result; \\\n if (__testlib_format_buffer_usage_count != 0) \\\n __testlib_fail(\"FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0\"); \\\n __testlib_format_buffer_usage_count++; \\\n va_list ap; \\\n va_start(ap, fmt); \\\n vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \\\n va_end(ap); \\\n __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \\\n result = std::string(__testlib_format_buffer); \\\n __testlib_format_buffer_usage_count--;\n\nconst long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;\n\nNORETURN static void __testlib_fail(const std::string &message);\n\ntemplate \nstatic inline T __testlib_abs(const T &x)\n{\n return x > 0 ? x : -x;\n}\n\ntemplate \nstatic inline T __testlib_min(const T &a, const T &b)\n{\n return a < b ? a : b;\n}\n\ntemplate \nstatic inline T __testlib_max(const T &a, const T &b)\n{\n return a > b ? a : b;\n}\n\nstatic bool __testlib_prelimIsNaN(double r)\n{\n volatile double ra = r;\n#ifndef __BORLANDC__\n return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);\n#else\n return std::_isnan(ra);\n#endif\n}\n\nstatic std::string removeDoubleTrailingZeroes(std::string value)\n{\n while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)\n value = value.substr(0, value.length() - 1);\n return value + '0';\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 1, 2)))\n#endif\nstd::string\nformat(const char *fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt, result);\n return result;\n}\n\nstd::string format(const std::string fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt.c_str(), result);\n return result;\n}\n\nstatic std::string __testlib_part(const std::string &s);\n\nstatic bool __testlib_isNaN(double r)\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n volatile double ra = r;\n long long llr1, llr2;\n std::memcpy((void *)&llr1, (void *)&ra, sizeof(double));\n ra = -ra;\n std::memcpy((void *)&llr2, (void *)&ra, sizeof(double));\n long long llnan = 0xFFF8000000000000LL;\n return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;\n}\n\nstatic double __testlib_nan()\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n#ifndef NAN\n long long llnan = 0xFFF8000000000000LL;\n double nan;\n std::memcpy(&nan, &llnan, sizeof(double));\n return nan;\n#else\n return NAN;\n#endif\n}\n\nstatic bool __testlib_isInfinite(double r)\n{\n volatile double ra = r;\n return (ra > 1E300 || ra < -1E300);\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline bool\ndoubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)\n{\n if (__testlib_isNaN(expected))\n {\n return __testlib_isNaN(result);\n }\n else if (__testlib_isInfinite(expected))\n {\n if (expected > 0)\n {\n return result > 0 && __testlib_isInfinite(result);\n }\n else\n {\n return result < 0 && __testlib_isInfinite(result);\n }\n }\n else if (__testlib_isNaN(result) || __testlib_isInfinite(result))\n {\n return false;\n }\n else if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)\n {\n return true;\n }\n else\n {\n double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n return result + 1E-15 >= minv && result <= maxv + 1E-15;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline double\ndoubleDelta(double expected, double result)\n{\n double absolute = __testlib_abs(result - expected);\n\n if (__testlib_abs(expected) > 1E-9)\n {\n double relative = __testlib_abs(absolute / expected);\n return __testlib_min(absolute, relative);\n }\n else\n return absolute;\n}\n\n#if !defined(_MSC_VER) || _MSC_VER < 1900\n#ifndef _fileno\n#define _fileno(_stream) ((_stream)->_file)\n#endif\n#endif\n\n#ifndef O_BINARY\nstatic void __testlib_set_binary(\n#ifdef __GNUC__\n __attribute__((unused))\n#endif\n std::FILE *file)\n#else\nstatic void __testlib_set_binary(std::FILE *file)\n#endif\n{\n#ifdef O_BINARY\n if (NULL != file)\n {\n#ifndef __BORLANDC__\n _setmode(_fileno(file), O_BINARY);\n#else\n setmode(fileno(file), O_BINARY);\n#endif\n }\n#endif\n}\n\n/*\n * Very simple regex-like pattern.\n * It used for two purposes: validation and generation.\n *\n * For example, pattern(\"[a-z]{1,5}\").next(rnd) will return\n * random string from lowercase latin letters with length\n * from 1 to 5. It is easier to call rnd.next(\"[a-z]{1,5}\")\n * for the same effect.\n *\n * Another samples:\n * \"mike|john\" will generate (match) \"mike\" or \"john\";\n * \"-?[1-9][0-9]{0,3}\" will generate (match) non-zero integers from -9999 to 9999;\n * \"id-([ac]|b{2})\" will generate (match) \"id-a\", \"id-bb\", \"id-c\";\n * \"[^0-9]*\" will match sequences (empty or non-empty) without digits, you can't\n * use it for generations.\n *\n * You can't use pattern for generation if it contains meta-symbol '*'. Also it\n * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].\n *\n * For matching very simple greedy algorithm is used. For example, pattern\n * \"[0-9]?1\" will not match \"1\", because of greedy nature of matching.\n * Alternations (meta-symbols \"|\") are processed with brute-force algorithm, so\n * do not use many alternations in one expression.\n *\n * If you want to use one expression many times it is better to compile it into\n * a single pattern like \"pattern p(\"[a-z]+\")\". Later you can use\n * \"p.matches(std::string s)\" or \"p.next(random_t& rd)\" to check matching or generate\n * new string by pattern.\n *\n * Simpler way to read token and check it for pattern matching is \"inf.readToken(\"[a-z]+\")\".\n */\nclass random_t;\n\nclass pattern\n{\npublic:\n /* Create pattern instance by string. */\n pattern(std::string s);\n /* Generate new string by pattern and given random_t. */\n std::string next(random_t &rnd) const;\n /* Checks if given string match the pattern. */\n bool matches(const std::string &s) const;\n /* Returns source string of the pattern. */\n std::string src() const;\n\nprivate:\n bool matches(const std::string &s, size_t pos) const;\n\n std::string s;\n std::vector children;\n std::vector chars;\n int from;\n int to;\n};\n\n/*\n * Use random_t instances to generate random values. It is preffered\n * way to use randoms instead of rand() function or self-written\n * randoms.\n *\n * Testlib defines global variable \"rnd\" of random_t class.\n * Use registerGen(argc, argv, 1) to setup random_t seed be command\n * line (to use latest random generator version).\n *\n * Random generates uniformly distributed values if another strategy is\n * not specified explicitly.\n */\nclass random_t\n{\nprivate:\n unsigned long long seed;\n static const unsigned long long multiplier;\n static const unsigned long long addend;\n static const unsigned long long mask;\n static const int lim;\n\n long long nextBits(int bits)\n {\n if (bits <= 48)\n {\n seed = (seed * multiplier + addend) & mask;\n return (long long)(seed >> (48 - bits));\n }\n else\n {\n if (bits > 63)\n __testlib_fail(\"random_t::nextBits(int bits): n must be less than 64\");\n\n int lowerBitCount = (random_t::version == 0 ? 31 : 32);\n\n long long left = (nextBits(31) << 32);\n long long right = nextBits(lowerBitCount);\n\n return left ^ right;\n }\n }\n\npublic:\n static int version;\n\n /* New random_t with fixed seed. */\n random_t()\n : seed(3905348978240129619LL)\n {\n }\n\n /* Sets seed by command line. */\n void setSeed(int argc, char *argv[])\n {\n random_t p;\n\n seed = 3905348978240129619LL;\n for (int i = 1; i < argc; i++)\n {\n std::size_t le = std::strlen(argv[i]);\n for (std::size_t j = 0; j < le; j++)\n seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;\n seed += multiplier / addend;\n }\n\n seed = seed & mask;\n }\n\n /* Sets seed by given value. */\n void setSeed(long long _seed)\n {\n _seed = (_seed ^ multiplier) & mask;\n seed = _seed;\n }\n\n#ifndef __BORLANDC__\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(const std::string &ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#else\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(std::string ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#endif\n\n /* Random value in range [0, n-1]. */\n int next(int n)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(int n): n must be positive\");\n\n if ((n & -n) == n) // n is a power of 2\n return (int)((n * (long long)nextBits(31)) >> 31);\n\n const long long limit = INT_MAX / n * n;\n\n long long bits;\n do\n {\n bits = nextBits(31);\n } while (bits >= limit);\n\n return int(bits % n);\n }\n\n /* Random value in range [0, n-1]. */\n unsigned int next(unsigned int n)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::next(unsigned int n): n must be less INT_MAX\");\n return (unsigned int)next(int(n));\n }\n\n /* Random value in range [0, n-1]. */\n long long next(long long n)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(long long n): n must be positive\");\n\n const long long limit = __TESTLIB_LONGLONG_MAX / n * n;\n\n long long bits;\n do\n {\n bits = nextBits(63);\n } while (bits >= limit);\n\n return bits % n;\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long long next(unsigned long long n)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long long n): n must be less LONGLONG_MAX\");\n return (unsigned long long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n long next(long n)\n {\n return (long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long next(unsigned long n)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long n): n must be less LONG_MAX\");\n return (unsigned long)next((unsigned long long)(n));\n }\n\n /* Returns random value in range [from,to]. */\n int next(int from, int to)\n {\n return int(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n unsigned int next(unsigned int from, unsigned int to)\n {\n return (unsigned int)(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n long long next(long long from, long long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long long next(unsigned long long from, unsigned long long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n long next(long from, long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long next(unsigned long from, unsigned long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long from, unsigned long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Random double value in range [0, 1). */\n double next()\n {\n long long left = ((long long)(nextBits(26)) << 27);\n long long right = nextBits(27);\n return (double)(left + right) / (double)(1LL << 53);\n }\n\n /* Random double value in range [0, n). */\n double next(double n)\n {\n return n * next();\n }\n\n /* Random double value in range [from, to). */\n double next(double from, double to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(double from, double to): from can't not exceed to\");\n return next(to - from) + from;\n }\n\n /* Returns random element from container. */\n template \n typename Container::value_type any(const Container &c)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Container& c): c.size() must be positive\");\n return *(c.begin() + next(size));\n }\n\n /* Returns random element from iterator range. */\n template \n typename Iter::value_type any(const Iter &begin, const Iter &end)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end): range must have positive length\");\n return *(begin + next(size));\n }\n\n /* Random string value by given pattern (see pattern documentation). */\n#ifdef __GNUC__\n __attribute__((format(printf, 2, 3)))\n#endif\n std::string\n next(const char *format, ...)\n {\n FMT_TO_RESULT(format, format, ptrn);\n return next(ptrn);\n }\n\n /*\n * Weighted next. If type == 0 than it is usual \"next()\".\n *\n * If type = 1, than it returns \"max(next(), next())\"\n * (the number of \"max\" functions equals to \"type\").\n *\n * If type < 0, than \"max\" function replaces with \"min\".\n */\n int wnext(int n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(int n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n int result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n\n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n\n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));\n\n return int(n * p);\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n long long wnext(long long n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(long long n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n long long result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n\n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n\n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, -type + 1);\n\n return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(int type)\n {\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n\n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return result;\n }\n else\n {\n double p;\n\n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, -type + 1);\n\n return p;\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(double n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(double n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n\n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return n * result;\n }\n else\n {\n double p;\n\n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, -type + 1);\n\n return n * p;\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned int wnext(unsigned int n, int type)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::wnext(unsigned int n, int type): n must be less INT_MAX\");\n return (unsigned int)wnext(int(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long long wnext(unsigned long long n, int type)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX\");\n\n return (unsigned long long)wnext((long long)(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n long wnext(long n, int type)\n {\n return (long)wnext((long long)(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long wnext(unsigned long n, int type)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long n, int type): n must be less LONG_MAX\");\n\n return (unsigned long)wnext((unsigned long long)(n), type);\n }\n\n /* Returns weighted random value in range [from, to]. */\n int wnext(int from, int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(int from, int to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n\n /* Returns weighted random value in range [from, to]. */\n int wnext(unsigned int from, unsigned int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to\");\n return int(wnext(to - from + 1, type) + from);\n }\n\n /* Returns weighted random value in range [from, to]. */\n long long wnext(long long from, long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long long from, long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n\n /* Returns weighted random value in range [from, to]. */\n unsigned long long wnext(unsigned long long from, unsigned long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n\n /* Returns weighted random value in range [from, to]. */\n long wnext(long from, long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long from, long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n\n /* Returns weighted random value in range [from, to]. */\n unsigned long wnext(unsigned long from, unsigned long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n\n /* Returns weighted random double value in range [from, to). */\n double wnext(double from, double to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(double from, double to, int type): from can't not exceed to\");\n return wnext(to - from, type) + from;\n }\n\n /* Returns weighted random element from container. */\n template \n typename Container::value_type wany(const Container &c, int type)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::wany(const Container& c, int type): c.size() must be positive\");\n return *(c.begin() + wnext(size, type));\n }\n\n /* Returns weighted random element from iterator range. */\n template \n typename Iter::value_type wany(const Iter &begin, const Iter &end, int type)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length\");\n return *(begin + wnext(size, type));\n }\n\n template \n std::vector perm(T size, E first)\n {\n if (size <= 0)\n __testlib_fail(\"random_t::perm(T size, E first = 0): size must be positive\");\n std::vector p(size);\n for (T i = 0; i < size; i++)\n p[i] = first + i;\n if (size > 1)\n for (T i = 1; i < size; i++)\n std::swap(p[i], p[next(i + 1)]);\n return p;\n }\n\n template \n std::vector perm(T size)\n {\n return perm(size, T(0));\n }\n};\n\nconst int random_t::lim = 25;\nconst unsigned long long random_t::multiplier = 0x5DEECE66DLL;\nconst unsigned long long random_t::addend = 0xBLL;\nconst unsigned long long random_t::mask = (1LL << 48) - 1;\nint random_t::version = -1;\n\n/* Pattern implementation */\nbool pattern::matches(const std::string &s) const\n{\n return matches(s, 0);\n}\n\nstatic bool __pattern_isSlash(const std::string &s, size_t pos)\n{\n return s[pos] == '\\\\';\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic bool\n__pattern_isCommandChar(const std::string &s, size_t pos, char value)\n{\n if (pos >= s.length())\n return false;\n\n int slashes = 0;\n\n int before = int(pos) - 1;\n while (before >= 0 && s[before] == '\\\\')\n before--, slashes++;\n\n return slashes % 2 == 0 && s[pos] == value;\n}\n\nstatic char __pattern_getChar(const std::string &s, size_t &pos)\n{\n if (__pattern_isSlash(s, pos))\n pos += 2;\n else\n pos++;\n\n return s[pos - 1];\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic int\n__pattern_greedyMatch(const std::string &s, size_t pos, const std::vector chars)\n{\n int result = 0;\n\n while (pos < s.length())\n {\n char c = s[pos++];\n if (!std::binary_search(chars.begin(), chars.end(), c))\n break;\n else\n result++;\n }\n\n return result;\n}\n\nstd::string pattern::src() const\n{\n return s;\n}\n\nbool pattern::matches(const std::string &s, size_t pos) const\n{\n std::string result;\n\n if (to > 0)\n {\n int size = __pattern_greedyMatch(s, pos, chars);\n if (size < from)\n return false;\n if (size > to)\n size = to;\n pos += size;\n }\n\n if (children.size() > 0)\n {\n for (size_t child = 0; child < children.size(); child++)\n if (children[child].matches(s, pos))\n return true;\n return false;\n }\n else\n return pos == s.length();\n}\n\nstd::string pattern::next(random_t &rnd) const\n{\n std::string result;\n result.reserve(20);\n\n if (to == INT_MAX)\n __testlib_fail(\"pattern::next(random_t& rnd): can't process character '*' for generation\");\n\n if (to > 0)\n {\n int count = rnd.next(to - from + 1) + from;\n for (int i = 0; i < count; i++)\n result += chars[rnd.next(int(chars.size()))];\n }\n\n if (children.size() > 0)\n {\n int child = rnd.next(int(children.size()));\n result += children[child].next(rnd);\n }\n\n return result;\n}\n\nstatic void __pattern_scanCounts(const std::string &s, size_t &pos, int &from, int &to)\n{\n if (pos >= s.length())\n {\n from = to = 1;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '{'))\n {\n std::vector parts;\n std::string part;\n\n pos++;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))\n {\n if (__pattern_isCommandChar(s, pos, ','))\n parts.push_back(part), part = \"\", pos++;\n else\n part += __pattern_getChar(s, pos);\n }\n\n if (part != \"\")\n parts.push_back(part);\n\n if (!__pattern_isCommandChar(s, pos, '}'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (parts.size() < 1 || parts.size() > 2)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector numbers;\n\n for (size_t i = 0; i < parts.size(); i++)\n {\n if (parts[i].length() == 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n int number;\n if (std::sscanf(parts[i].c_str(), \"%d\", &number) != 1)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n numbers.push_back(number);\n }\n\n if (numbers.size() == 1)\n from = to = numbers[0];\n else\n from = numbers[0], to = numbers[1];\n\n if (from > to)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n }\n else\n {\n if (__pattern_isCommandChar(s, pos, '?'))\n {\n from = 0, to = 1, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '*'))\n {\n from = 0, to = INT_MAX, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '+'))\n {\n from = 1, to = INT_MAX, pos++;\n return;\n }\n\n from = to = 1;\n }\n}\n\nstatic std::vector __pattern_scanCharSet(const std::string &s, size_t &pos)\n{\n if (pos >= s.length())\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector result;\n\n if (__pattern_isCommandChar(s, pos, '['))\n {\n pos++;\n bool negative = __pattern_isCommandChar(s, pos, '^');\n\n char prev = 0;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))\n {\n if (__pattern_isCommandChar(s, pos, '-') && prev != 0)\n {\n pos++;\n\n if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']'))\n {\n result.push_back(prev);\n prev = '-';\n continue;\n }\n\n char next = __pattern_getChar(s, pos);\n if (prev > next)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n for (char c = prev; c != next; c++)\n result.push_back(c);\n result.push_back(next);\n\n prev = 0;\n }\n else\n {\n if (prev != 0)\n result.push_back(prev);\n prev = __pattern_getChar(s, pos);\n }\n }\n\n if (prev != 0)\n result.push_back(prev);\n\n if (!__pattern_isCommandChar(s, pos, ']'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (negative)\n {\n std::sort(result.begin(), result.end());\n std::vector actuals;\n for (int code = 0; code < 255; code++)\n {\n char c = char(code);\n if (!std::binary_search(result.begin(), result.end(), c))\n actuals.push_back(c);\n }\n result = actuals;\n }\n\n std::sort(result.begin(), result.end());\n }\n else\n result.push_back(__pattern_getChar(s, pos));\n\n return result;\n}\n\npattern::pattern(std::string s) : s(s), from(0), to(0)\n{\n std::string t;\n for (size_t i = 0; i < s.length(); i++)\n if (!__pattern_isCommandChar(s, i, ' '))\n t += s[i];\n s = t;\n\n int opened = 0;\n int firstClose = -1;\n std::vector seps;\n\n for (size_t i = 0; i < s.length(); i++)\n {\n if (__pattern_isCommandChar(s, i, '('))\n {\n opened++;\n continue;\n }\n\n if (__pattern_isCommandChar(s, i, ')'))\n {\n opened--;\n if (opened == 0 && firstClose == -1)\n firstClose = int(i);\n continue;\n }\n\n if (opened < 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (__pattern_isCommandChar(s, i, '|') && opened == 0)\n seps.push_back(int(i));\n }\n\n if (opened != 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (seps.size() == 0 && firstClose + 1 == (int)s.length() && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))\n {\n children.push_back(pattern(s.substr(1, s.length() - 2)));\n }\n else\n {\n if (seps.size() > 0)\n {\n seps.push_back(int(s.length()));\n int last = 0;\n\n for (size_t i = 0; i < seps.size(); i++)\n {\n children.push_back(pattern(s.substr(last, seps[i] - last)));\n last = seps[i] + 1;\n }\n }\n else\n {\n size_t pos = 0;\n chars = __pattern_scanCharSet(s, pos);\n __pattern_scanCounts(s, pos, from, to);\n if (pos < s.length())\n children.push_back(pattern(s.substr(pos)));\n }\n }\n}\n/* End of pattern implementation */\n\ntemplate \ninline bool isEof(C c)\n{\n return c == EOFC;\n}\n\ntemplate \ninline bool isEoln(C c)\n{\n return (c == LF || c == CR);\n}\n\ntemplate \ninline bool isBlanks(C c)\n{\n return (c == LF || c == CR || c == SPACE || c == TAB);\n}\n\nenum TMode\n{\n _input,\n _output,\n _answer\n};\n\n/* Outcomes 6-15 are reserved for future use. */\nenum TResult\n{\n _ok = 0,\n _wa = 1,\n _pe = 2,\n _fail = 3,\n _dirt = 4,\n _points = 5,\n _unexpected_eof = 8,\n _sv = 10,\n _pv = 11,\n _partially = 16\n};\n\nenum TTestlibMode\n{\n _unknown,\n _checker,\n _validator,\n _generator,\n _interactor\n};\n\n#define _pc(exitCode) (TResult(_partially + (exitCode)))\n\n/* Outcomes 6-15 are reserved for future use. */\nconst std::string outcomes[] = {\n \"accepted\",\n \"wrong-answer\",\n \"presentation-error\",\n \"fail\",\n \"fail\",\n#ifndef PCMS2\n \"points\",\n#else\n \"relative-scoring\",\n#endif\n \"reserved\",\n \"reserved\",\n \"unexpected-eof\",\n \"reserved\",\n \"security-violation\",\n \"protocol-violation\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"partially-correct\"};\n\nclass InputStreamReader\n{\npublic:\n virtual int curChar() = 0;\n virtual int nextChar() = 0;\n virtual void skipChar() = 0;\n virtual void unreadChar(int c) = 0;\n virtual std::string getName() = 0;\n virtual bool eof() = 0;\n virtual void close() = 0;\n virtual int getLine() = 0;\n virtual ~InputStreamReader() = 0;\n};\n\nInputStreamReader::~InputStreamReader()\n{\n // No operations.\n}\n\nclass StringInputStreamReader : public InputStreamReader\n{\nprivate:\n std::string s;\n size_t pos;\n\npublic:\n StringInputStreamReader(const std::string &content) : s(content), pos(0)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (pos >= s.length())\n return EOFC;\n else\n return s[pos];\n }\n\n int nextChar()\n {\n if (pos >= s.length())\n {\n pos++;\n return EOFC;\n }\n else\n return s[pos++];\n }\n\n void skipChar()\n {\n pos++;\n }\n\n void unreadChar(int c)\n {\n if (pos == 0)\n __testlib_fail(\"FileFileInputStreamReader::unreadChar(int): pos == 0.\");\n pos--;\n if (pos < s.length())\n s[pos] = char(c);\n }\n\n std::string getName()\n {\n return __testlib_part(s);\n }\n\n int getLine()\n {\n return -1;\n }\n\n bool eof()\n {\n return pos >= s.length();\n }\n\n void close()\n {\n // No operations.\n }\n};\n\nclass FileInputStreamReader : public InputStreamReader\n{\nprivate:\n std::FILE *file;\n std::string name;\n int line;\n std::vector undoChars;\n\n inline int postprocessGetc(int getcResult)\n {\n if (getcResult != EOF)\n return getcResult;\n else\n return EOFC;\n }\n\n int getc(FILE *file)\n {\n int c;\n if (undoChars.empty())\n c = ::getc(file);\n else\n {\n c = undoChars.back();\n undoChars.pop_back();\n }\n\n if (c == LF)\n line++;\n return c;\n }\n\n int ungetc(int c /*, FILE* file*/)\n {\n if (c == LF)\n line--;\n undoChars.push_back(c);\n return c;\n }\n\npublic:\n FileInputStreamReader(std::FILE *file, const std::string &name) : file(file), name(name), line(1)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (feof(file))\n return EOFC;\n else\n {\n int c = getc(file);\n ungetc(c /*, file*/);\n return postprocessGetc(c);\n }\n }\n\n int nextChar()\n {\n if (feof(file))\n return EOFC;\n else\n return postprocessGetc(getc(file));\n }\n\n void skipChar()\n {\n getc(file);\n }\n\n void unreadChar(int c)\n {\n ungetc(c /*, file*/);\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n\n bool eof()\n {\n if (NULL == file || feof(file))\n return true;\n else\n {\n int c = nextChar();\n if (c == EOFC || (c == EOF && feof(file)))\n return true;\n unreadChar(c);\n return false;\n }\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nclass BufferedFileInputStreamReader : public InputStreamReader\n{\nprivate:\n static const size_t BUFFER_SIZE;\n static const size_t MAX_UNREAD_COUNT;\n\n std::FILE *file;\n char *buffer;\n bool *isEof;\n int bufferPos;\n size_t bufferSize;\n\n std::string name;\n int line;\n\n bool refill()\n {\n if (NULL == file)\n __testlib_fail(\"BufferedFileInputStreamReader: file == NULL (\" + getName() + \")\");\n\n if (bufferPos >= int(bufferSize))\n {\n size_t readSize = fread(\n buffer + MAX_UNREAD_COUNT,\n 1,\n BUFFER_SIZE - MAX_UNREAD_COUNT,\n file);\n\n if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT && ferror(file))\n __testlib_fail(\"BufferedFileInputStreamReader: unable to read (\" + getName() + \")\");\n\n bufferSize = MAX_UNREAD_COUNT + readSize;\n bufferPos = int(MAX_UNREAD_COUNT);\n std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);\n\n return readSize > 0;\n }\n else\n return true;\n }\n\n char increment()\n {\n char c;\n if ((c = buffer[bufferPos++]) == LF)\n line++;\n return c;\n }\n\npublic:\n BufferedFileInputStreamReader(std::FILE *file, const std::string &name) : file(file), name(name), line(1)\n {\n buffer = new char[BUFFER_SIZE];\n isEof = new bool[BUFFER_SIZE];\n bufferSize = MAX_UNREAD_COUNT;\n bufferPos = int(MAX_UNREAD_COUNT);\n }\n\n ~BufferedFileInputStreamReader()\n {\n if (NULL != buffer)\n {\n delete[] buffer;\n buffer = NULL;\n }\n if (NULL != isEof)\n {\n delete[] isEof;\n isEof = NULL;\n }\n }\n\n int curChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : buffer[bufferPos];\n }\n\n int nextChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : increment();\n }\n\n void skipChar()\n {\n increment();\n }\n\n void unreadChar(int c)\n {\n bufferPos--;\n if (bufferPos < 0)\n __testlib_fail(\"BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0\");\n isEof[bufferPos] = (c == EOFC);\n buffer[bufferPos] = char(c);\n if (c == LF)\n line--;\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n\n bool eof()\n {\n return !refill() || EOFC == curChar();\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nconst size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;\nconst size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2;\n\n/*\n * Streams to be used for reading data in checkers or validators.\n * Each read*() method moves pointer to the next character after the\n * read value.\n */\nstruct InStream\n{\n /* Do not use them. */\n InStream();\n ~InStream();\n\n /* Wrap std::string with InStream. */\n InStream(const InStream &baseStream, std::string content);\n\n InputStreamReader *reader;\n int lastLine;\n\n std::string name;\n TMode mode;\n bool opened;\n bool stdfile;\n bool strict;\n\n int wordReserveSize;\n std::string _tmpReadToken;\n\n int readManyIteration;\n size_t maxFileSize;\n size_t maxTokenLength;\n size_t maxMessageLength;\n\n void init(std::string fileName, TMode mode);\n void init(std::FILE *f, TMode mode);\n\n /* Moves stream pointer to the first non-white-space character or EOF. */\n void skipBlanks();\n\n /* Returns current character in the stream. Doesn't remove it from stream. */\n char curChar();\n /* Moves stream pointer one character forward. */\n void skipChar();\n /* Returns current character and moves pointer one character forward. */\n char nextChar();\n\n /* Returns current character and moves pointer one character forward. */\n char readChar();\n /* As \"readChar()\" but ensures that the result is equal to given parameter. */\n char readChar(char c);\n /* As \"readChar()\" but ensures that the result is equal to the space (code=32). */\n char readSpace();\n /* Puts back the character into the stream. */\n void unreadChar(char c);\n\n /* Reopens stream, you should not use it. */\n void reset(std::FILE *file = NULL);\n /* Checks that current position is EOF. If not it doesn't move stream pointer. */\n bool eof();\n /* Moves pointer to the first non-white-space character and calls \"eof()\". */\n bool seekEof();\n\n /*\n * Checks that current position contains EOLN.\n * If not it doesn't move stream pointer.\n * In strict mode expects \"#13#10\" for windows or \"#10\" for other platforms.\n */\n bool eoln();\n /* Moves pointer to the first non-space and non-tab character and calls \"eoln()\". */\n bool seekEoln();\n\n /* Moves stream pointer to the first character of the next line (if exists). */\n void nextLine();\n\n /*\n * Reads new token. Ignores white-spaces into the non-strict mode\n * (strict mode is used in validators usually).\n */\n std::string readWord();\n /* The same as \"readWord()\", it is preffered to use \"readToken()\". */\n std::string readToken();\n /* The same as \"readWord()\", but ensures that token matches to given pattern. */\n std::string readWord(const std::string &ptrn, const std::string &variableName = \"\");\n std::string readWord(const pattern &p, const std::string &variableName = \"\");\n std::vector readWords(int size, const std::string &ptrn, const std::string &variablesName = \"\", int indexBase = 1);\n std::vector readWords(int size, const pattern &p, const std::string &variablesName = \"\", int indexBase = 1);\n /* The same as \"readToken()\", but ensures that token matches to given pattern. */\n std::string readToken(const std::string &ptrn, const std::string &variableName = \"\");\n std::string readToken(const pattern &p, const std::string &variableName = \"\");\n std::vector readTokens(int size, const std::string &ptrn, const std::string &variablesName = \"\", int indexBase = 1);\n std::vector readTokens(int size, const pattern &p, const std::string &variablesName = \"\", int indexBase = 1);\n\n void readWordTo(std::string &result);\n void readWordTo(std::string &result, const pattern &p, const std::string &variableName = \"\");\n void readWordTo(std::string &result, const std::string &ptrn, const std::string &variableName = \"\");\n\n void readTokenTo(std::string &result);\n void readTokenTo(std::string &result, const pattern &p, const std::string &variableName = \"\");\n void readTokenTo(std::string &result, const std::string &ptrn, const std::string &variableName = \"\");\n\n /*\n * Reads new long long value. Ignores white-spaces into the non-strict mode\n * (strict mode is used in validators usually).\n */\n long long readLong();\n unsigned long long readUnsignedLong();\n /*\n * Reads new int. Ignores white-spaces into the non-strict mode\n * (strict mode is used in validators usually).\n */\n int readInteger();\n /*\n * Reads new int. Ignores white-spaces into the non-strict mode\n * (strict mode is used in validators usually).\n */\n int readInt();\n\n /* As \"readLong()\" but ensures that value in the range [minv,maxv]. */\n long long readLong(long long minv, long long maxv, const std::string &variableName = \"\");\n /* Reads space-separated sequence of long longs. */\n std::vector readLongs(int size, long long minv, long long maxv, const std::string &variablesName = \"\", int indexBase = 1);\n\n unsigned long long readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName = \"\");\n std::vector readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName = \"\", int indexBase = 1);\n unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName = \"\");\n std::vector readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName = \"\", int indexBase = 1);\n\n /* As \"readInteger()\" but ensures that value in the range [minv,maxv]. */\n int readInteger(int minv, int maxv, const std::string &variableName = \"\");\n /* As \"readInt()\" but ensures that value in the range [minv,maxv]. */\n int readInt(int minv, int maxv, const std::string &variableName = \"\");\n /* Reads space-separated sequence of integers. */\n std::vector readIntegers(int size, int minv, int maxv, const std::string &variablesName = \"\", int indexBase = 1);\n /* Reads space-separated sequence of integers. */\n std::vector readInts(int size, int minv, int maxv, const std::string &variablesName = \"\", int indexBase = 1);\n\n /*\n * Reads new double. Ignores white-spaces into the non-strict mode\n * (strict mode is used in validators usually).\n */\n double readReal();\n /*\n * Reads new double. Ignores white-spaces into the non-strict mode\n * (strict mode is used in validators usually).\n */\n double readDouble();\n\n /* As \"readReal()\" but ensures that value in the range [minv,maxv]. */\n double readReal(double minv, double maxv, const std::string &variableName = \"\");\n std::vector readReals(int size, double minv, double maxv, const std::string &variablesName = \"\", int indexBase = 1);\n /* As \"readDouble()\" but ensures that value in the range [minv,maxv]. */\n double readDouble(double minv, double maxv, const std::string &variableName = \"\");\n std::vector readDoubles(int size, double minv, double maxv, const std::string &variablesName = \"\", int indexBase = 1);\n\n /*\n * As \"readReal()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variableName = \"\");\n std::vector readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variablesName = \"\", int indexBase = 1);\n\n /*\n * As \"readDouble()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variableName = \"\");\n std::vector readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variablesName = \"\", int indexBase = 1);\n\n /* As readLine(). */\n std::string readString();\n /* Read many lines. */\n std::vector readStrings(int size, int indexBase = 1);\n /* See readLine(). */\n void readStringTo(std::string &result);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const pattern &p, const std::string &variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const std::string &ptrn, const std::string &variableName = \"\");\n /* Read many lines. */\n std::vector readStrings(int size, const pattern &p, const std::string &variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readStrings(int size, const std::string &ptrn, const std::string &variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string &result, const pattern &p, const std::string &variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName = \"\");\n\n /*\n * Reads line from the current position to EOLN or EOF. Moves stream pointer to\n * the first character of the new line (if possible).\n */\n std::string readLine();\n /* Read many lines. */\n std::vector readLines(int size, int indexBase = 1);\n /* See readLine(). */\n void readLineTo(std::string &result);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const pattern &p, const std::string &variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const std::string &ptrn, const std::string &variableName = \"\");\n /* Read many lines. */\n std::vector readLines(int size, const pattern &p, const std::string &variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readLines(int size, const std::string &ptrn, const std::string &variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string &result, const pattern &p, const std::string &variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string &result, const std::string &ptrn, const std::string &variableName = \"\");\n\n /* Reads EOLN or fails. Use it in validators. Calls \"eoln()\" method internally. */\n void readEoln();\n /* Reads EOF or fails. Use it in validators. Calls \"eof()\" method internally. */\n void readEof();\n\n /*\n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quit(TResult result, const char *msg);\n /*\n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quitf(TResult result, const char *msg, ...);\n /*\n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quits(TResult result, std::string msg);\n\n/*\n * Checks condition and aborts a program if codition is false.\n * Returns _wa for ouf and _fail on any other streams.\n */\n#ifdef __GNUC__\n __attribute__((format(printf, 3, 4)))\n#endif\n void\n ensuref(bool cond, const char *format, ...);\n void __testlib_ensure(bool cond, std::string message);\n\n void close();\n\n const static int NO_INDEX = INT_MAX;\n\n const static WORD LightGray = 0x07;\n const static WORD LightRed = 0x0c;\n const static WORD LightCyan = 0x0b;\n const static WORD LightGreen = 0x0a;\n const static WORD LightYellow = 0x0e;\n const static WORD LightMagenta = 0x0d;\n\n static void textColor(WORD color);\n static void quitscr(WORD color, const char *msg);\n static void quitscrS(WORD color, std::string msg);\n void xmlSafeWrite(std::FILE *file, const char *msg);\n\n void readSecret(std::string secret, TResult mismatchResult = _pv, std::string mismatchMessage = \"Secret mismatch\");\n void readGraderResult();\n\nprivate:\n InStream(const InStream &);\n InStream &operator=(const InStream &);\n void quitByGraderResult(TResult result, std::string defaultMessage);\n};\n\nInStream inf;\nInStream ouf;\nInStream ans;\nbool appesMode;\nstd::string resultName;\nstd::string checkerName = \"untitled checker\";\nrandom_t rnd;\nTTestlibMode testlibMode = _unknown;\ndouble __testlib_points = std::numeric_limits::infinity();\n\nstruct ValidatorBoundsHit\n{\n static const double EPS;\n bool minHit;\n bool maxHit;\n\n ValidatorBoundsHit(bool minHit = false, bool maxHit = false) : minHit(minHit), maxHit(maxHit){};\n\n ValidatorBoundsHit merge(const ValidatorBoundsHit &validatorBoundsHit)\n {\n return ValidatorBoundsHit(\n __testlib_max(minHit, validatorBoundsHit.minHit),\n __testlib_max(maxHit, validatorBoundsHit.maxHit));\n }\n};\n\nconst double ValidatorBoundsHit::EPS = 1E-12;\n\nclass Validator\n{\nprivate:\n std::string _testset;\n std::string _group;\n std::string _testOverviewLogFileName;\n std::map _boundsHitByVariableName;\n std::set _features;\n std::set _hitFeatures;\n\n bool isVariableNameBoundsAnalyzable(const std::string &variableName)\n {\n for (size_t i = 0; i < variableName.length(); i++)\n if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')\n return false;\n return true;\n }\n\n bool isFeatureNameAnalyzable(const std::string &featureName)\n {\n for (size_t i = 0; i < featureName.length(); i++)\n if (featureName[i] < ' ')\n return false;\n return true;\n }\n\npublic:\n Validator() : _testset(\"tests\"), _group()\n {\n }\n\n std::string testset() const\n {\n return _testset;\n }\n\n std::string group() const\n {\n return _group;\n }\n\n std::string testOverviewLogFileName() const\n {\n return _testOverviewLogFileName;\n }\n\n void setTestset(const char *const testset)\n {\n _testset = testset;\n }\n\n void setGroup(const char *const group)\n {\n _group = group;\n }\n\n void setTestOverviewLogFileName(const char *const testOverviewLogFileName)\n {\n _testOverviewLogFileName = testOverviewLogFileName;\n }\n\n void addBoundsHit(const std::string &variableName, ValidatorBoundsHit boundsHit)\n {\n if (isVariableNameBoundsAnalyzable(variableName))\n {\n _boundsHitByVariableName[variableName] = boundsHit.merge(_boundsHitByVariableName[variableName]);\n }\n }\n\n std::string getBoundsHitLog()\n {\n std::string result;\n for (std::map::iterator i = _boundsHitByVariableName.begin();\n i != _boundsHitByVariableName.end();\n i++)\n {\n result += \"\\\"\" + i->first + \"\\\":\";\n if (i->second.minHit)\n result += \" min-value-hit\";\n if (i->second.maxHit)\n result += \" max-value-hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n std::string getFeaturesLog()\n {\n std::string result;\n for (std::set::iterator i = _features.begin();\n i != _features.end();\n i++)\n {\n result += \"feature \\\"\" + *i + \"\\\":\";\n if (_hitFeatures.count(*i))\n result += \" hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n void writeTestOverviewLog()\n {\n if (!_testOverviewLogFileName.empty())\n {\n std::string fileName(_testOverviewLogFileName);\n _testOverviewLogFileName = \"\";\n FILE *testOverviewLogFile = fopen(fileName.c_str(), \"w\");\n if (NULL == testOverviewLogFile)\n __testlib_fail(\"Validator::writeTestOverviewLog: can't test overview log to (\" + fileName + \")\");\n fprintf(testOverviewLogFile, \"%s%s\", getBoundsHitLog().c_str(), getFeaturesLog().c_str());\n if (fclose(testOverviewLogFile))\n __testlib_fail(\"Validator::writeTestOverviewLog: can't close test overview log file (\" + fileName + \")\");\n }\n }\n\n void addFeature(const std::string &feature)\n {\n if (_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" registered twice.\");\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n _features.insert(feature);\n }\n\n void feature(const std::string &feature)\n {\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n if (!_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" didn't registered via addFeature(feature).\");\n\n _hitFeatures.insert(feature);\n }\n} validator;\n\nstruct TestlibFinalizeGuard\n{\n static bool alive;\n int quitCount, readEofCount;\n\n TestlibFinalizeGuard() : quitCount(0), readEofCount(0)\n {\n // No operations.\n }\n\n ~TestlibFinalizeGuard()\n {\n bool _alive = alive;\n alive = false;\n\n if (_alive)\n {\n if (testlibMode == _checker && quitCount == 0)\n __testlib_fail(\"Checker must end with quit or quitf call.\");\n\n if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)\n __testlib_fail(\"Validator must end with readEof call.\");\n }\n\n validator.writeTestOverviewLog();\n }\n};\n\nbool TestlibFinalizeGuard::alive = true;\nTestlibFinalizeGuard testlibFinalizeGuard;\n\n/*\n * Call it to disable checks on finalization.\n */\nvoid disableFinalizeGuard()\n{\n TestlibFinalizeGuard::alive = false;\n}\n\n/* Interactor streams.\n */\nstd::fstream tout;\n\n/* implementation\n */\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate \nstatic std::string vtos(const T &t, std::true_type)\n{\n if (t == 0)\n return \"0\";\n else\n {\n T n(t);\n bool negative = n < 0;\n std::string s;\n while (n != 0)\n {\n T digit = n % 10;\n if (digit < 0)\n digit = -digit;\n s += char('0' + digit);\n n /= 10;\n }\n std::reverse(s.begin(), s.end());\n return negative ? \"-\" + s : s;\n }\n}\n\ntemplate \nstatic std::string vtos(const T &t, std::false_type)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n\ntemplate \nstatic std::string vtos(const T &t)\n{\n return vtos(t, std::is_integral());\n}\n#else\ntemplate \nstatic std::string vtos(const T &t)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n#endif\n\ntemplate \nstatic std::string toString(const T &t)\n{\n return vtos(t);\n}\n\nInStream::InStream()\n{\n reader = NULL;\n lastLine = -1;\n name = \"\";\n mode = _input;\n strict = false;\n stdfile = false;\n wordReserveSize = 4;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::InStream(const InStream &baseStream, std::string content)\n{\n reader = new StringInputStreamReader(content);\n lastLine = -1;\n opened = true;\n strict = baseStream.strict;\n mode = baseStream.mode;\n name = \"based on \" + baseStream.name;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::~InStream()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\nint\nresultExitCode(TResult r)\n{\n if (testlibMode == _checker)\n return 0; // CMS Checkers should always finish with zero exit code.\n if (r == _ok)\n return OK_EXIT_CODE;\n if (r == _wa)\n return WA_EXIT_CODE;\n if (r == _pe)\n return PE_EXIT_CODE;\n if (r == _fail)\n return FAIL_EXIT_CODE;\n if (r == _dirt)\n return DIRT_EXIT_CODE;\n if (r == _points)\n return POINTS_EXIT_CODE;\n if (r == _unexpected_eof)\n#ifdef ENABLE_UNEXPECTED_EOF\n return UNEXPECTED_EOF_EXIT_CODE;\n#else\n return PE_EXIT_CODE;\n#endif\n if (r == _sv)\n return SV_EXIT_CODE;\n if (r == _pv)\n return PV_EXIT_CODE;\n if (r >= _partially)\n return PC_BASE_EXIT_CODE + (r - _partially);\n return FAIL_EXIT_CODE;\n}\n\nvoid InStream::textColor(\n#if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER > 1400)) && defined(__GNUC__)\n __attribute__((unused))\n#endif\n WORD color)\n{\n#if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER > 1400)\n HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(handle, color);\n#endif\n#if !defined(ON_WINDOWS) && defined(__GNUC__)\n if (isatty(2))\n {\n switch (color)\n {\n case LightRed:\n fprintf(stderr, \"\\033[1;31m\");\n break;\n case LightCyan:\n fprintf(stderr, \"\\033[1;36m\");\n break;\n case LightGreen:\n fprintf(stderr, \"\\033[1;32m\");\n break;\n case LightYellow:\n fprintf(stderr, \"\\033[1;33m\");\n break;\n case LightMagenta:\n fprintf(stderr, \"\\033[1;35m\");\n break;\n case LightGray:\n default:\n fprintf(stderr, \"\\033[0m\");\n }\n }\n#endif\n}\n\nNORETURN void halt(int exitCode)\n{\n callHaltListeners();\n#ifdef FOOTER\n InStream::textColor(InStream::LightGray);\n std::fprintf(stderr, \"Checker: \\\"%s\\\"\\n\", checkerName.c_str());\n std::fprintf(stderr, \"Exit code: %d\\n\", exitCode);\n InStream::textColor(InStream::LightGray);\n#endif\n std::exit(exitCode);\n}\n\nstatic bool __testlib_shouldCheckDirt(TResult result)\n{\n return result == _ok || result == _points || result >= _partially;\n}\n\nstd::string RESULT_MESSAGE_CORRECT = \"Output is correct\";\nstd::string RESULT_MESSAGE_PARTIALLY_CORRECT = \"Output is partially correct\";\nstd::string RESULT_MESSAGE_WRONG = \"Output isn't correct\";\nstd::string RESULT_MESSAGE_SECURITY_VIOLATION = \"Security Violation\";\nstd::string RESULT_MESSAGE_PROTOCOL_VIOLATION = \"Protocol Violation\";\nstd::string RESULT_MESSAGE_FAIL = \"Judge Failure; Contact staff!\";\n\nNORETURN void InStream::quit(TResult result, const char *msg)\n{\n if (TestlibFinalizeGuard::alive)\n testlibFinalizeGuard.quitCount++;\n\n // You can change maxMessageLength.\n // Example: 'inf.maxMessageLength = 1024 * 1024;'.\n if (strlen(msg) > maxMessageLength)\n {\n std::string message(msg);\n std::string warn = \"message length exceeds \" + vtos(maxMessageLength) + \", the message is truncated: \";\n msg = (warn + message.substr(0, maxMessageLength - warn.length())).c_str();\n }\n\n#ifndef ENABLE_UNEXPECTED_EOF\n if (result == _unexpected_eof)\n result = _pe;\n#endif\n\n if (mode != _output && result != _fail)\n {\n if (mode == _input && testlibMode == _validator && lastLine != -1)\n quits(_fail, std::string(msg) + \" (\" + name + \", line \" + vtos(lastLine) + \")\");\n else\n quits(_fail, std::string(msg) + \" (\" + name + \")\");\n }\n\n std::FILE *resultFile;\n std::string errorName;\n\n if (__testlib_shouldCheckDirt(result))\n {\n if (testlibMode != _interactor && !ouf.seekEof())\n quit(_dirt, \"Extra information in the output file\");\n }\n\n int pctype = result - _partially;\n bool isPartial = false;\n\n if (testlibMode == _checker)\n {\n WORD color;\n std::string pointsStr = \"0\";\n switch (result)\n {\n case _ok:\n pointsStr = format(\"%d\", 1);\n color = LightGreen;\n errorName = RESULT_MESSAGE_CORRECT;\n break;\n case _wa:\n case _pe:\n case _dirt:\n case _unexpected_eof:\n color = LightRed;\n errorName = RESULT_MESSAGE_WRONG;\n break;\n case _fail:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_FAIL;\n break;\n case _sv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_SECURITY_VIOLATION;\n break;\n case _pv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_PROTOCOL_VIOLATION;\n break;\n case _points:\n if (__testlib_points < 1e-5)\n pointsStr = \"0.00001\"; // Prevent zero scores in CMS as zero is considered wrong\n else if (__testlib_points < 0.0001)\n pointsStr = format(\"%lf\", __testlib_points); // Prevent rounding the numbers below 0.0001\n else\n pointsStr = format(\"%.4lf\", __testlib_points);\n color = LightYellow;\n errorName = RESULT_MESSAGE_PARTIALLY_CORRECT;\n break;\n default:\n if (result >= _partially)\n quit(_fail, \"testlib partially mode not supported\");\n else\n quit(_fail, \"What is the code ??? \");\n }\n std::fprintf(stdout, \"%s\\n\", pointsStr.c_str());\n quitscrS(color, errorName);\n std::fprintf(stderr, \"\\n\");\n }\n else\n {\n switch (result)\n {\n case _ok:\n errorName = \"ok \";\n quitscrS(LightGreen, errorName);\n break;\n case _wa:\n errorName = \"wrong answer \";\n quitscrS(LightRed, errorName);\n break;\n case _pe:\n errorName = \"wrong output format \";\n quitscrS(LightRed, errorName);\n break;\n case _fail:\n errorName = \"FAIL \";\n quitscrS(LightRed, errorName);\n break;\n case _dirt:\n errorName = \"wrong output format \";\n quitscrS(LightCyan, errorName);\n result = _pe;\n break;\n case _points:\n errorName = \"points \";\n quitscrS(LightYellow, errorName);\n break;\n case _unexpected_eof:\n errorName = \"unexpected eof \";\n quitscrS(LightCyan, errorName);\n break;\n default:\n if (result >= _partially)\n {\n errorName = format(\"partially correct (%d) \", pctype);\n isPartial = true;\n quitscrS(LightYellow, errorName);\n }\n else\n quit(_fail, \"What is the code ??? \");\n }\n }\n\n if (resultName != \"\")\n {\n resultFile = std::fopen(resultName.c_str(), \"w\");\n if (resultFile == NULL)\n quit(_fail, \"Can not write to the result file\");\n if (appesMode)\n {\n std::fprintf(resultFile, \"\");\n if (isPartial)\n std::fprintf(resultFile, \"\", outcomes[(int)_partially].c_str(), pctype);\n else\n {\n if (result != _points)\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str());\n else\n {\n if (__testlib_points == std::numeric_limits::infinity())\n quit(_fail, \"Expected points, but infinity found\");\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", __testlib_points));\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str(), stringPoints.c_str());\n }\n }\n xmlSafeWrite(resultFile, msg);\n std::fprintf(resultFile, \"\\n\");\n }\n else\n std::fprintf(resultFile, \"%s\", msg);\n if (NULL == resultFile || fclose(resultFile) != 0)\n quit(_fail, \"Can not write to the result file\");\n }\n\n quitscr(LightGray, msg);\n std::fprintf(stderr, \"\\n\");\n\n inf.close();\n ouf.close();\n ans.close();\n if (tout.is_open())\n tout.close();\n\n textColor(LightGray);\n\n if (resultName != \"\")\n std::fprintf(stderr, \"See file to check exit message\\n\");\n\n halt(resultExitCode(result));\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 3, 4)))\n#endif\nNORETURN void\nInStream::quitf(TResult result, const char *msg, ...)\n{\n FMT_TO_RESULT(msg, msg, message);\n InStream::quit(result, message.c_str());\n}\n\nNORETURN void InStream::quits(TResult result, std::string msg)\n{\n InStream::quit(result, msg.c_str());\n}\n\nvoid InStream::xmlSafeWrite(std::FILE *file, const char *msg)\n{\n size_t lmsg = strlen(msg);\n for (size_t i = 0; i < lmsg; i++)\n {\n if (msg[i] == '&')\n {\n std::fprintf(file, \"%s\", \"&\");\n continue;\n }\n if (msg[i] == '<')\n {\n std::fprintf(file, \"%s\", \"<\");\n continue;\n }\n if (msg[i] == '>')\n {\n std::fprintf(file, \"%s\", \">\");\n continue;\n }\n if (msg[i] == '\"')\n {\n std::fprintf(file, \"%s\", \""\");\n continue;\n }\n if (0 <= msg[i] && msg[i] <= 31)\n {\n std::fprintf(file, \"%c\", '.');\n continue;\n }\n std::fprintf(file, \"%c\", msg[i]);\n }\n}\n\nvoid InStream::quitscrS(WORD color, std::string msg)\n{\n quitscr(color, msg.c_str());\n}\n\nvoid InStream::quitscr(WORD color, const char *msg)\n{\n if (resultName == \"\")\n {\n textColor(color);\n std::fprintf(stderr, \"%s\", msg);\n textColor(LightGray);\n }\n}\n\nvoid InStream::reset(std::FILE *file)\n{\n if (opened && stdfile)\n quit(_fail, \"Can't reset standard handle\");\n\n if (opened)\n close();\n\n if (!stdfile)\n if (NULL == (file = std::fopen(name.c_str(), \"rb\")))\n {\n if (mode == _output)\n quits(_pe, std::string(\"Output file not found: \\\"\") + name + \"\\\"\");\n\n if (mode == _answer)\n quits(_fail, std::string(\"Answer file not found: \\\"\") + name + \"\\\"\");\n }\n\n if (NULL != file)\n {\n opened = true;\n\n __testlib_set_binary(file);\n\n if (stdfile)\n reader = new FileInputStreamReader(file, name);\n else\n reader = new BufferedFileInputStreamReader(file, name);\n }\n else\n {\n opened = false;\n reader = NULL;\n }\n}\n\nvoid InStream::init(std::string fileName, TMode mode)\n{\n opened = false;\n name = fileName;\n stdfile = false;\n this->mode = mode;\n\n std::ifstream stream;\n stream.open(fileName.c_str(), std::ios::in);\n if (stream.is_open())\n {\n std::streampos start = stream.tellg();\n stream.seekg(0, std::ios::end);\n std::streampos end = stream.tellg();\n size_t fileSize = size_t(end - start);\n stream.close();\n\n // You can change maxFileSize.\n // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'.\n if (fileSize > maxFileSize)\n quitf(_pe, \"File size exceeds %d bytes, size is %d\", int(maxFileSize), int(fileSize));\n }\n\n reset();\n}\n\nvoid InStream::init(std::FILE *f, TMode mode)\n{\n opened = false;\n name = \"untitled\";\n this->mode = mode;\n\n if (f == stdin)\n name = \"stdin\", stdfile = true;\n if (f == stdout)\n name = \"stdout\", stdfile = true;\n if (f == stderr)\n name = \"stderr\", stdfile = true;\n\n reset(f);\n}\n\nchar InStream::curChar()\n{\n return char(reader->curChar());\n}\n\nchar InStream::nextChar()\n{\n return char(reader->nextChar());\n}\n\nchar InStream::readChar()\n{\n return nextChar();\n}\n\nchar InStream::readChar(char c)\n{\n lastLine = reader->getLine();\n char found = readChar();\n if (c != found)\n {\n if (!isEoln(found))\n quit(_pe, (\"Unexpected character '\" + std::string(1, found) + \"', but '\" + std::string(1, c) + \"' expected\").c_str());\n else\n quit(_pe, (\"Unexpected character \" + (\"#\" + vtos(int(found))) + \", but '\" + std::string(1, c) + \"' expected\").c_str());\n }\n return found;\n}\n\nchar InStream::readSpace()\n{\n return readChar(' ');\n}\n\nvoid InStream::unreadChar(char c)\n{\n reader->unreadChar(c);\n}\n\nvoid InStream::skipChar()\n{\n reader->skipChar();\n}\n\nvoid InStream::skipBlanks()\n{\n while (isBlanks(reader->curChar()))\n reader->skipChar();\n}\n\nstd::string InStream::readWord()\n{\n readWordTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nvoid InStream::readWordTo(std::string &result)\n{\n if (!strict)\n skipBlanks();\n\n lastLine = reader->getLine();\n int cur = reader->nextChar();\n\n if (cur == EOFC)\n quit(_unexpected_eof, \"Unexpected end of file - token expected\");\n\n if (isBlanks(cur))\n quit(_pe, \"Unexpected white-space - token expected\");\n\n result.clear();\n\n while (!(isBlanks(cur) || cur == EOFC))\n {\n result += char(cur);\n\n // You can change maxTokenLength.\n // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'.\n if (result.length() > maxTokenLength)\n quitf(_pe, \"Length of token exceeds %d, token is '%s...'\", int(maxTokenLength), __testlib_part(result).c_str());\n\n cur = reader->nextChar();\n }\n\n reader->unreadChar(cur);\n\n if (result.length() == 0)\n quit(_unexpected_eof, \"Unexpected end of file or white-space - token expected\");\n}\n\nstd::string InStream::readToken()\n{\n return readWord();\n}\n\nvoid InStream::readTokenTo(std::string &result)\n{\n readWordTo(result);\n}\n\nstatic std::string __testlib_part(const std::string &s)\n{\n if (s.length() <= 64)\n return s;\n else\n return s.substr(0, 30) + \"...\" + s.substr(s.length() - 31, 31);\n}\n\n#define __testlib_readMany(readMany, readOne, typeName, space) \\\n if (size < 0) \\\n quit(_fail, #readMany \": size should be non-negative.\"); \\\n if (size > 100000000) \\\n quit(_fail, #readMany \": size should be at most 100000000.\"); \\\n \\\n std::vector result(size); \\\n readManyIteration = indexBase; \\\n \\\n for (int i = 0; i < size; i++) \\\n { \\\n result[i] = readOne; \\\n readManyIteration++; \\\n if (strict && space && i + 1 < size) \\\n readSpace(); \\\n } \\\n \\\n readManyIteration = NO_INDEX; \\\n return result;\n\nstd::string InStream::readWord(const pattern &p, const std::string &variableName)\n{\n readWordTo(_tmpReadToken);\n if (!p.matches(_tmpReadToken))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Token element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token element \" + variableName + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n return _tmpReadToken;\n}\n\nstd::vector InStream::readWords(int size, const pattern &p, const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readWord(const std::string &ptrn, const std::string &variableName)\n{\n return readWord(pattern(ptrn), variableName);\n}\n\nstd::vector InStream::readWords(int size, const std::string &ptrn, const std::string &variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const pattern &p, const std::string &variableName)\n{\n return readWord(p, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const pattern &p, const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const std::string &ptrn, const std::string &variableName)\n{\n return readWord(ptrn, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const std::string &ptrn, const std::string &variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true);\n}\n\nvoid InStream::readWordTo(std::string &result, const pattern &p, const std::string &variableName)\n{\n readWordTo(result);\n if (!p.matches(result))\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n}\n\nvoid InStream::readWordTo(std::string &result, const std::string &ptrn, const std::string &variableName)\n{\n return readWordTo(result, pattern(ptrn), variableName);\n}\n\nvoid InStream::readTokenTo(std::string &result, const pattern &p, const std::string &variableName)\n{\n return readWordTo(result, p, variableName);\n}\n\nvoid InStream::readTokenTo(std::string &result, const std::string &ptrn, const std::string &variableName)\n{\n return readWordTo(result, ptrn, variableName);\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool\nequals(long long integer, const char *s)\n{\n if (integer == LLONG_MIN)\n return strcmp(s, \"-9223372036854775808\") == 0;\n\n if (integer == 0LL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n if (integer < 0 && s[0] != '-')\n return false;\n\n if (integer < 0)\n s++, length--, integer = -integer;\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool\nequals(unsigned long long integer, const char *s)\n{\n if (integer == ULLONG_MAX)\n return strcmp(s, \"18446744073709551615\") == 0;\n\n if (integer == 0ULL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\nstatic inline double stringToDouble(InStream &in, const char *buffer)\n{\n double retval;\n\n size_t length = strlen(buffer);\n\n int minusCount = 0;\n int plusCount = 0;\n int decimalPointCount = 0;\n int digitCount = 0;\n int eCount = 0;\n\n for (size_t i = 0; i < length; i++)\n {\n if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.' || buffer[i] == 'e' || buffer[i] == 'E' || buffer[i] == '-' || buffer[i] == '+')\n {\n if ('0' <= buffer[i] && buffer[i] <= '9')\n digitCount++;\n if (buffer[i] == 'e' || buffer[i] == 'E')\n eCount++;\n if (buffer[i] == '-')\n minusCount++;\n if (buffer[i] == '+')\n plusCount++;\n if (buffer[i] == '.')\n decimalPointCount++;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n // If for sure is not a number in standard notation or in e-notation.\n if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char *suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline double stringToStrictDouble(InStream &in, const char *buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)\n{\n if (minAfterPointDigitCount < 0)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be non-negative.\");\n\n if (minAfterPointDigitCount > maxAfterPointDigitCount)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.\");\n\n double retval;\n\n size_t length = strlen(buffer);\n\n if (length == 0 || length > 1000)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int pointPos = -1;\n for (size_t i = 1; i + 1 < length; i++)\n {\n if (buffer[i] == '.')\n {\n if (pointPos > -1)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n pointPos = int(i);\n }\n if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n if (buffer[length - 1] < '0' || buffer[length - 1] > '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);\n if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)\n in.quit(_pe, (\"Expected strict double with number of digits after point in range [\" + vtos(minAfterPointDigitCount) + \",\" + vtos(maxAfterPointDigitCount) + \"], but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int firstDigitPos = -1;\n for (size_t i = 0; i < length; i++)\n if (buffer[i] >= '0' && buffer[i] <= '9')\n {\n firstDigitPos = int(i);\n break;\n }\n\n if (firstDigitPos > 1 || firstDigitPos == -1)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length) && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char *suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline long long stringToLongLong(InStream &in, const char *buffer)\n{\n if (strcmp(buffer, \"-9223372036854775808\") == 0)\n return LLONG_MIN;\n\n bool minus = false;\n size_t length = strlen(buffer);\n\n if (length > 1 && buffer[0] == '-')\n minus = true;\n\n if (length > 20)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n long long retval = 0LL;\n\n int zeroes = 0;\n int processingZeroes = true;\n\n for (int i = (minus ? 1 : 0); i < int(length); i++)\n {\n if (buffer[i] == '0' && processingZeroes)\n zeroes++;\n else\n processingZeroes = false;\n\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (retval < 0)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n retval = (minus ? -retval : +retval);\n\n if (length < 19)\n return retval;\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline unsigned long long stringToUnsignedLongLong(InStream &in, const char *buffer)\n{\n size_t length = strlen(buffer);\n\n if (length > 20)\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n if (length > 1 && buffer[0] == '0')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n unsigned long long retval = 0LL;\n for (int i = 0; i < int(length); i++)\n {\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (length < 19)\n return retval;\n\n if (length == 20 && strcmp(buffer, \"18446744073709551615\") == 1)\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nint InStream::readInteger()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int32 expected\");\n\n readWordTo(_tmpReadToken);\n\n long long value = stringToLongLong(*this, _tmpReadToken.c_str());\n if (value < INT_MIN || value > INT_MAX)\n quit(_pe, (\"Expected int32, but \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" found\").c_str());\n\n return int(value);\n}\n\nlong long InStream::readLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToLongLong(*this, _tmpReadToken.c_str());\n}\n\nunsigned long long InStream::readUnsignedLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToUnsignedLongLong(*this, _tmpReadToken.c_str());\n}\n\nlong long InStream::readLong(long long minv, long long maxv, const std::string &variableName)\n{\n long long result = readLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readLongs(int size, long long minv, long long maxv, const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true)\n}\n\nunsigned long long InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName)\n{\n unsigned long long result = readUnsignedLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true)\n}\n\nunsigned long long InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string &variableName)\n{\n return readUnsignedLong(minv, maxv, variableName);\n}\n\nint InStream::readInt()\n{\n return readInteger();\n}\n\nint InStream::readInt(int minv, int maxv, const std::string &variableName)\n{\n int result = readInt();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nint InStream::readInteger(int minv, int maxv, const std::string &variableName)\n{\n return readInt(minv, maxv, variableName);\n}\n\nstd::vector InStream::readInts(int size, int minv, int maxv, const std::string &variablesName, int indexBase){\n __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true)}\n\nstd::vector InStream::readIntegers(int size, int minv, int maxv, const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true)\n}\n\ndouble InStream::readReal()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - double expected\");\n\n return stringToDouble(*this, readWord().c_str());\n}\n\ndouble InStream::readDouble()\n{\n return readReal();\n}\n\ndouble InStream::readReal(double minv, double maxv, const std::string &variableName)\n{\n double result = readReal();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS));\n\n return result;\n}\n\nstd::vector InStream::readReals(int size, double minv, double maxv, const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readDouble(double minv, double maxv, const std::string &variableName)\n{\n return readReal(minv, maxv, variableName);\n}\n\nstd::vector InStream::readDoubles(int size, double minv, double maxv, const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variableName)\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - strict double expected\");\n\n double result = stringToStrictDouble(*this, readWord().c_str(),\n minAfterPointDigitCount, maxAfterPointDigitCount);\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS));\n\n return result;\n}\n\nstd::vector InStream::readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readStrictReals, readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\ndouble InStream::readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variableName)\n{\n return readStrictReal(minv, maxv,\n minAfterPointDigitCount, maxAfterPointDigitCount,\n variableName);\n}\n\nstd::vector InStream::readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string &variablesName, int indexBase)\n{\n __testlib_readMany(readStrictDoubles, readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\nbool InStream::eof()\n{\n if (!strict && NULL == reader)\n return true;\n\n return reader->eof();\n}\n\nbool InStream::seekEof()\n{\n if (!strict && NULL == reader)\n return true;\n skipBlanks();\n return eof();\n}\n\nbool InStream::eoln()\n{\n if (!strict && NULL == reader)\n return true;\n\n int c = reader->nextChar();\n\n if (!strict)\n {\n if (c == EOFC)\n return true;\n\n if (c == CR)\n {\n c = reader->nextChar();\n\n if (c != LF)\n {\n reader->unreadChar(c);\n reader->unreadChar(CR);\n return false;\n }\n else\n return true;\n }\n\n if (c == LF)\n return true;\n\n reader->unreadChar(c);\n return false;\n }\n else\n {\n bool returnCr = false;\n\n#if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS)\n if (c != CR)\n {\n reader->unreadChar(c);\n return false;\n }\n else\n {\n if (!returnCr)\n returnCr = true;\n c = reader->nextChar();\n }\n#endif\n if (c != LF)\n {\n reader->unreadChar(c);\n if (returnCr)\n reader->unreadChar(CR);\n return false;\n }\n\n return true;\n }\n}\n\nvoid InStream::readEoln()\n{\n lastLine = reader->getLine();\n if (!eoln())\n quit(_pe, \"Expected EOLN\");\n}\n\nvoid InStream::readEof()\n{\n lastLine = reader->getLine();\n if (!eof())\n quit(_pe, \"Expected EOF\");\n\n if (TestlibFinalizeGuard::alive && this == &inf)\n testlibFinalizeGuard.readEofCount++;\n}\n\nbool InStream::seekEoln()\n{\n if (!strict && NULL == reader)\n return true;\n\n int cur;\n do\n {\n cur = reader->nextChar();\n } while (cur == SPACE || cur == TAB);\n\n reader->unreadChar(cur);\n return eoln();\n}\n\nvoid InStream::nextLine()\n{\n readLine();\n}\n\nvoid InStream::readStringTo(std::string &result)\n{\n if (NULL == reader)\n quit(_pe, \"Expected line\");\n\n result.clear();\n\n for (;;)\n {\n int cur = reader->curChar();\n\n if (cur == LF || cur == EOFC)\n break;\n\n if (cur == CR)\n {\n cur = reader->nextChar();\n if (reader->curChar() == LF)\n {\n reader->unreadChar(cur);\n break;\n }\n }\n\n lastLine = reader->getLine();\n result += char(reader->nextChar());\n }\n\n if (strict)\n readEoln();\n else\n eoln();\n}\n\nstd::string InStream::readString()\n{\n readStringTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, int indexBase)\n{\n __testlib_readMany(readStrings, readString(), std::string, false)\n}\n\nvoid InStream::readStringTo(std::string &result, const pattern &p, const std::string &variableName)\n{\n readStringTo(result);\n if (!p.matches(result))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Line \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Line element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n}\n\nvoid InStream::readStringTo(std::string &result, const std::string &ptrn, const std::string &variableName)\n{\n readStringTo(result, pattern(ptrn), variableName);\n}\n\nstd::string InStream::readString(const pattern &p, const std::string &variableName)\n{\n readStringTo(_tmpReadToken, p, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const pattern &p, const std::string &variablesName, int indexBase){\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)}\n\nstd::string InStream::readString(const std::string &ptrn, const std::string &variableName)\n{\n readStringTo(_tmpReadToken, ptrn, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const std::string &ptrn, const std::string &variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string &result)\n{\n readStringTo(result);\n}\n\nstd::string InStream::readLine()\n{\n return readString();\n}\n\nstd::vector InStream::readLines(int size, int indexBase)\n{\n __testlib_readMany(readLines, readString(), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string &result, const pattern &p, const std::string &variableName)\n{\n readStringTo(result, p, variableName);\n}\n\nvoid InStream::readLineTo(std::string &result, const std::string &ptrn, const std::string &variableName)\n{\n readStringTo(result, ptrn, variableName);\n}\n\nstd::string InStream::readLine(const pattern &p, const std::string &variableName)\n{\n return readString(p, variableName);\n}\n\nstd::vector InStream::readLines(int size, const pattern &p, const std::string &variablesName, int indexBase){\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)}\n\nstd::string InStream::readLine(const std::string &ptrn, const std::string &variableName)\n{\n return readString(ptrn, variableName);\n}\n\nstd::vector InStream::readLines(int size, const std::string &ptrn, const std::string &variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 3, 4)))\n#endif\nvoid\nInStream::ensuref(bool cond, const char *format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n this->__testlib_ensure(cond, message);\n }\n}\n\nvoid InStream::__testlib_ensure(bool cond, std::string message)\n{\n if (!cond)\n this->quit(_wa, message.c_str());\n}\n\nvoid InStream::close()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n\n opened = false;\n}\n\nNORETURN void quit(TResult result, const std::string &msg)\n{\n ouf.quit(result, msg.c_str());\n}\n\nNORETURN void quit(TResult result, const char *msg)\n{\n ouf.quit(result, msg);\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 2, 3)))\n#endif\nNORETURN void\nquitf(TResult result, const char *format, ...);\n\nNORETURN void __testlib_quitp(double points, const char *message)\n{\n if (points < 0 || points > 1)\n quitf(_fail, \"wrong points: %lf, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", points));\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void __testlib_quitp(int points, const char *message)\n{\n if (points < 0 || points > 1)\n quitf(_fail, \"wrong points: %d, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = format(\"%d\", points);\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void quitp(float points, const std::string &message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(double points, const std::string &message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\nNORETURN void quitp(long double points, const std::string &message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(int points, const std::string &message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\ntemplate \n#ifdef __GNUC__\n__attribute__((format(printf, 2, 3)))\n#endif\nNORETURN void\nquitp(F points, const char *format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quitp(points, message);\n}\n\ntemplate \nNORETURN void quitp(F points)\n{\n __testlib_quitp(points, std::string(\"\"));\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 2, 3)))\n#endif\nNORETURN void\nquitf(TResult result, const char *format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 3, 4)))\n#endif\nvoid\nquitif(bool condition, TResult result, const char *format, ...)\n{\n if (condition)\n {\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n }\n}\n\nNORETURN void __testlib_help()\n{\n InStream::textColor(InStream::LightCyan);\n std::fprintf(stderr, \"TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ \", VERSION);\n std::fprintf(stderr, \"by Mike Mirzayanov, copyright(c) 2005-2018\\n\");\n std::fprintf(stderr, \"Checker name: \\\"%s\\\"\\n\", checkerName.c_str());\n InStream::textColor(InStream::LightGray);\n\n std::fprintf(stderr, \"\\n\");\n std::fprintf(stderr, \"Latest features: \\n\");\n for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char *); i++)\n {\n std::fprintf(stderr, \"*) %s\\n\", latestFeatures[i]);\n }\n std::fprintf(stderr, \"\\n\");\n\n std::fprintf(stderr, \"Program must be run with the following arguments: \\n\");\n std::fprintf(stderr, \" [ [<-appes>]]\\n\\n\");\n\n std::exit(FAIL_EXIT_CODE);\n}\n\nstatic void __testlib_ensuresPreconditions()\n{\n // testlib assumes: sizeof(int) = 4.\n __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);\n\n // testlib assumes: INT_MAX == 2147483647.\n __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);\n\n // testlib assumes: sizeof(long long) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);\n\n // testlib assumes: sizeof(double) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);\n\n // testlib assumes: no -ffast-math.\n if (!__testlib_isNaN(+__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n if (!__testlib_isNaN(-__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n}\n\nvoid registerGen(int argc, char *argv[], int randomGeneratorVersion)\n{\n if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)\n quitf(_fail, \"Random generator version is expected to be 0 or 1.\");\n random_t::version = randomGeneratorVersion;\n\n __testlib_ensuresPreconditions();\n\n testlibMode = _generator;\n __testlib_set_binary(stdin);\n rnd.setSeed(argc, argv);\n}\n\n#ifdef USE_RND_AS_BEFORE_087\nvoid registerGen(int argc, char *argv[])\n{\n registerGen(argc, argv, 0);\n}\n#else\n#ifdef __GNUC__\n#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4))\n__attribute__((deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\")))\n#else\n__attribute__((deprecated))\n#endif\n#endif\n#ifdef _MSC_VER\n__declspec(deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\"))\n#endif\n void registerGen(int argc, char *argv[])\n{\n std::fprintf(stderr, \"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\\n\\n\");\n registerGen(argc, argv, 0);\n}\n#endif\n\nvoid registerInteraction(int argc, char *argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _interactor;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n\n if (argc < 3 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [ [<-appes>]]]\") +\n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc <= 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n#ifndef EJUDGE\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n#endif\n\n inf.init(argv[1], _input);\n\n tout.open(argv[2], std::ios_base::out);\n if (tout.fail() || !tout.is_open())\n quit(_fail, std::string(\"Can not write to the test-output-file '\") + argv[2] + std::string(\"'\"));\n\n ouf.init(stdin, _output);\n\n if (argc >= 4)\n ans.init(argv[3], _answer);\n else\n ans.name = \"unopened answer stream\";\n}\n\nvoid registerValidation()\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _validator;\n __testlib_set_binary(stdin);\n\n inf.init(stdin, _input);\n inf.strict = true;\n}\n\nvoid registerValidation(int argc, char *argv[])\n{\n registerValidation();\n\n for (int i = 1; i < argc; i++)\n {\n if (!strcmp(\"--testset\", argv[i]))\n {\n if (i + 1 < argc && strlen(argv[i + 1]) > 0)\n validator.setTestset(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--group\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setGroup(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--testOverviewLogFileName\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setTestOverviewLogFileName(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n }\n}\n\nvoid addFeature(const std::string &feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.addFeature(feature);\n}\n\nvoid feature(const std::string &feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.feature(feature);\n}\n\nvoid registerTestlibCmd(int argc, char *argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _checker;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n\n if (argc < 4 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [<-appes>]]\") +\n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc == 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n\n inf.init(argv[1], _input);\n ans.init(argv[2], _answer);\n ouf.init(argv[3], _output);\n}\n\nvoid registerTestlib(int argc, ...)\n{\n if (argc < 3 || argc > 5)\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n\n char **argv = new char *[argc + 1];\n\n va_list ap;\n va_start(ap, argc);\n argv[0] = NULL;\n for (int i = 0; i < argc; i++)\n {\n argv[i + 1] = va_arg(ap, char *);\n }\n va_end(ap);\n\n registerTestlibCmd(argc + 1, argv);\n delete[] argv;\n}\n\nstatic inline void __testlib_ensure(bool cond, const std::string &msg)\n{\n if (!cond)\n quit(_fail, msg.c_str());\n}\n\n#ifdef __GNUC__\n__attribute__((unused))\n#endif\nstatic inline void\n__testlib_ensure(bool cond, const char *msg)\n{\n if (!cond)\n quit(_fail, msg);\n}\n\n#define ensure(cond) __testlib_ensure(cond, \"Condition failed: \\\"\" #cond \"\\\"\")\n\n#ifdef __GNUC__\n__attribute__((format(printf, 2, 3)))\n#endif\ninline void\nensuref(bool cond, const char *format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n __testlib_ensure(cond, message);\n }\n}\n\nNORETURN static void __testlib_fail(const std::string &message)\n{\n quitf(_fail, \"%s\", message.c_str());\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 1, 2)))\n#endif\nvoid\nsetName(const char *format, ...)\n{\n FMT_TO_RESULT(format, format, name);\n checkerName = name;\n}\n\n/*\n * Do not use random_shuffle, because it will produce different result\n * for different C++ compilers.\n *\n * This implementation uses testlib random_t to produce random numbers, so\n * it is stable.\n */\ntemplate \nvoid shuffle(_RandomAccessIter __first, _RandomAccessIter __last)\n{\n if (__first == __last)\n return;\n for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)\n std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));\n}\n\ntemplate \n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__((error(\"Don't use random_shuffle(), use shuffle() instead\")))\n#endif\nvoid\nrandom_shuffle(_RandomAccessIter, _RandomAccessIter)\n{\n quitf(_fail, \"Don't use random_shuffle(), use shuffle() instead\");\n}\n\n#ifdef __GLIBC__\n#define RAND_THROW_STATEMENT throw()\n#else\n#define RAND_THROW_STATEMENT\n#endif\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__((error(\"Don't use rand(), use rnd.next() instead\")))\n#endif\n#ifdef _MSC_VER\n#pragma warning(disable : 4273)\n#endif\nint\nrand() RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use rand(), use rnd.next() instead\");\n\n /* This line never runs. */\n // throw \"Don't use rand(), use rnd.next() instead\";\n}\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__((error(\"Don't use srand(), you should use \"\n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1).\")))\n#endif\n#ifdef _MSC_VER\n#pragma warning(disable : 4273)\n#endif\nvoid\nsrand(unsigned int seed) RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use srand(), you should use \"\n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1) [ignored seed=%d].\",\n seed);\n}\n\nvoid startTest(int test)\n{\n const std::string testFileName = vtos(test);\n if (NULL == freopen(testFileName.c_str(), \"wt\", stdout))\n __testlib_fail(\"Unable to write file '\" + testFileName + \"'\");\n}\n\ninline std::string upperCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('a' <= s[i] && s[i] <= 'z')\n s[i] = char(s[i] - 'a' + 'A');\n return s;\n}\n\ninline std::string lowerCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('A' <= s[i] && s[i] <= 'Z')\n s[i] = char(s[i] - 'A' + 'a');\n return s;\n}\n\ninline std::string compress(const std::string &s)\n{\n return __testlib_part(s);\n}\n\ninline std::string englishEnding(int x)\n{\n x %= 100;\n if (x / 10 == 1)\n return \"th\";\n if (x % 10 == 1)\n return \"st\";\n if (x % 10 == 2)\n return \"nd\";\n if (x % 10 == 3)\n return \"rd\";\n return \"th\";\n}\n\ninline std::string trim(const std::string &s)\n{\n if (s.empty())\n return s;\n\n int left = 0;\n while (left < int(s.length()) && isBlanks(s[left]))\n left++;\n if (left >= int(s.length()))\n return \"\";\n\n int right = int(s.length()) - 1;\n while (right >= 0 && isBlanks(s[right]))\n right--;\n if (right < 0)\n return \"\";\n\n return s.substr(left, right - left + 1);\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator)\n{\n std::stringstream ss;\n bool repeated = false;\n for (_ForwardIterator i = first; i != last; i++)\n {\n if (repeated)\n ss << separator;\n else\n repeated = true;\n ss << *i;\n }\n return ss.str();\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last)\n{\n return join(first, last, ' ');\n}\n\ntemplate \nstd::string join(const _Collection &collection, _Separator separator)\n{\n return join(collection.begin(), collection.end(), separator);\n}\n\ntemplate \nstd::string join(const _Collection &collection)\n{\n return join(collection, ' ');\n}\n\n/**\n * Splits string s by character separator returning exactly k+1 items,\n * where k is the number of separator occurences.\n */\nstd::vector split(const std::string &s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning exactly k+1 items,\n * where k is the number of separator occurences.\n */\nstd::vector split(const std::string &s, const std::string &separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separator returning non-empty items.\n */\nstd::vector tokenize(const std::string &s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n if (!item.empty())\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning non-empty items.\n */\nstd::vector tokenize(const std::string &s, const std::string &separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n\n if (!item.empty())\n result.push_back(item);\n\n return result;\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char *prepend)\n{\n std::string message;\n if (strlen(prepend) != 0)\n message = format(\"%s: expected '%s', but found '%s'\",\n compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());\n else\n message = format(\"expected '%s', but found '%s'\",\n compress(expected).c_str(), compress(found).c_str());\n quit(result, message);\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char *prepend)\n{\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend);\n}\n\ntemplate \n#ifdef __GNUC__\n__attribute__((format(printf, 4, 5)))\n#endif\nNORETURN void\nexpectedButFound(TResult result, T expected, T found, const char *prependFormat = \"\", ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = vtos(expected);\n std::string foundString = vtos(found);\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__((format(printf, 4, 5)))\n#endif\nNORETURN void\nexpectedButFound(TResult result, std::string expected, std::string found, const char *prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, expected, found, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__((format(printf, 4, 5)))\n#endif\nNORETURN void\nexpectedButFound(TResult result, double expected, double found, const char *prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__((format(printf, 4, 5)))\n#endif\nNORETURN void\nexpectedButFound(TResult result, const char *expected, const char *found, const char *prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__((format(printf, 4, 5)))\n#endif\nNORETURN void\nexpectedButFound(TResult result, float expected, float found, const char *prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__((format(printf, 4, 5)))\n#endif\nNORETURN void\nexpectedButFound(TResult result, long double expected, long double found, const char *prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\n#endif\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate \nstruct is_iterable\n{\n template \n static char test(typename U::iterator *x);\n\n template \n static long test(U *x);\n\n static const bool value = sizeof(test(0)) == 1;\n};\n\ntemplate \nstruct __testlib_enable_if\n{\n};\n\ntemplate \nstruct __testlib_enable_if\n{\n typedef T type;\n};\n\ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T &t)\n{\n std::cout << t;\n}\n\ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T &t)\n{\n bool first = true;\n for (typename T::const_iterator i = t.begin(); i != t.end(); i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n std::cout << *i;\n }\n}\n\ntemplate <>\ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const std::string &t)\n{\n std::cout << t;\n}\n\ntemplate \nvoid __println_range(A begin, B end)\n{\n bool first = true;\n for (B i = B(begin); i != end; i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n __testlib_print_one(*i);\n }\n std::cout << std::endl;\n}\n\ntemplate \nstruct is_iterator\n{\n static T makeT();\n typedef void *twoptrs[2];\n static twoptrs &test(...);\n template \n static typename R::iterator_category *test(R);\n template \n static void *test(R *);\n static const bool value = sizeof(test(makeT())) == sizeof(void *);\n};\n\ntemplate \nstruct is_iterator::value>::type>\n{\n static const bool value = false;\n};\n\ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A &a, const B &b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n\ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A &a, const B &b)\n{\n __println_range(a, b);\n}\n\ntemplate \nvoid println(const A *a, const A *b)\n{\n __println_range(a, b);\n}\n\ntemplate <>\nvoid println(const char *a, const char *b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n\ntemplate \nvoid println(const T &x)\n{\n __testlib_print_one(x);\n std::cout << std::endl;\n}\n\ntemplate \nvoid println(const A &a, const B &b, const C &c)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << std::endl;\n}\n\ntemplate \nvoid println(const A &a, const B &b, const C &c, const D &d)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << std::endl;\n}\n\ntemplate \nvoid println(const A &a, const B &b, const C &c, const D &d, const E &e)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << std::endl;\n}\n\ntemplate \nvoid println(const A &a, const B &b, const C &c, const D &d, const E &e, const F &f)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << std::endl;\n}\n\ntemplate \nvoid println(const A &a, const B &b, const C &c, const D &d, const E &e, const F &f, const G &g)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << \" \";\n __testlib_print_one(g);\n std::cout << std::endl;\n}\n#endif\n\nvoid registerChecker(std::string probName, int argc, char *argv[])\n{\n setName(\"checker for problem %s\", probName.c_str());\n registerTestlibCmd(argc, argv);\n}\n\nconst std::string _grader_OK = \"OK\";\nconst std::string _grader_SV = \"SV\";\nconst std::string _grader_PV = \"PV\";\nconst std::string _grader_WA = \"WA\";\nconst std::string _grader_FAIL = \"FAIL\";\n\nvoid InStream::readSecret(std::string secret, TResult mismatchResult, std::string mismatchMessage)\n{\n if (readWord() != secret)\n quits(mismatchResult, mismatchMessage);\n eoln();\n}\n\nvoid readBothSecrets(std::string secret)\n{\n ans.readSecret(secret, _fail, \"Secret mismatch in the (correct) answer file\");\n ouf.readSecret(secret, _pv, \"Possible tampering with the output\");\n}\n\nvoid InStream::quitByGraderResult(TResult result, std::string defaultMessage)\n{\n std::string msg = \"\";\n if (!eof())\n msg = readLine();\n if (msg.empty())\n quits(result, defaultMessage);\n quits(result, msg);\n}\n\nvoid InStream::readGraderResult()\n{\n std::string result = readWord();\n eoln();\n if (result == _grader_OK)\n return;\n if (result == _grader_SV)\n quitByGraderResult(_sv, \"Security violation detected in grader\");\n if (result == _grader_PV)\n quitByGraderResult(_pv, \"Protocol violation detected in grader\");\n if (result == _grader_WA)\n quitByGraderResult(_wa, \"Wrong answer detected in grader\");\n if (result == _grader_FAIL)\n quitByGraderResult(_fail, \"Failure in grader\");\n quitf(_fail, \"Unknown grader result\");\n}\n\nvoid readBothGraderResults()\n{\n ans.readGraderResult();\n ouf.readGraderResult();\n}\n\nNORETURN void quit(TResult result)\n{\n ouf.quit(result, \"\");\n}\n\n/// Used in validators: skips the rest of input, assuming it to be correct\nNORETURN void skip_ok()\n{\n if (testlibMode != _validator)\n quitf(_fail, \"skip_ok() only works in validators\");\n testlibFinalizeGuard.quitCount++;\n halt(0);\n}\n\n/// 1 -> 1st, 2 -> 2nd, 3 -> 3rd, 4 -> 4th, ...\nstd::string englishTh(int x)\n{\n char c[100];\n sprintf(c, \"%d%s\", x, englishEnding(x).c_str());\n return c;\n}\n\n/// Compares the tokens of two lines\nvoid compareTokens(int lineNo, std::string a, std::string b, char separator = ' ')\n{\n std::vector toka = tokenize(a, separator);\n std::vector tokb = tokenize(b, separator);\n if (toka == tokb)\n return;\n std::string dif = format(\"%s lines differ - \", englishTh(lineNo).c_str());\n if (toka.size() != tokb.size())\n quitf(_wa, \"%sexpected: %d tokens, found %d tokens\", dif.c_str(), int(toka.size()), int(tokb.size()));\n for (int i = 0; i < int(toka.size()); i++)\n if (toka[i] != tokb[i])\n quitf(_wa, \"%son the %s token, expected: '%s', found: '%s'\", dif.c_str(), englishTh(i + 1).c_str(), compress(toka[i]).c_str(), compress(tokb[i]).c_str());\n quitf(_fail, \"%sbut I don't know why!\", dif.c_str());\n}\n\n/// Compares the tokens of the remaining lines\nNORETURN void compareRemainingLines(int lineNo = 1)\n{\n for (; !ans.eof(); lineNo++)\n {\n std::string j = ans.readString();\n\n if (j == \"\" && ans.eof())\n break;\n\n std::string p = ouf.readString();\n\n compareTokens(lineNo, j, p);\n }\n quit(_ok);\n}\n"}, "problem_json": {"protocol_version": 1, "code": "longesttrip", "name": "Longest Trip", "time_limit": 1.0, "memory_limit": 2147483648, "score_precision": 2, "task_type": "Communication", "task_type_params": "{\"task_type_parameters_Communication_num_processes\": 1}", "feedback_level": "oi_restricted"}} {"problem_id": "ioi14_a", "cate": ["graph", "math"], "difficulty": "medium", "cpu_time_limit_ms": 1000, "memory_limit_mb": 256, "description": "Taiwan has a big railway line connecting the western and eastern shores of the island. The line consists of blocks $m$. The consecutive blocks are numbered $0, \\ldots, m - 1$, starting from the western end. Each block has a one-way west-bound track on the north, a one-way east-bound track on the south, and optionally a train station between them.\n\nThere are three types of blocks. A type $C$ block has a train station that you must enter from the northern track and exit to the southern track, a type $D$ block has a train station that you must enter from the southern track and exit to the northern track, and a type empty block has no train station. For example, in the following figure block 0 is type empty, block 1 is type $C$, and block 5 is type $D$. Blocks connect to each other horizontally. Tracks of adjacent blocks are joined by connectors, shown as shaded rectangles in the following figure.\n\n![](https://ioi.contest.codeforces.com/espresso/365a386fce7b867cdf5592f3f5ed675f3cc2917d.png)\n\nThe railsystem has $n$ stations numbered from $0$ to $n - 1$. We assume that we can go from any station to any other station by following the track. For example we can go from station 0 to station 2 by starting from block 2, then passing through blocks 3 and 4 by the southern track, and then passing through station 1, then passing through block 4 by the northern track, and finally reaching station 2 at block 3.\n\nSince there are multiple possible routes, the distance from one station to another is defined as the minimum number of connectors the route passes through. For example the shortest route from station 0 to 2 is through blocks $2-3-4-5-4-3$ and passes through 5 connectors, so the distance is $5$.\n\nA computer system manages the railsystem. Unfortunately after a power outage the computer no longer knows where the stations are and what types of blocks they are in. The only clue the computer has is the block number of station 0, which is always in a type $C$ block. Fortunately the computer can query the distance from any station to any other station. For example, the computer can query \"what is the distance from station $0$ to station $2$?\" and it will receive $5$.\n\nTask\n\nYou need to implement a function findLocation that determines for each station the block number and block type.\n\n* void findLocation(int n, int first, int location[], int stype[])\n + $n$: the number of stations.\n + $first$: the block number of station $0$.\n + $location$: array of size $n$; you should place the block number of station $i$ into $location[i]$.\n + $stype$: array of size $n$; you should place the block type of station $i$ into $stype[i]$: $1$ for type $C$ and $2$ for type $D$.\n\nYou can call a function int getDistance(int i, int j) to help you find the locations and types of stations.\n\n* getDistance(i, j) returns the distance from station $i$ to station $j$\n* getDistance(i, i) will return $0$\n* getDistance(i, j) will return $-1$ if $i$ or $j$ is outside the range $0 \\le i, j \\le n - 1$.\n\nInput\n\nThe sample grader reads the input in the following format:\n\n* line 1: the subtask number\n* line 2: $n$\n* lines $3 + i (0 \\le i \\le n - 1)$: $stype[i]$ ($1$ for type $C$ and $2$ for type $D$), $location[i]$.\n\nOutput\n\nThe sample grader will print Correct if $location[0] \\ldots location[n - 1]$ and $stype[0] \\ldots stype[n - 1]$ computed by your program match the input when findLocation returns, or Incorrect if they do not match.\n\nScoring\n\nIn allsubtasks the number of blocks $m$ is no more than $1\\,000\\,000$. In some subtasks the number of calls to getDistance is limited. The limit varies by subtask. Your program will receive 'wrong answer' if it exceeds this limit.\n\n| | | | | |\n| --- | --- | --- | --- | --- |\n| Subtask | Points | $n$ | getDistance calls | note |\n| 1 | 8 | $1 \\le n \\le 100$ | unlimited | Allstations except $0$ are in type $D$ blocks. |\n| 2 | 22 | $1 \\le n \\le 100$ | unlimited | Allstations to the right of station $0$ are in type $D$ blocks, and allstations to the left of station $0$ are in type $C$ blocks. |\n| 3 | 26 | $1 \\le N \\le 5\\,000$ | $n(n - 1) / 2$ | No additional limits |\n| 4 | 44 | $1 \\le N \\le 5\\,000$ | $3(n - 1)$ | No additional limits |", "interactor_files": {"grader.cpp": "/* This is sample grader for the contestant */\n#include \n#include \n#include \n#include \n#include \n#include \"rail.h\"\n\ntypedef struct Station {\n int index;\n int type;\n int location;\n int L,R;\n}STATION;\nlong long cnt;\nstatic int S,SUBTASK;\nstatic STATION stations[10004];\n\nint cmp_fun_1(const void *a,const void *b)\n{\n\tSTATION c,d;\n\tc = *(STATION*)(a);\n\td = *(STATION*)(b);\n \treturn c.location < d.location ? -1 : 1;\n}\n\nint cmp_fun_2(const void *a,const void *b)\n{\n\tSTATION c,d;\n\tc = *(STATION*)(a);\n\td = *(STATION*)(b);\n \treturn c.index < d.index ? -1 : 1;\n}\n\nvoid now_I_want_to_getLR(){\n int now = stations[S-1].index,i;\n for(i=S-2;i>=0;i--){\n stations[i].R = now;\n if(stations[i].type==2)\tnow = stations[i].index;\n }\n now = stations[0].index;\n for(i=1;i=S || y<0 || y>=S) return -1;\n if(stations[x].location > stations[y].location){\n \tint tmp = x;\n\tx = y;\n\ty = tmp;\n }\n int ret = 0;\n if(stations[x].type==1 && stations[y].type==1){\n ret = stations[stations[y].R].location-stations[x].location+stations[stations[y].R].location-stations[y].location;\n }else if(stations[x].type==1 && stations[y].type==2){\n ret = stations[y].location-stations[x].location;\n }else if(stations[x].type==2 && stations[y].type==2){\n ret = stations[x].location-stations[stations[x].L].location+stations[y].location-stations[stations[x].L].location;\n }else if(stations[x].type==2 && stations[y].type==1){\n ret = stations[x].location-stations[stations[x].L].location+stations[stations[y].R].location\n -stations[stations[x].L].location+stations[stations[y].R].location-stations[y].location;\n }\n return ret;\n}\n\n\nvoid getInput()\n{\n int g;\n g = scanf(\"%d\",&SUBTASK);\n g = scanf(\"%d\",&S);\n int s;\n for (s = 0; s < S; s++) {\n int type, location;\n g = scanf(\" %d %d\",&type,&location);\n stations[s].index = s;\n stations[s].location = location;\n stations[s].type = type;\n stations[s].L = -1;\n stations[s].R = -1;\n }\n qsort(stations, S, sizeof(STATION), cmp_fun_1);\n now_I_want_to_getLR();\n qsort(stations, S, sizeof(STATION), cmp_fun_2);\n}\n\nint serverGetStationNumber()\n{\n return S;\n}\n\nint serverGetSubtaskNumber()\n{\n return SUBTASK;\n}\n\nint serverGetFirstStationLocation()\n{\n return stations[0].location;\n}\n\nint main()\n{\n int i;\n getInput();\n cnt = 0;\n \n int location[10005];\n int type[10005];\n int ok = 1;\n findLocation(S, serverGetFirstStationLocation(),location, type);\n if(SUBTASK==3 && cnt>S*(S-1))\tok = 0;\n if(SUBTASK==4 && cnt>3*(S-1))\tok = 0;\n \n \n for (i = 0; i < S; i++)\n if(type[i]!=stations[i].type || location[i]!=stations[i].location)\n ok = 0;\n if(ok==0)\tprintf(\"Incorrect\");\n else\tprintf(\"Correct\");\n return 0;\n}\n", "rail.cpp": "#include \"rail.h\"\n\nvoid findLocation(int N, int first, int location[], int stype[])\n{\n\n}\n", "rail.h": "#ifndef __RAIL_H__\n#define __RAIL_H__\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n void findLocation(int n, int first, int location[], int stype[]);\n \n int getDistance(int i, int j);\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __RAIL_H__ */\n\n"}} {"problem_id": "ioi20_e", "cate": ["search", "math"], "difficulty": "medium", "cpu_time_limit_ms": 2000, "memory_limit_mb": 1024, "description": "Andrew the mushroom expert is investigating mushrooms native to Singapore.\n\nAs part of his research, Andrew collected $n$ mushrooms labelled $0$ to $n-1$. Each mushroom is of one of two species, which are called A and B.\n\nAndrew knows that mushroom $0$ belongs to species A, but as the two species look the same, he does not know the species of mushrooms $1$ to $n-1$.\n\nFortunately, Andrew has a machine in his lab that can help with this. To use this machine, one should place two or more mushrooms in a row inside the machine (in any order) and turn the machine on. Then, the machine calculates the number of adjacent pairs of mushrooms that are of different species. For example, if you place mushrooms of species $[A, B, B, A]$ (in that order) into the machine, the result will be $2$.\n\nHowever, as operating the machine is very expensive, the machine can be used for a limited number of times. In addition, the total number of mushrooms placed in the machine across all its uses cannot exceed $100\\,000$. Use this machine to help Andrew count the number of mushrooms of species A collected.\n\nImplementation details\n\nYou should implement the following procedure:\n\n* int count\\_mushrooms(int n)\n + $n$: number of mushrooms collected by Andrew.\n + This procedure is called exactly once, and should return the number of mushrooms of species A.\n\nThe above procedure can make calls to the following procedure:\n\n* int use\\_machine(int[] x)\n + $x$: an array of length between $2$ and $n$ inclusive, describing the labels of the mushrooms placed in the machine, in order.\n + The elements of $x$ must be distinct integers from $0$ to $n-1$ inclusive.\n + Let $d$ be the length of array $x$. Then, the procedure returns the number of different indices $j$, such that $0 \\leq j \\leq d-2$ and mushrooms $x[j]$ and $x[j+1]$ are of different species.\n + This procedure can be called at most $20\\,000$ times.\n + The total length of $x$ passed to the procedure use\\_machine among all its invocations cannot exceed $100\\,000$.\n\nInput\n\nThe sample grader reads an array $s$ of integers giving the mushroom species. For all $0 \\leq i \\leq n-1$, $s[i] = 0$ means the species of mushroom $i$ is A, whereas $s[i] = 1$ means the species of mushroom $i$ is B. The sample grader reads input in the following format:\n\n* line $1$: $n$ ($2 \\leq n \\leq 20\\,000$)\n* line $2$: $s[0]\\ s[1] \\ldots s[n-1]$\n\nOutput\n\nThe output of sample grader is in the following format:\n\n* line $1$: the return value of count\\_mushrooms.\n* line $2$: the number of calls to use\\_machine.\n\nNote that the sample grader is not adaptive.\n\nInteraction\n\nIn 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 mushroom species. Instead, the answers given by the grader may depend on the prior calls to use\\_machine. Though, it is guaranteed that the grader answers in such a way that after each interaction there is at least one sequence of mushroom species consistent with all the answers given so far.\n\nScoring\n\nIf in any of the test cases, the calls to the procedure use\\_machine do not conform to the rules mentioned above, or the return value of count\\_mushrooms is incorrect, the score of your solution will be $0$. Otherwise, let $Q$ be the maximum number of calls to the procedure use\\_machine among all test cases. Then, the score will be calculated according to the following table:\n\n| | |\n| --- | --- |\n| Condition | Score |\n| $20\\,000 \\textless Q$ | 0 |\n| $10\\,010 \\textless Q \\le 20\\,000$ | 10 |\n| $904 \\textless Q \\le 10\\,010$ | 25 |\n| $226 \\textless Q \\le 904$ | $100 \\cdot \\frac{226}{Q}$ |\n| $Q \\le 226$ | 100 |\n\nNote\n\nExample 1\n\nConsider a scenario in which there are $3$ mushrooms of species $[A, B, B]$, in order. The procedure count\\_mushrooms is called in the following way:\n\ncount\\_mushrooms(3)\n\nThis procedure may call use\\_machine([0, 1, 2]), which (in this scenario) returns $1$.\n\nIt may then call use\\_machine([2, 1]), which returns $0$.\n\nAt this point, there is sufficient information to conclude that there is only $1$ mushroom of species A. So, the procedure count\\_mushrooms should return $1$.\n\nExample 2\n\nConsider a case in which there are $4$ mushrooms with species $[A, B, A, A]$, in order. The procedure count\\_mushrooms is called as below:\n\ncount\\_mushrooms(4)\n\nThis procedure may call use\\_machine([0, 2, 1, 3]), which returns $2$.\n\nIt may then call use\\_machine([1, 2]), which returns $1$.\n\nAt this point, there is sufficient information to conclude that there are $3$ mushrooms of species A. Therefore, the procedure count\\_mushrooms should return $3$.", "interactor_files": {"manager.cpp": "/*\n * Judge manager (interacts with graders)\n * Task: mushrooms\n * The manager itself produces the judgement results (including the scores).\n * Author: Kian Mirjalali\n */\n#include \"testlib.h\"\n#include \n#include \nusing namespace std;\n\n\n\n/*********************** Begin helper definitions for compiling in Windows ***********************/\n#ifdef ON_WINDOWS\ntypedef __p_sig_fn_t __sighandler_t;\n#define SIGPIPE 13\nstruct sigaction {\n\t__sighandler_t sa_handler;\n};\nint sigaction(int, const struct sigaction *__restrict, struct sigaction *__restrict) {\n\treturn 0;\n}\n#endif\n/************************ End helper definitions for compiling in Windows ************************/\n\n\n/****************************** Begin FactoryRegistry and tools for self-registering classes ******************************/\n/**\n * A FactoryRegistry can create instances of (sub)type T.\n * The exact type for instantiation is specified by a (string) key.\n */\ntemplate\nstruct FactoryRegistry {\n\ttypedef T InstanceType;\n\ttypedef unique_ptr InstancePtr;\n\ttypedef InstancePtr (*FactoryFunction)();\nprivate:\n\tmap factories;\n\npublic:\n\n\tinline void registerFactory(string name, FactoryFunction factoryFunc) {\n\t\tfactories[name] = factoryFunc;\n\t}\n\n\ttemplate & factoryRegistry>\n\tclass SelfRegisteringInstanceMixin {\n\t\tstruct _RegisteringObject {\n\t\t\tinline _RegisteringObject() {\n\t\t\t\tFactoryFunction factoryFunc = []() -> InstancePtr {\n\t\t\t\t\treturn make_unique();\n\t\t\t\t};\n\t\t\t\tfactoryRegistry.registerFactory(registrationName, factoryFunc);\n\t\t\t}\n\t\t};\n\t\tstatic _RegisteringObject _registeringObject;\n\t\t// will force instantiation of definition of static member\n\t\ttemplate<_RegisteringObject&> struct _RegisteringObjectReferrer {};\n\t\tstatic _RegisteringObjectReferrer<_registeringObject> _registeringObjectReferrer;\n\t};\n\n\tinline InstancePtr create(string name) {\n\t\tauto it = factories.find(name);\n\t\tif (it == factories.end())\n\t\t\treturn nullptr;\n\t\tFactoryFunction factory = it->second;\n\t\tInstancePtr instance = factory();\n\t\treturn instance;\n\t}\n};\n\ntemplate template& factoryRegistry>\n\ttypename FactoryRegistry::template SelfRegisteringInstanceMixin::_RegisteringObject\n\tFactoryRegistry::SelfRegisteringInstanceMixin::_registeringObject;\n\n#define __REGISTRATION_NAME_FOR__(className) __REGISTRATION_NAME_FOR__##className##__\n\n#define SELF_REGISTERED(structOrClass, className, registrationName, selfRegisteringInstanceMixinClass) \\\n\tchar __REGISTRATION_NAME_FOR__(className)[] = (registrationName); \\\n\tstructOrClass className: selfRegisteringInstanceMixinClass\n\n#define DEFINE_SELF_REGISTERING_INSTANCE_MIXIN(mixinName, factoryRegistry) \\\ntemplate using mixinName = \\\n\tFactoryRegistry::SelfRegisteringInstanceMixin\n\n/******************************* End FactoryRegistry and tools for self-registering classes *******************************/\n\n\n/****************************** Begin template/utility codes ******************************/\n#define fori(i, n) for (int i=0; (i<(n)); i++)\n#define forv(i, v) fori(i, sz(v))\n#define forall(x, c) for (auto& x: c)\n#define allOf(c) ((c).begin()), ((c).end())\n\n\ntypedef vector VI;\n\ntemplate\ninline T sqr(const T& x) {\n\treturn x*x;\n}\n\ntemplate\ninline int sz(const T& c) {\n\treturn c.size();\n}\n\n/**\n * Reads a single word from a FILE\n * @param s The variable to store the word on success\n * @return true on success\n */\ninline bool readStr(FILE* f, string& s) {\n\tstatic char buff[1000000];\n\tif (1 != fscanf(f, \"%999999s\", buff))\n\t\treturn false;\n\ts = buff;\n\treturn true;\n}\n\n/**\n * Reads a single line from a FILE\n * New line characters in the end of the line (if any) are trimmed.\n * @param s The variable to store the line on success\n * @return true on success\n */\ninline bool readLine(FILE* f, string& s) {\n\tconst int max_len = 1000000;\n\tstatic char buff[max_len];\n\tif (!fgets(buff, max_len, f))\n\t\treturn false;\n\tbuff[strcspn(buff, \"\\r\\n\")] = 0; //Remove trailing newline characters\n\ts = buff;\n\treturn true;\n}\n\ninline string vec2str(const VI& v) {\n\tstring s;\n\tforv(i, v)\n\t\ts += format((i?\" %d\":\"%d\"), v[i]);\n\treturn s;\n}\n#define vec2cstr(v) ((vec2str(v)).c_str())\n\ntemplate\ninline int count(const C& c, T value) {\n\treturn count(allOf(c), value);\n}\n\n/******************************* End template/utility codes *******************************/\n\n\nconst int TYPE_0 = 0;\nconst int TYPE_1 = 1;\nconst int N_TYPES = 2;\n\nint n;\n\ninline int count_diffs(const VI& species, const VI& index) {\n\tint diffs = 0;\n\tfor (int i = 1; i < sz(index); i++)\n\t\tdiffs += int(species[index[i]] != species[index[i-1]]);\n\treturn diffs;\n}\n\nclass ManagerStrategy {\npublic:\n\tvirtual void read_input(InStream& inStream) = 0;\n\tvirtual void describe_in_one_line(FILE* file) const = 0;\n\tvirtual int ask(const VI& x) = 0;\n\tvirtual bool checkAnswer(int answer) = 0;\n\tvirtual VI get_species() = 0;\n\tvirtual ~ManagerStrategy() = default;\n};\n\n\nFactoryRegistry strategyFactoryRegistry;\nDEFINE_SELF_REGISTERING_INSTANCE_MIXIN(SelfRegisteringStrategyMixin, strategyFactoryRegistry);\n#define REGISTERED_STRATEGY(className, registrationName, parentClass) \\\n\tSELF_REGISTERED(struct, className, registrationName, SelfRegisteringStrategyMixin), public parentClass\n\n\n/******************************** Begin different implementations for manager strategies ********************************/\n\n/// Reads the types thoroughly from the input\nREGISTERED_STRATEGY(ManagerStrategy_Plain, \"plain\", ManagerStrategy) {\n\tVI species;\npublic:\n\tvirtual void read_input(InStream& inStream) {\n\t\tn = inStream.readInt();\n\t\tspecies = inStream.readInts(n, TYPE_0, N_TYPES-1, \"species[i]\", 0);\n\t}\n\tvirtual void describe_in_one_line(FILE* file) const {\n\t\tfprintf(file, \"%d %s\", n, vec2cstr(species));\n\t}\n\tvirtual int ask(const VI& x) {\n\t\treturn count_diffs(species, x);\n\t}\n\tvirtual bool checkAnswer(int answer) {\n\t\treturn answer == count(species, TYPE_0);\n\t}\n\tvirtual VI get_species() {\n\t\treturn species;\n\t}\n};\n\n\n/// Descendants of this strategy keep the types partially specified and lazily set their values (on demand).\nclass ManagerStrategyWithPartiallySpecifiedTypes: public ManagerStrategy {\nprotected:\n\tstatic const int TYPE_UNSPECIFIED = -1;\n\tinline bool is_unspecified(int index) {\n\t\treturn species[index] == TYPE_UNSPECIFIED;\n\t}\n\tinline bool is_specified(int index) {\n\t\treturn species[index] != TYPE_UNSPECIFIED;\n\t}\n\n\tVI species;\n\n\tinline void init_species() {\n\t\tspecies = VI(n, TYPE_UNSPECIFIED);\n\t\tspecies[0] = TYPE_0;\n\t}\n\npublic:\n\tvirtual bool checkAnswer(int answer) {\n\t\tint scn = count(species, TYPE_UNSPECIFIED);\n\t\tint sc0 = count(species, TYPE_0);\n\t\tif (scn == 0)\n\t\t\treturn answer == sc0;\n\t\tint t = (sc0 < answer) ? TYPE_1 : TYPE_0;\n\t\treplace(allOf(species), TYPE_UNSPECIFIED, t);\n\t\treturn false;\n\t}\n\tvirtual VI get_species() {\n\t\treplace(allOf(species), TYPE_UNSPECIFIED, TYPE_0);\n\t\treturn species;\n\t}\n};\n\n\n/// Sets the types to random values, lazily (on demand).\nREGISTERED_STRATEGY(ManagerStrategy_Adversary_SimpleRandom, \"adversary_simple_random\", ManagerStrategyWithPartiallySpecifiedTypes) {\n\tint seed;\npublic:\n\tvirtual void read_input(InStream& inStream) {\n\t\tn = inStream.readInt();\n\t\tinit_species();\n\t\tseed = inStream.readInt();\n\t\trnd.setSeed(seed);\n\t}\n\tvirtual void describe_in_one_line(FILE* file) const {\n\t\tfprintf(file, \"%d %d\", n, seed);\n\t}\n\tvirtual int ask(const VI& x) {\n\t\tforall(xi, x)\n\t\t\tif (is_unspecified(xi))\n\t\t\t\tspecies[xi] = rnd.next(N_TYPES);\n\t\treturn count_diffs(species, x);\n\t}\n};\n\n\n/// Balanced Random with p * n type A species\nREGISTERED_STRATEGY(ManagerStrategy_Adversary_BalancedRandom, \"adversary_balanced_random\", ManagerStrategyWithPartiallySpecifiedTypes) {\n\tint seed;\n\tdouble p;\n\tVI species_stack;\npublic:\n\tvirtual void read_input(InStream& inStream) {\n\t\tn = inStream.readInt();\n\t\tinit_species();\n\t\tp = inStream.readDouble(0, 1, \"p\");\n\t\tseed = inStream.readInt();\n\t\trnd.setSeed(seed);\n\n\t\tspecies_stack = VI(n-1, TYPE_1);\n\t\tint zeros = int(p * (n-1));\n\t\tfill_n(species_stack.begin(), zeros, TYPE_0);\n\t\tshuffle(allOf(species_stack));\n\t}\n\tvirtual void describe_in_one_line(FILE* file) const {\n\t\tfprintf(file, \"%d %f %d\", n, p, seed);\n\t}\n\tvirtual int ask(const VI& x) {\n\t\tforall(xi, x)\n\t\t\tif (is_unspecified(xi)) {\n\t\t\t\tspecies[xi] = species_stack.back();\n\t\t\t\tspecies_stack.pop_back();\n\t\t\t}\n\t\treturn count_diffs(species, x);\n\t}\n};\n\n\n/**\n * Two types of queries are considered: small and large.\n * A query is considered large if number of its unspecified elements exceeds a threshold.\n * We assume that the solution can detect the element types in small queries.\n * The strategy tries to equalize the known types in small queries and act random in large queries.\n */\nREGISTERED_STRATEGY(ManagerStrategy_Adversary_SmallEqual, \"adversary_small_equal\", ManagerStrategyWithPartiallySpecifiedTypes) {\n\tint seed;\n\t/// The threshold for small vs. large queries.\n\tint qthreshold;\n\t/**\n\t * Specifies the species type equalizing strategy:\n\t * true: The strategy tries to equalize the known types for all of the elements with specified species.\n\t * false: The strategy tries to equalize the known types for only the elements that the solution has (possibly) detected.\n\t */\n\tbool total_equalizing;\n\tint cnt[N_TYPES];\npublic:\n\tvirtual void read_input(InStream& inStream) {\n\t\tn = inStream.readInt();\n\t\tinit_species();\n\t\tqthreshold = inStream.readInt(0, n, \"qthreshold\");\n\t\ttotal_equalizing = inStream.readInt(0, 1, \"total_equalizing\") == 1;\n\t\tseed = inStream.readInt();\n\t\trnd.setSeed(seed);\n\t\tcnt[TYPE_0] = 1;\n\t\tcnt[TYPE_1] = 0;\n\t}\n\tvirtual void describe_in_one_line(FILE* file) const {\n\t\tfprintf(file, \"%d %d %d %d\", n, qthreshold, total_equalizing, seed);\n\t}\n\tvirtual int ask(const VI& x) {\n\t\tvector ultimate_unspecifieds;\n\t\tfor (int i = 1; i < sz(x)-1; i++)\n\t\t\tif (is_unspecified(x[i])\n\t\t\t\t\t&& is_specified(x[i-1])\n\t\t\t\t\t&& is_specified(x[i+1])\n\t\t\t\t\t&& species[x[i-1]] != species[x[i+1]]) {\n\t\t\t\tultimate_unspecifieds.push_back(x[i]);\n\t\t\t\tspecies[x[i]] = TYPE_0;\n\t\t\t}\n\n\t\tint unspecified = count_if(allOf(x), [&] (int xi) {return is_unspecified(xi);});\n\t\tbool small_query = (unspecified <= qthreshold);\n\n\t\tforall(xi, x)\n\t\t\tif (is_unspecified(xi)) {\n\t\t\t\tspecies[xi] = small_query ? (cnt[TYPE_0] < cnt[TYPE_1] ? TYPE_0 : TYPE_1) : rnd.next(N_TYPES);\n\t\t\t\tif (small_query || total_equalizing)\n\t\t\t\t\tcnt[species[xi]]++;\n\t\t\t}\n\n\t\tint ret = count_diffs(species, x);\n\n\t\tforall(xi, ultimate_unspecifieds)\n\t\t\tspecies[xi] = TYPE_UNSPECIFIED;\n\n\t\treturn ret;\n\t}\n};\n/********************************* End different implementations for manager strategies *********************************/\n\n\n/******************************** Begin testlib-related material ********************************/\n\ninline FILE* openFile(const char* name, const char* mode) {\n\tFILE* file = fopen(name, mode);\n\tif (!file)\n\t\tquitf(_fail, \"Could not open file '%s' with mode '%s'.\", name, mode);\n\tcloseOnHalt(file);\n\treturn file;\n}\n\nFILE *fifo_in, *fifo_out, *logfile;\n\nvoid registerManager(std::string probName, int argc, char* argv[]) {\n\tsetName(\"manager for problem %s\", probName.c_str());\n\t__testlib_ensuresPreconditions();\n\ttestlibMode = _checker;\n\trandom_t::version = 1; // Random generator version\n\t__testlib_set_binary(stdin);\n\touf.mode = _output;\n\n\t{//Keep alive on broken pipes\n\t\t//signal(SIGPIPE, SIG_IGN);\n\t\tstruct sigaction sa;\n\t\tsa.sa_handler = SIG_IGN;\n\t\tsigaction(SIGPIPE, &sa, NULL);\n\t}\n\n\tif (argc < 3 || 4 < argc)\n\t\tquitf(_fail,\n\t\t\t\"Manager for problem %s:\\n\"\n\t\t\t\"Invalid number of arguments: %d\\n\"\n\t\t\t\"Usage: '%s' sol2mgr-pipe mgr2sol-pipe [mgr_log] < input-file\",\n\t\t\tprobName.c_str(), argc-1, argv[0]);\n\n\tinf.init(stdin, _input);\n\tcloseOnHalt(stdout);\n\tcloseOnHalt(stderr);\n\tfifo_out = openFile(argv[2], \"a\");\n\tfifo_in = openFile(argv[1], \"r\");\n\tlogfile = NULL;\n\tif (argc > 3)\n\t\tlogfile = openFile(argv[3], \"w\");\n}\n\ninline string tresult2str(TResult result) {\n\tswitch (result) {\n\tcase _ok: return \"OK\";\n\tcase _wa: return \"WA\";\n\tcase _fail: return \"FAIL\";\n\tcase _points: return \"PARTIAL\";\n\tcase _sv : return \"SV\";\n\tdefault: return \"UNKNOWN\";\n\t}\n}\n/********************************* End testlib-related material *********************************/\n\n\ninline void writelnFifo(int i) {\n\tfprintf(fifo_out, \"%d\\n\", i);\n\tfflush(fifo_out);\n}\n\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid logprintf(const char* msgfmt, ...) {\n\tif (logfile) {\n\t\tFMT_TO_RESULT(msgfmt, msgfmt, message);\n\t\tfprintf(logfile, \"%s\", message.c_str());\n\t\tfflush(logfile);\n\t}\n}\n\n\nunique_ptr strategy;\nvector< pair > queries; //vector(pair(query, response))\nvector< pair > answer_optional; //vector(pair(answer, accepted)), 0 <= size <= 1\ndouble _parital_score;\n\n\ninline bool is_scenario_valid(const VI& species, string& reason) {\n\t#define verify(condition, msg) do if (!(condition)) { reason = (msg); return false; } while (false)\n\t//Verifying the species\n\tverify(sz(species) == n, format(\"Invalid length of species %d.\", sz(species)));\n\tfori(i, n)\n\t\tverify(TYPE_0 <= species[i] && species[i] < N_TYPES, format(\"Invalid species value %d at position %d\", species[i], i));\n\tverify(species[0] == TYPE_0, format(\"First element must be of type %d\", TYPE_0));\n\t// Verifying correctness of query responses\n\tforv(i, queries) {\n\t\tint response = queries[i].second;\n\t\tint correct_response = count_diffs(species, queries[i].first);\n\t\tverify(response == correct_response, format(\"Wrong response (%d) for query %d (expected %d).\", response, i+1, correct_response));\n\t}\n\t// Verifying the acceptance of the answer\n\tif (!answer_optional.empty()) {\n\t\tint answer = answer_optional[0].first;\n\t\tbool accepted = answer_optional[0].second;\n\t\tint correct_answer = count(species, TYPE_0);\n\t\tbool matched = (answer == correct_answer);\n\t\tverify(matched == accepted, accepted ?\n\t\t\t\tformat(\"Answer (%d) is accepted, but correct answer is %d.\", answer, correct_answer):\n\t\t\t\tformat(\"Answer (%d) is rejected, but it is correct.\", answer));\n\t}\n\treturn true;\n\t#undef verify\n}\n\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nNORETURN inline void finish(TResult result, bool sendDie, const char* msgfmt, ...) {\n\tif (sendDie) {\n\t\tlogprintf(\"-1\\n\");\n\t\twritelnFifo(-1);\n\t}\n\n\tif (answer_optional.empty())\n\t\tlogprintf(\"NA\\n\");\n\telse\n\t\tlogprintf(\"A %d\\n\", answer_optional[0].first);\n\n\tVI species = strategy->get_species();\n\tlogprintf(\"%s\\n\", vec2cstr(species));\n\n\tFMT_TO_RESULT(msgfmt, msgfmt, message);\n\tif (!is_scenario_valid(species, message)) {\n\t\tresult = _fail;\n\t\tmessage = \"Invalid strategy behavior: \" + message;\n\t}\n\n\tlogprintf(\"%s\\n%s\\n\", tresult2str(result).c_str(), message.c_str());\n\tif (result == _points)\n\t\tquitp(_parital_score, message);\n\telse\n\t\tquit(result, message);\n}\n\ninline int readFifoInteger(const char* name) {\n\tint x;\n\tif (1 != fscanf(fifo_in, \"%d\", &x))\n\t\tfinish(_fail, false, \"Could not read integer %s (IO error).\", name);\n\treturn x;\n}\n\nNORETURN inline void quit_partial(double grade, int qc) {\n\t_parital_score = grade/double(100);\n\tfinish(_points, false, \"Number of queries: %d\", qc);\n}\n\nconst int min_n = 2;\nconst int max_n = 20000;\nconst int max_qc = 20000;\nconst int max_qs = 100000;\n\nNORETURN inline void finish_with_scoring(int qc) {\n\t#define qp(grade) quit_partial((grade), qc)\n\tif (max_qc < qc) finish(_wa, false, \"Too many queries.\");\n\tif (10010 < qc) qp(10);\n\tif (904 < qc) qp(25);\n\tif (226 < qc) qp(226.0/qc*100);\n\t/* (qc <= 226) */\n\t//qp(100);\n\tfinish(_ok, false, \"%s\", \"\");\n\t#undef qp\n}\n\nint main(int argc, char **argv) {\n\tregisterManager(\"mushrooms\", argc, argv);\n\n\tstring strategy_type = inf.readToken();\n\tlogprintf(\"%s\\n\", strategy_type.c_str());\n\tstrategy = strategyFactoryRegistry.create(strategy_type);\n\tif (!strategy)\n\t\tquitf(_fail, \"Invalid strategy type '%s'\", strategy_type.c_str());\n\tregisterHaltListener([]() {\n\t\tstrategy.reset(nullptr);\n\t});\n\tstrategy->read_input(inf);\n\tif (logfile)\n\t\tstrategy->describe_in_one_line(logfile);\n\tlogprintf(\"\\n\");\n\n\tlogprintf(\"%d\\n\", n);\n\tif (n < min_n || max_n < n)\n\t\tquitf(_fail, \"Invalid value of n: %d\", n);\n\n\tint qc = 0;\n\tint qs = 0;\n\tqueries.clear();\n\tanswer_optional.clear();\n\n\twritelnFifo(n);\n\twhile (true) {\n\t\tstring cmd;\n\t\tif (!readStr(fifo_in, cmd)) {\n\t\t\tlogprintf(\"N\\n\\n\");\n\t\t\tfinish(_wa, false, \"No more action (solution possibly terminated).\");\n\t\t}\n\t\tif (cmd==\"Q\") {// Query\n\t\t\tint k = readFifoInteger(\"k\");\n\t\t\tVI x(k);\n\t\t\tfori(i, k)\n\t\t\t\tx[i] = readFifoInteger(\"x[i]\");\n\t\t\tlogprintf(\"Q %d %s\\n\", k, vec2cstr(x));\n\t\t\t// Validating query\n\t\t\tif (k < 2)\n\t\t\t\tfinish(_wa, true, \"Too small array for query.\");\n\t\t\tif (k > n)\n\t\t\t\tfinish(_wa, true, \"Too large array for query.\");\n\t\t\tqc++;\n\t\t\tif (qc > max_qc)\n\t\t\t\tfinish(_wa, true, \"Too many queries.\");\n\t\t\tqs += k;\n\t\t\tif (qs > max_qs)\n\t\t\t\tfinish(_wa, true, \"Too many total array sizes as queries.\");\n\t\t\tfori(i, k)\n\t\t\t\tif (x[i] < 0 || n - 1 < x[i])\n\t\t\t\t\tfinish(_wa, true, \"Invalid value %d in the query array.\", x[i]);\n\t\t\tvector used(n, false);\n\t\t\tfori(i, k) {\n\t\t\t\tif (used[x[i]])\n\t\t\t\t\tfinish(_wa, true, \"Duplicate value %d in the query array.\", x[i]);\n\t\t\t\tused[x[i]] = true;\n\t\t\t}\n\t\t\t// Evaluating, logging, and sending response\n\t\t\tint response = strategy->ask(x);\n\t\t\tlogprintf(\"%d\\n\", response);\n\t\t\tqueries.emplace_back(x, response);\n\t\t\twritelnFifo(response);\n\t\t} else if (cmd==\"W\") {//Wrong query detected in grader\n\t\t\tstring reason;\n\t\t\tif ((fscanf(fifo_in, \" \") != 0) || !readLine(fifo_in, reason))\n\t\t\t\tfinish(_fail, false, \"Could not read reason for WA in grader (protocol error).\");\n\t\t\tlogprintf(\"W %s\\n\\n\", reason.c_str());\n\t\t\tfinish(_wa, false, \"%s\", reason.c_str());\n\t\t} else if (cmd==\"A\") {// Answer\n\t\t\tint answer = readFifoInteger(\"answer\");\n\t\t\tbool accept = strategy->checkAnswer(answer);\n\t\t\tanswer_optional.emplace_back(answer, accept);\n\t\t\tif (!accept)\n\t\t\t\tfinish(_wa, false, \"Answer is not correct.\");\n\t\t\tfinish_with_scoring(qc);\n\t\t} else {\n\t\t\tfinish(_fail, false, \"Invalid action (protocol error).\");\n\t\t}\n\t}\n\tfinish(_fail, false, \"Must not reach here!\");\n}\n", "stub.cpp": "/*\n * Judge grader for C++\n * Task: mushrooms\n * Author: Kian Mirjalali\n */\n#include \n#include \n#include \n#include \n#include \n#include \"mushrooms.h\"\nusing namespace std;\n\n#ifdef _MSC_VER\n#define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n#define NORETURN __attribute__ ((noreturn))\n#else\n#define NORETURN\n#endif\n\nstatic char fmt_buffer[100000];\n#define FMT_TO_STR(fmt, result) va_list vargs; va_start(vargs, fmt); \\\n\tvsnprintf(fmt_buffer, sizeof(fmt_buffer), fmt, vargs); \\\n\tva_end(vargs); fmt_buffer[sizeof(fmt_buffer)-1] = 0; \\\n\tstd::string result(fmt_buffer);\n\nstatic int n;\nstatic FILE* fifo_in = NULL;\nstatic FILE* fifo_out = NULL;\n\n#ifdef __GNUC__\n__attribute__ ((format(printf, 2, 3)))\n#endif\nNORETURN static inline void die(int exit_code=0, const char* message_fmt=NULL, ...) {\n\tif (message_fmt) {\n\t\tFMT_TO_STR(message_fmt, message);\n\t\tfprintf(stderr, \"%s\\n\", message.c_str());\n\t}\n\tif (fifo_in)\n\t\tfclose(fifo_in);\n\tif (fifo_out)\n\t\tfclose(fifo_out);\n\texit(exit_code);\n}\n\nstatic inline int readFifoInteger(string name) {\n\tint x;\n\tif (1 != fscanf(fifo_in, \"%d\", &x))\n\t\tdie(3, \"Grader error: Could not read %s.\", name.c_str());\n\treturn x;\n}\n\nstatic inline void wrong_if(bool cond, string message) {\n\tif (cond) {\n\t\tfprintf(fifo_out, \"W %s\\n\", message.c_str());\n\t\tfflush(fifo_out);\n\t\tdie();\n\t}\n}\n\nint use_machine(vector x) {\n\t#ifdef _GLIBCXX_HAS_GTHREADS\n\tstatic mutex _mutex;\n\tlock_guard lock(_mutex);\n\t#endif\n\tconst int k = x.size();\n\twrong_if(k > n, \"Too large array for query.\");\n\tfprintf(fifo_out, \"Q %d\", k);\n\tfor (int i = 0; i < k; i++)\n\t\tfprintf(fifo_out, \" %d\", x[i]);\n\tfprintf(fifo_out, \"\\n\");\n\tfflush(fifo_out);\n\tint response = readFifoInteger(\"query response\");\n\tif (response < 0) // 'Die' sent from manager\n\t\tdie();\n\treturn response;\n}\n\nint main(int argc, char **argv) {\n\tfclose(stdin);\n\tfclose(stdout);\n\tif (argc < 3)\n\t\tdie(1, \"Grader error: Invalid number of arguments: %d\", argc-1);\n\tfifo_in = fopen(argv[1], \"r\");\n\tif (!fifo_in)\n\t\tdie(2, \"Grader error: Could not open file '%s' for reading.\", argv[1]);\n\tfifo_out = fopen(argv[2], \"a\");\n\tif (!fifo_out)\n\t\tdie(2, \"Grader error: Could not open file '%s' for writing.\", argv[2]);\n\n\tn = readFifoInteger(\"'n'\");\n\tint answer = count_mushrooms(n);\n\tfprintf(fifo_out, \"A %d\\n\", answer);\n\tfflush(fifo_out);\n\tdie();\n}\n", "mushrooms.h": "#include \n\nint count_mushrooms(int n);\n\nint use_machine(std::vector x);\n\n", "testlib.h": "/* \n * It is strictly recommended to include \"testlib.h\" before any other include \n * in your code. In this case testlib overrides compiler specific \"random()\".\n *\n * If you can't compile your code and compiler outputs something about \n * ambiguous call of \"random_shuffle\", \"rand\" or \"srand\" it means that \n * you shouldn't use them. Use \"shuffle\", and \"rnd.next()\" instead of them\n * because these calls produce stable result for any C++ compiler. Read \n * sample generator sources for clarification.\n *\n * Please read the documentation for class \"random_t\" and use \"rnd\" instance in\n * generators. Probably, these sample calls will be usefull for you:\n * rnd.next(); rnd.next(100); rnd.next(1, 2); \n * rnd.next(3.14); rnd.next(\"[a-z]{1,100}\").\n *\n * Also read about wnext() to generate off-center random distribution.\n *\n * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker.\n */\n\n#ifndef _TESTLIB_H_\n#define _TESTLIB_H_\n\n/*\n * Copyright (c) 2005-2018\n */\n\n#define VERSION \"0.9.21\"\n\n/* \n * Mike Mirzayanov\n *\n * This material is provided \"as is\", with absolutely no warranty expressed\n * or implied. Any use is at your own risk.\n *\n * Permission to use or copy this software for any purpose is hereby granted \n * without fee, provided the above notices are retained on all copies.\n * Permission to modify the code and to distribute modified code is granted,\n * provided the above notices are retained, and a notice that the code was\n * modified is included with the above copyright notice.\n *\n */\n\n/*\n * Kian Mirjalali:\n *\n * Modified to be compatible with CMS & requirements for preparing IOI tasks\n *\n * * defined FOR_LINUX in order to force linux-based line endings in validators.\n *\n * * Changed the ordering of checker arguments\n * from \n * to \n *\n * * Added \"Security Violation\" as a new result type.\n *\n * * Changed checker quit behaviors to make it compliant with CMS.\n *\n * * The checker exit codes should always be 0 in CMS.\n *\n * * For partial scoring, forced quitp() functions to accept only scores in the range [0,1].\n * If the partial score is less than 1e-5, it becomes 1e-5, because 0 grades are considered wrong in CMS.\n * Grades in range [1e-5, 0.001) are printed exactly (to prevent rounding to zero).\n * Grades in [0.001, 1] are printed with 3 digits after decimal point.\n *\n * * Added the following utility types/functions/methods:\n * type HaltListener (as a function with no parameters or return values)\n * vector __haltListeners\n * void registerHaltListener(HaltListener haltListener)\n * void callHaltListeners() (which is called in quit)\n * void closeOnHalt(FILE* file)\n * void InStream::readSecret(string secret)\n * void InStream::readGraderResult()\n * +supporting conversion of graderResult to CMS result\n * void quitp(double), quitp(int)\n * void registerChecker(string probName, argc, argv)\n * void readBothSecrets(string secret)\n * void readBothGraderResults()\n * void quit(TResult)\n * bool compareTokens(string a, string b, char separator=' ')\n * void compareRemainingLines(int lineNo=1)\n * void skip_ok()\n *\n */\n\n/* NOTE: This file contains testlib library for C++.\n *\n * Check, using testlib running format:\n * check.exe [ [-appes]],\n * If result file is specified it will contain results.\n *\n * Validator, using testlib running format: \n * validator.exe < input.txt,\n * It will return non-zero exit code and writes message to standard output.\n *\n * Generator, using testlib running format: \n * gen.exe [parameter-1] [parameter-2] [... paramerter-n]\n * You can write generated test(s) into standard output or into the file(s).\n *\n * Interactor, using testlib running format: \n * interactor.exe [ [ [-appes]]],\n * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],\n * can be judged by checker later), reads program output from ouf (mapped to stdin),\n * writes output to program via stdout (use cout, printf, etc).\n */\n\nconst char* latestFeatures[] = {\n \"Fixed stringstream repeated usage issue\",\n \"Fixed compilation in g++ (for std=c++03)\",\n \"Batch of println functions (support collections, iterator ranges)\",\n \"Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation\",\n \"Allow any whitespace in readInts-like functions for non-validators\",\n \"Ignore 4+ command line arguments ifdef EJUDGE\",\n \"Speed up of vtos\",\n \"Show line number in validators in case of incorrect format\",\n \"Truncate huge checker/validator/interactor message\",\n \"Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type\",\n \"Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type\",\n \"Fixed compilation in VS 2015+\",\n \"Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines\",\n \"Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals\",\n \"Introduced split/tokenize functions to separate string by given char\",\n \"Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters\",\n \"Supported --testOverviewLogFileName for validator: bounds hits + features\",\n \"Fixed UB (sequence points) in random_t\",\n \"POINTS_EXIT_CODE returned back to 7 (instead of 0)\",\n \"Removed disable buffers for interactive problems, because it works unexpectedly in wine\",\n \"InStream over string: constructor of InStream from base InStream to inherit policies and std::string\",\n \"Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \\\"[n=%d,m=%d]\\\", n, m)\",\n \"Fixed incorrect interval parsing in patterns\",\n \"Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)\",\n \"Introduced disableFinalizeGuard() to switch off finalization checkings\",\n \"Use join() functions to format a range of items as a single string (separated by spaces or other separators)\",\n \"Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors\",\n \"Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7\",\n \"Fixed bug with nan in stringToDouble\", \n \"Fixed issue around overloads for size_t on x64\", \n \"Added attribute 'points' to the XML output in case of result=_points\", \n \"Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14\", \n \"Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading\", \n \"Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()\", \n \"Manual buffer in InStreams, some IO speed improvements\", \n \"Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true\", \n \"Introduced guard against missed quitf() in checker or readEof() in validators\", \n \"Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers\", \n \"Supported registerInteraction(argc, argv)\", \n \"Print checker message to the stderr instead of stdout\", \n \"Supported TResult _points to output calculated score, use quitp(...) functions\", \n \"Fixed to be compilable on Mac\", \n \"PC_BASE_EXIT_CODE=50 in case of defined TESTSYS\",\n \"Fixed issues 19-21, added __attribute__ format printf\", \n \"Some bug fixes\", \n \"ouf.readInt(1, 100) and similar calls return WA\", \n \"Modified random_t to avoid integer overflow\", \n \"Truncated checker output [patch by Stepan Gatilov]\", \n \"Renamed class random -> class random_t\", \n \"Supported name parameter for read-and-validation methods, like readInt(1, 2, \\\"n\\\")\", \n \"Fixed bug in readDouble()\", \n \"Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()\", \n \"Supported \\\"partially correct\\\", example: quitf(_pc(13), \\\"result=%d\\\", result)\", \n \"Added shuffle(begin, end), use it instead of random_shuffle(begin, end)\", \n \"Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode\", \n \"Package extended with samples of generators and validators\", \n \"Written the documentation for classes and public methods in testlib.h\",\n \"Implemented random routine to support generators, use registerGen() to switch it on\",\n \"Implemented strict mode to validate tests, use registerValidation() to switch it on\",\n \"Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output\",\n \"Added InStream::readLong() and removed InStream::readLongint()\",\n \"Now no footer added to each report by default (use directive FOOTER to switch on)\",\n \"Now every checker has a name, use setName(const char* format, ...) to set it\",\n \"Now it is compatible with TTS (by Kittens Computing)\",\n \"Added \\'ensure(condition, message = \\\"\\\")\\' feature, it works like assert()\",\n \"Fixed compatibility with MS C++ 7.1\",\n \"Added footer with exit code information\",\n \"Added compatibility with EJUDGE (compile with EJUDGE directive)\",\n \"Added compatibility with Contester (compile with CONTESTER directive)\"\n };\n\n#define FOR_LINUX\n\n#ifdef _MSC_VER\n#define _CRT_SECURE_NO_DEPRECATE\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_NO_VA_START_VALIDATION\n#endif\n\n/* Overrides random() for Borland C++. */\n#define random __random_deprecated\n#include \n#include \n#include \n#include \n#undef random\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ || __CYGWIN__ )\n# if !defined(_MSC_VER) || _MSC_VER>1400\n# define NOMINMAX 1\n# include \n# else\n# define WORD unsigned short\n# include \n# endif\n# include \n# define ON_WINDOWS\n# if defined(_MSC_VER) && _MSC_VER>1400\n# pragma warning( disable : 4127 )\n# pragma warning( disable : 4146 )\n# pragma warning( disable : 4458 )\n# endif\n#else\n# define WORD unsigned short\n# include \n#endif\n\n#if defined(FOR_WINDOWS) && defined(FOR_LINUX)\n#error Only one target system is allowed\n#endif\n\n#ifndef LLONG_MIN\n#define LLONG_MIN (-9223372036854775807LL - 1)\n#endif\n\n#ifndef ULLONG_MAX\n#define ULLONG_MAX (18446744073709551615)\n#endif\n\n#define LF ((char)10)\n#define CR ((char)13)\n#define TAB ((char)9)\n#define SPACE ((char)' ')\n#define EOFC (255)\n\n#ifndef OK_EXIT_CODE\n# ifdef CONTESTER\n# define OK_EXIT_CODE 0xAC\n# else\n# define OK_EXIT_CODE 0\n# endif\n#endif\n\n#ifndef WA_EXIT_CODE\n# ifdef EJUDGE\n# define WA_EXIT_CODE 5\n# elif defined(CONTESTER)\n# define WA_EXIT_CODE 0xAB\n# else\n# define WA_EXIT_CODE 1\n# endif\n#endif\n\n#ifndef PE_EXIT_CODE\n# ifdef EJUDGE\n# define PE_EXIT_CODE 4\n# elif defined(CONTESTER)\n# define PE_EXIT_CODE 0xAA\n# else\n# define PE_EXIT_CODE 2\n# endif\n#endif\n\n#ifndef FAIL_EXIT_CODE\n# ifdef EJUDGE\n# define FAIL_EXIT_CODE 6\n# elif defined(CONTESTER)\n# define FAIL_EXIT_CODE 0xA3\n# else\n# define FAIL_EXIT_CODE 3\n# endif\n#endif\n\n#ifndef DIRT_EXIT_CODE\n# ifdef EJUDGE\n# define DIRT_EXIT_CODE 6\n# else\n# define DIRT_EXIT_CODE 4\n# endif\n#endif\n\n#ifndef POINTS_EXIT_CODE\n# define POINTS_EXIT_CODE 7\n#endif\n\n#ifndef UNEXPECTED_EOF_EXIT_CODE\n# define UNEXPECTED_EOF_EXIT_CODE 8\n#endif\n\n#ifndef SV_EXIT_CODE\n# define SV_EXIT_CODE 20\n#endif\n\n#ifndef PC_BASE_EXIT_CODE\n# ifdef TESTSYS\n# define PC_BASE_EXIT_CODE 50\n# else\n# define PC_BASE_EXIT_CODE 0\n# endif\n#endif\n\n#ifdef __GNUC__\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))\n#else\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]\n#endif\n\n#ifdef ON_WINDOWS\n#define I64 \"%I64d\"\n#define U64 \"%I64u\"\n#else\n#define I64 \"%lld\"\n#define U64 \"%llu\"\n#endif\n\n#ifdef _MSC_VER\n# define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n# define NORETURN __attribute__ ((noreturn))\n#else\n# define NORETURN\n#endif\n\n/**************** HaltListener material ****************/\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntypedef std::function HaltListener;\n#else\ntypedef void (*HaltListener)();\n#endif\n\nstd::vector __haltListeners;\n\ninline void registerHaltListener(HaltListener haltListener) {\n __haltListeners.push_back(haltListener);\n}\n\ninline void callHaltListeners() {\n // Removing and calling haltListeners in reverse order.\n while (!__haltListeners.empty()) {\n HaltListener haltListener = __haltListeners.back();\n __haltListeners.pop_back();\n haltListener();\n }\n}\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ninline void closeOnHalt(FILE* file) {\n registerHaltListener([file] { fclose(file); });\n}\ntemplate\ninline void closeOnHalt(F& f) {\n registerHaltListener([&f] { f.close(); });\n}\n#endif\n/*******************************************************/\n\nstatic char __testlib_format_buffer[16777216];\nstatic int __testlib_format_buffer_usage_count = 0;\n\n#define FMT_TO_RESULT(fmt, cstr, result) std::string result; \\\n if (__testlib_format_buffer_usage_count != 0) \\\n __testlib_fail(\"FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0\"); \\\n __testlib_format_buffer_usage_count++; \\\n va_list ap; \\\n va_start(ap, fmt); \\\n vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \\\n va_end(ap); \\\n __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \\\n result = std::string(__testlib_format_buffer); \\\n __testlib_format_buffer_usage_count--; \\\n\nconst long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;\n\nNORETURN static void __testlib_fail(const std::string& message);\n\ntemplate\nstatic inline T __testlib_abs(const T& x)\n{\n return x > 0 ? x : -x;\n}\n\ntemplate\nstatic inline T __testlib_min(const T& a, const T& b)\n{\n return a < b ? a : b;\n}\n\ntemplate\nstatic inline T __testlib_max(const T& a, const T& b)\n{\n return a > b ? a : b;\n}\n\nstatic bool __testlib_prelimIsNaN(double r)\n{\n volatile double ra = r;\n#ifndef __BORLANDC__\n return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);\n#else\n return std::_isnan(ra);\n#endif\n}\n\nstatic std::string removeDoubleTrailingZeroes(std::string value)\n{\n while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)\n value = value.substr(0, value.length() - 1);\n return value + '0';\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nstd::string format(const char* fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt, result);\n return result;\n}\n\nstd::string format(const std::string fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt.c_str(), result);\n return result;\n}\n\nstatic std::string __testlib_part(const std::string& s);\n\nstatic bool __testlib_isNaN(double r)\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n volatile double ra = r;\n long long llr1, llr2;\n std::memcpy((void*)&llr1, (void*)&ra, sizeof(double)); \n ra = -ra;\n std::memcpy((void*)&llr2, (void*)&ra, sizeof(double)); \n long long llnan = 0xFFF8000000000000LL;\n return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;\n}\n\nstatic double __testlib_nan()\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n#ifndef NAN\n long long llnan = 0xFFF8000000000000LL;\n double nan;\n std::memcpy(&nan, &llnan, sizeof(double));\n return nan;\n#else\n return NAN;\n#endif\n}\n\nstatic bool __testlib_isInfinite(double r)\n{\n volatile double ra = r;\n return (ra > 1E300 || ra < -1E300);\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)\n{\n if (__testlib_isNaN(expected))\n {\n return __testlib_isNaN(result);\n }\n else \n if (__testlib_isInfinite(expected))\n {\n if (expected > 0)\n {\n return result > 0 && __testlib_isInfinite(result);\n }\n else\n {\n return result < 0 && __testlib_isInfinite(result);\n }\n }\n else \n if (__testlib_isNaN(result) || __testlib_isInfinite(result))\n {\n return false;\n }\n else \n if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)\n {\n return true;\n }\n else\n {\n double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n return result + 1E-15 >= minv && result <= maxv + 1E-15;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline double doubleDelta(double expected, double result)\n{\n double absolute = __testlib_abs(result - expected);\n \n if (__testlib_abs(expected) > 1E-9)\n {\n double relative = __testlib_abs(absolute / expected);\n return __testlib_min(absolute, relative);\n }\n else\n return absolute;\n}\n\n#if !defined(_MSC_VER) || _MSC_VER<1900\n#ifndef _fileno\n#define _fileno(_stream) ((_stream)->_file)\n#endif\n#endif\n\n#ifndef O_BINARY\nstatic void __testlib_set_binary(\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\n std::FILE* file\n)\n#else\nstatic void __testlib_set_binary(std::FILE* file)\n#endif\n{\n#ifdef O_BINARY\n if (NULL != file)\n {\n#ifndef __BORLANDC__\n _setmode(_fileno(file), O_BINARY);\n#else\n setmode(fileno(file), O_BINARY);\n#endif\n }\n#endif\n}\n\n/*\n * Very simple regex-like pattern.\n * It used for two purposes: validation and generation.\n * \n * For example, pattern(\"[a-z]{1,5}\").next(rnd) will return\n * random string from lowercase latin letters with length \n * from 1 to 5. It is easier to call rnd.next(\"[a-z]{1,5}\") \n * for the same effect. \n * \n * Another samples:\n * \"mike|john\" will generate (match) \"mike\" or \"john\";\n * \"-?[1-9][0-9]{0,3}\" will generate (match) non-zero integers from -9999 to 9999;\n * \"id-([ac]|b{2})\" will generate (match) \"id-a\", \"id-bb\", \"id-c\";\n * \"[^0-9]*\" will match sequences (empty or non-empty) without digits, you can't \n * use it for generations.\n *\n * You can't use pattern for generation if it contains meta-symbol '*'. Also it\n * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].\n *\n * For matching very simple greedy algorithm is used. For example, pattern\n * \"[0-9]?1\" will not match \"1\", because of greedy nature of matching.\n * Alternations (meta-symbols \"|\") are processed with brute-force algorithm, so \n * do not use many alternations in one expression.\n *\n * If you want to use one expression many times it is better to compile it into\n * a single pattern like \"pattern p(\"[a-z]+\")\". Later you can use \n * \"p.matches(std::string s)\" or \"p.next(random_t& rd)\" to check matching or generate\n * new string by pattern.\n * \n * Simpler way to read token and check it for pattern matching is \"inf.readToken(\"[a-z]+\")\".\n */\nclass random_t;\n\nclass pattern\n{\npublic:\n /* Create pattern instance by string. */\n pattern(std::string s);\n /* Generate new string by pattern and given random_t. */\n std::string next(random_t& rnd) const;\n /* Checks if given string match the pattern. */\n bool matches(const std::string& s) const;\n /* Returns source string of the pattern. */\n std::string src() const;\nprivate:\n bool matches(const std::string& s, size_t pos) const;\n\n std::string s;\n std::vector children;\n std::vector chars;\n int from;\n int to;\n};\n\n/* \n * Use random_t instances to generate random values. It is preffered\n * way to use randoms instead of rand() function or self-written \n * randoms.\n *\n * Testlib defines global variable \"rnd\" of random_t class.\n * Use registerGen(argc, argv, 1) to setup random_t seed be command\n * line (to use latest random generator version).\n *\n * Random generates uniformly distributed values if another strategy is\n * not specified explicitly.\n */\nclass random_t\n{\nprivate:\n unsigned long long seed;\n static const unsigned long long multiplier;\n static const unsigned long long addend;\n static const unsigned long long mask;\n static const int lim;\n\n long long nextBits(int bits) \n {\n if (bits <= 48)\n {\n seed = (seed * multiplier + addend) & mask;\n return (long long)(seed >> (48 - bits));\n }\n else\n {\n if (bits > 63)\n __testlib_fail(\"random_t::nextBits(int bits): n must be less than 64\");\n\n int lowerBitCount = (random_t::version == 0 ? 31 : 32);\n \n long long left = (nextBits(31) << 32);\n long long right = nextBits(lowerBitCount);\n \n return left ^ right;\n }\n }\n\npublic:\n static int version;\n\n /* New random_t with fixed seed. */\n random_t()\n : seed(3905348978240129619LL)\n {\n }\n\n /* Sets seed by command line. */\n void setSeed(int argc, char* argv[])\n {\n random_t p;\n\n seed = 3905348978240129619LL;\n for (int i = 1; i < argc; i++)\n {\n std::size_t le = std::strlen(argv[i]);\n for (std::size_t j = 0; j < le; j++)\n seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;\n seed += multiplier / addend;\n }\n\n seed = seed & mask;\n }\n\n /* Sets seed by given value. */ \n void setSeed(long long _seed)\n {\n _seed = (_seed ^ multiplier) & mask;\n seed = _seed;\n }\n\n#ifndef __BORLANDC__\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(const std::string& ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#else\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(std::string ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#endif\n\n /* Random value in range [0, n-1]. */\n int next(int n)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(int n): n must be positive\");\n\n if ((n & -n) == n) // n is a power of 2\n return (int)((n * (long long)nextBits(31)) >> 31);\n\n const long long limit = INT_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(31);\n } while (bits >= limit);\n\n return int(bits % n);\n }\n\n /* Random value in range [0, n-1]. */\n unsigned int next(unsigned int n)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::next(unsigned int n): n must be less INT_MAX\");\n return (unsigned int)next(int(n));\n }\n\n /* Random value in range [0, n-1]. */\n long long next(long long n) \n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(long long n): n must be positive\");\n\n const long long limit = __TESTLIB_LONGLONG_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(63);\n } while (bits >= limit);\n\n return bits % n;\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long long next(unsigned long long n)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long long n): n must be less LONGLONG_MAX\");\n return (unsigned long long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n long next(long n)\n {\n return (long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long next(unsigned long n)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long n): n must be less LONG_MAX\");\n return (unsigned long)next((unsigned long long)(n));\n }\n\n /* Returns random value in range [from,to]. */\n int next(int from, int to)\n {\n return int(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n unsigned int next(unsigned int from, unsigned int to)\n {\n return (unsigned int)(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n long long next(long long from, long long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long long next(unsigned long long from, unsigned long long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n long next(long from, long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long next(unsigned long from, unsigned long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long from, unsigned long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Random double value in range [0, 1). */\n double next() \n {\n long long left = ((long long)(nextBits(26)) << 27);\n long long right = nextBits(27);\n return (double)(left + right) / (double)(1LL << 53);\n }\n\n /* Random double value in range [0, n). */\n double next(double n)\n {\n return n * next();\n }\n\n /* Random double value in range [from, to). */\n double next(double from, double to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(double from, double to): from can't not exceed to\");\n return next(to - from) + from;\n }\n\n /* Returns random element from container. */\n template \n typename Container::value_type any(const Container& c)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Container& c): c.size() must be positive\");\n return *(c.begin() + next(size));\n }\n\n /* Returns random element from iterator range. */\n template \n typename Iter::value_type any(const Iter& begin, const Iter& end)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end): range must have positive length\");\n return *(begin + next(size));\n }\n\n /* Random string value by given pattern (see pattern documentation). */\n#ifdef __GNUC__\n __attribute__ ((format (printf, 2, 3)))\n#endif\n std::string next(const char* format, ...)\n {\n FMT_TO_RESULT(format, format, ptrn);\n return next(ptrn);\n }\n\n /* \n * Weighted next. If type == 0 than it is usual \"next()\".\n *\n * If type = 1, than it returns \"max(next(), next())\"\n * (the number of \"max\" functions equals to \"type\").\n *\n * If type < 0, than \"max\" function replaces with \"min\".\n */\n int wnext(int n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(int n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n int result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));\n\n return int(n * p);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n long long wnext(long long n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(long long n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n long long result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(int type)\n {\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return p;\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(double n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(double n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return n * result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return n * p;\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned int wnext(unsigned int n, int type)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::wnext(unsigned int n, int type): n must be less INT_MAX\");\n return (unsigned int)wnext(int(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long long wnext(unsigned long long n, int type)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX\");\n\n return (unsigned long long)wnext((long long)(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n long wnext(long n, int type)\n {\n return (long)wnext((long long)(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long wnext(unsigned long n, int type)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long n, int type): n must be less LONG_MAX\");\n\n return (unsigned long)wnext((unsigned long long)(n), type);\n }\n\n /* Returns weighted random value in range [from, to]. */\n int wnext(int from, int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(int from, int to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n int wnext(unsigned int from, unsigned int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to\");\n return int(wnext(to - from + 1, type) + from);\n }\n \n /* Returns weighted random value in range [from, to]. */\n long long wnext(long long from, long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long long from, long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long long wnext(unsigned long long from, unsigned long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n long wnext(long from, long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long from, long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long wnext(unsigned long from, unsigned long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random double value in range [from, to). */\n double wnext(double from, double to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(double from, double to, int type): from can't not exceed to\");\n return wnext(to - from, type) + from;\n }\n\n /* Returns weighted random element from container. */\n template \n typename Container::value_type wany(const Container& c, int type)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::wany(const Container& c, int type): c.size() must be positive\");\n return *(c.begin() + wnext(size, type));\n }\n\n /* Returns weighted random element from iterator range. */\n template \n typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length\");\n return *(begin + wnext(size, type));\n }\n\n template\n std::vector perm(T size, E first)\n {\n if (size <= 0)\n __testlib_fail(\"random_t::perm(T size, E first = 0): size must be positive\");\n std::vector p(size);\n for (T i = 0; i < size; i++)\n p[i] = first + i;\n if (size > 1)\n for (T i = 1; i < size; i++)\n std::swap(p[i], p[next(i + 1)]);\n return p;\n }\n\n template\n std::vector perm(T size)\n {\n return perm(size, T(0));\n }\n};\n\nconst int random_t::lim = 25;\nconst unsigned long long random_t::multiplier = 0x5DEECE66DLL;\nconst unsigned long long random_t::addend = 0xBLL;\nconst unsigned long long random_t::mask = (1LL << 48) - 1;\nint random_t::version = -1;\n\n/* Pattern implementation */\nbool pattern::matches(const std::string& s) const\n{\n return matches(s, 0);\n}\n\nstatic bool __pattern_isSlash(const std::string& s, size_t pos)\n{\n return s[pos] == '\\\\';\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)\n{\n if (pos >= s.length())\n return false;\n\n int slashes = 0;\n\n int before = int(pos) - 1;\n while (before >= 0 && s[before] == '\\\\')\n before--, slashes++;\n\n return slashes % 2 == 0 && s[pos] == value;\n}\n\nstatic char __pattern_getChar(const std::string& s, size_t& pos)\n{\n if (__pattern_isSlash(s, pos))\n pos += 2;\n else\n pos++;\n\n return s[pos - 1];\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector chars)\n{\n int result = 0;\n\n while (pos < s.length())\n {\n char c = s[pos++];\n if (!std::binary_search(chars.begin(), chars.end(), c))\n break;\n else\n result++;\n }\n\n return result;\n}\n\nstd::string pattern::src() const\n{\n return s;\n}\n\nbool pattern::matches(const std::string& s, size_t pos) const\n{\n std::string result;\n\n if (to > 0)\n {\n int size = __pattern_greedyMatch(s, pos, chars);\n if (size < from)\n return false;\n if (size > to)\n size = to;\n pos += size;\n }\n\n if (children.size() > 0)\n {\n for (size_t child = 0; child < children.size(); child++)\n if (children[child].matches(s, pos))\n return true;\n return false;\n }\n else\n return pos == s.length();\n}\n\nstd::string pattern::next(random_t& rnd) const\n{\n std::string result;\n result.reserve(20);\n\n if (to == INT_MAX)\n __testlib_fail(\"pattern::next(random_t& rnd): can't process character '*' for generation\");\n\n if (to > 0)\n {\n int count = rnd.next(to - from + 1) + from;\n for (int i = 0; i < count; i++)\n result += chars[rnd.next(int(chars.size()))];\n }\n\n if (children.size() > 0)\n {\n int child = rnd.next(int(children.size()));\n result += children[child].next(rnd);\n }\n\n return result;\n}\n\nstatic void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)\n{\n if (pos >= s.length())\n {\n from = to = 1;\n return;\n }\n \n if (__pattern_isCommandChar(s, pos, '{'))\n {\n std::vector parts;\n std::string part;\n\n pos++;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))\n {\n if (__pattern_isCommandChar(s, pos, ','))\n parts.push_back(part), part = \"\", pos++;\n else\n part += __pattern_getChar(s, pos);\n }\n\n if (part != \"\")\n parts.push_back(part);\n\n if (!__pattern_isCommandChar(s, pos, '}'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (parts.size() < 1 || parts.size() > 2)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector numbers;\n\n for (size_t i = 0; i < parts.size(); i++)\n {\n if (parts[i].length() == 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n int number;\n if (std::sscanf(parts[i].c_str(), \"%d\", &number) != 1)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n numbers.push_back(number);\n }\n\n if (numbers.size() == 1)\n from = to = numbers[0];\n else\n from = numbers[0], to = numbers[1];\n\n if (from > to)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n }\n else\n {\n if (__pattern_isCommandChar(s, pos, '?'))\n {\n from = 0, to = 1, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '*'))\n {\n from = 0, to = INT_MAX, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '+'))\n {\n from = 1, to = INT_MAX, pos++;\n return;\n }\n \n from = to = 1;\n }\n}\n\nstatic std::vector __pattern_scanCharSet(const std::string& s, size_t& pos)\n{\n if (pos >= s.length())\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector result;\n\n if (__pattern_isCommandChar(s, pos, '['))\n {\n pos++;\n bool negative = __pattern_isCommandChar(s, pos, '^');\n\n char prev = 0;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))\n {\n if (__pattern_isCommandChar(s, pos, '-') && prev != 0)\n {\n pos++;\n\n if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']'))\n {\n result.push_back(prev);\n prev = '-';\n continue;\n }\n\n char next = __pattern_getChar(s, pos);\n if (prev > next)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n for (char c = prev; c != next; c++)\n result.push_back(c);\n result.push_back(next);\n\n prev = 0;\n }\n else\n {\n if (prev != 0)\n result.push_back(prev);\n prev = __pattern_getChar(s, pos);\n }\n }\n\n if (prev != 0)\n result.push_back(prev);\n\n if (!__pattern_isCommandChar(s, pos, ']'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (negative)\n {\n std::sort(result.begin(), result.end());\n std::vector actuals;\n for (int code = 0; code < 255; code++)\n {\n char c = char(code);\n if (!std::binary_search(result.begin(), result.end(), c))\n actuals.push_back(c);\n }\n result = actuals;\n }\n\n std::sort(result.begin(), result.end());\n }\n else\n result.push_back(__pattern_getChar(s, pos));\n\n return result;\n}\n\npattern::pattern(std::string s): s(s), from(0), to(0)\n{\n std::string t;\n for (size_t i = 0; i < s.length(); i++)\n if (!__pattern_isCommandChar(s, i, ' '))\n t += s[i];\n s = t;\n\n int opened = 0;\n int firstClose = -1;\n std::vector seps;\n\n for (size_t i = 0; i < s.length(); i++)\n {\n if (__pattern_isCommandChar(s, i, '('))\n {\n opened++;\n continue;\n }\n\n if (__pattern_isCommandChar(s, i, ')'))\n {\n opened--;\n if (opened == 0 && firstClose == -1)\n firstClose = int(i);\n continue;\n }\n \n if (opened < 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (__pattern_isCommandChar(s, i, '|') && opened == 0)\n seps.push_back(int(i));\n }\n\n if (opened != 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (seps.size() == 0 && firstClose + 1 == (int)s.length() \n && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))\n {\n children.push_back(pattern(s.substr(1, s.length() - 2)));\n }\n else\n {\n if (seps.size() > 0)\n {\n seps.push_back(int(s.length()));\n int last = 0;\n\n for (size_t i = 0; i < seps.size(); i++)\n {\n children.push_back(pattern(s.substr(last, seps[i] - last)));\n last = seps[i] + 1;\n }\n }\n else\n {\n size_t pos = 0;\n chars = __pattern_scanCharSet(s, pos);\n __pattern_scanCounts(s, pos, from, to);\n if (pos < s.length())\n children.push_back(pattern(s.substr(pos)));\n }\n }\n}\n/* End of pattern implementation */\n\ntemplate \ninline bool isEof(C c)\n{\n return c == EOFC;\n}\n\ntemplate \ninline bool isEoln(C c)\n{\n return (c == LF || c == CR);\n}\n\ntemplate\ninline bool isBlanks(C c)\n{\n return (c == LF || c == CR || c == SPACE || c == TAB);\n}\n\nenum TMode\n{\n _input, _output, _answer\n};\n\n/* Outcomes 6-15 are reserved for future use. */\nenum TResult\n{\n _ok = 0,\n _wa = 1,\n _pe = 2,\n _fail = 3,\n _dirt = 4,\n _points = 5,\n _unexpected_eof = 8,\n _sv = 10,\n _partially = 16\n};\n\nenum TTestlibMode\n{\n _unknown, _checker, _validator, _generator, _interactor\n};\n\n#define _pc(exitCode) (TResult(_partially + (exitCode)))\n\n/* Outcomes 6-15 are reserved for future use. */\nconst std::string outcomes[] = {\n \"accepted\",\n \"wrong-answer\",\n \"presentation-error\",\n \"fail\",\n \"fail\",\n#ifndef PCMS2\n \"points\",\n#else\n \"relative-scoring\",\n#endif\n \"reserved\",\n \"reserved\",\n \"unexpected-eof\",\n \"reserved\",\n \"security-violation\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"partially-correct\"\n};\n\nclass InputStreamReader\n{\npublic:\n virtual int curChar() = 0; \n virtual int nextChar() = 0; \n virtual void skipChar() = 0;\n virtual void unreadChar(int c) = 0;\n virtual std::string getName() = 0;\n virtual bool eof() = 0;\n virtual void close() = 0;\n virtual int getLine() = 0;\n virtual ~InputStreamReader() = 0;\n};\n\nInputStreamReader::~InputStreamReader()\n{\n // No operations.\n}\n\nclass StringInputStreamReader: public InputStreamReader\n{\nprivate:\n std::string s;\n size_t pos;\n\npublic:\n StringInputStreamReader(const std::string& content): s(content), pos(0)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (pos >= s.length())\n return EOFC;\n else\n return s[pos];\n }\n\n int nextChar()\n {\n if (pos >= s.length())\n {\n pos++;\n return EOFC;\n }\n else\n return s[pos++];\n }\n\n void skipChar()\n {\n pos++;\n }\n\n void unreadChar(int c)\n { \n if (pos == 0)\n __testlib_fail(\"FileFileInputStreamReader::unreadChar(int): pos == 0.\");\n pos--;\n if (pos < s.length())\n s[pos] = char(c);\n }\n\n std::string getName()\n {\n return __testlib_part(s);\n }\n\n int getLine()\n {\n return -1;\n }\n\n bool eof()\n {\n return pos >= s.length();\n }\n\n void close()\n {\n // No operations.\n }\n};\n\nclass FileInputStreamReader: public InputStreamReader\n{\nprivate:\n std::FILE* file;\n std::string name;\n int line;\n std::vector undoChars;\n\n inline int postprocessGetc(int getcResult)\n {\n if (getcResult != EOF)\n return getcResult;\n else\n return EOFC;\n }\n\n int getc(FILE* file)\n {\n int c;\n if (undoChars.empty())\n c = ::getc(file);\n else\n {\n c = undoChars.back();\n undoChars.pop_back();\n }\n\n if (c == LF)\n line++;\n return c;\n }\n\n int ungetc(int c/*, FILE* file*/)\n {\n if (c == LF)\n line--;\n undoChars.push_back(c);\n return c;\n }\n\npublic:\n FileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (feof(file))\n return EOFC;\n else\n {\n int c = getc(file);\n ungetc(c/*, file*/);\n return postprocessGetc(c);\n }\n }\n\n int nextChar()\n {\n if (feof(file))\n return EOFC;\n else\n return postprocessGetc(getc(file));\n }\n\n void skipChar()\n {\n getc(file);\n }\n\n void unreadChar(int c)\n { \n ungetc(c/*, file*/);\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n\n bool eof()\n {\n if (NULL == file || feof(file))\n return true;\n else\n {\n int c = nextChar();\n if (c == EOFC || (c == EOF && feof(file)))\n return true;\n unreadChar(c);\n return false;\n }\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nclass BufferedFileInputStreamReader: public InputStreamReader\n{\nprivate:\n static const size_t BUFFER_SIZE;\n static const size_t MAX_UNREAD_COUNT; \n \n std::FILE* file;\n char* buffer;\n bool* isEof;\n int bufferPos;\n size_t bufferSize;\n\n std::string name;\n int line;\n\n bool refill()\n {\n if (NULL == file)\n __testlib_fail(\"BufferedFileInputStreamReader: file == NULL (\" + getName() + \")\");\n\n if (bufferPos >= int(bufferSize))\n {\n size_t readSize = fread(\n buffer + MAX_UNREAD_COUNT,\n 1,\n BUFFER_SIZE - MAX_UNREAD_COUNT,\n file\n );\n\n if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT\n && ferror(file))\n __testlib_fail(\"BufferedFileInputStreamReader: unable to read (\" + getName() + \")\");\n\n bufferSize = MAX_UNREAD_COUNT + readSize;\n bufferPos = int(MAX_UNREAD_COUNT);\n std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);\n\n return readSize > 0;\n }\n else\n return true;\n }\n\n char increment()\n {\n char c;\n if ((c = buffer[bufferPos++]) == LF)\n line++;\n return c;\n }\n\npublic:\n BufferedFileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n buffer = new char[BUFFER_SIZE];\n isEof = new bool[BUFFER_SIZE];\n bufferSize = MAX_UNREAD_COUNT;\n bufferPos = int(MAX_UNREAD_COUNT);\n }\n\n ~BufferedFileInputStreamReader()\n {\n if (NULL != buffer)\n {\n delete[] buffer;\n buffer = NULL;\n }\n if (NULL != isEof)\n {\n delete[] isEof;\n isEof = NULL;\n }\n }\n\n int curChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : buffer[bufferPos];\n }\n\n int nextChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : increment();\n }\n\n void skipChar()\n {\n increment();\n }\n\n void unreadChar(int c)\n { \n bufferPos--;\n if (bufferPos < 0)\n __testlib_fail(\"BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0\");\n isEof[bufferPos] = (c == EOFC);\n buffer[bufferPos] = char(c);\n if (c == LF)\n line--;\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n \n bool eof()\n {\n return !refill() || EOFC == curChar();\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nconst size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;\nconst size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2; \n\n/*\n * Streams to be used for reading data in checkers or validators.\n * Each read*() method moves pointer to the next character after the\n * read value.\n */\nstruct InStream\n{\n /* Do not use them. */\n InStream();\n ~InStream();\n\n /* Wrap std::string with InStream. */\n InStream(const InStream& baseStream, std::string content);\n\n InputStreamReader* reader;\n int lastLine;\n\n std::string name;\n TMode mode;\n bool opened;\n bool stdfile;\n bool strict;\n\n int wordReserveSize;\n std::string _tmpReadToken;\n\n int readManyIteration;\n size_t maxFileSize;\n size_t maxTokenLength;\n size_t maxMessageLength;\n\n void init(std::string fileName, TMode mode);\n void init(std::FILE* f, TMode mode);\n\n /* Moves stream pointer to the first non-white-space character or EOF. */ \n void skipBlanks();\n \n /* Returns current character in the stream. Doesn't remove it from stream. */\n char curChar();\n /* Moves stream pointer one character forward. */\n void skipChar();\n /* Returns current character and moves pointer one character forward. */\n char nextChar();\n \n /* Returns current character and moves pointer one character forward. */\n char readChar();\n /* As \"readChar()\" but ensures that the result is equal to given parameter. */\n char readChar(char c);\n /* As \"readChar()\" but ensures that the result is equal to the space (code=32). */\n char readSpace();\n /* Puts back the character into the stream. */\n void unreadChar(char c);\n\n /* Reopens stream, you should not use it. */\n void reset(std::FILE* file = NULL);\n /* Checks that current position is EOF. If not it doesn't move stream pointer. */\n bool eof();\n /* Moves pointer to the first non-white-space character and calls \"eof()\". */\n bool seekEof();\n\n /* \n * Checks that current position contains EOLN. \n * If not it doesn't move stream pointer. \n * In strict mode expects \"#13#10\" for windows or \"#10\" for other platforms.\n */\n bool eoln();\n /* Moves pointer to the first non-space and non-tab character and calls \"eoln()\". */\n bool seekEoln();\n\n /* Moves stream pointer to the first character of the next line (if exists). */\n void nextLine();\n\n /* \n * Reads new token. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n std::string readWord();\n /* The same as \"readWord()\", it is preffered to use \"readToken()\". */\n std::string readToken();\n /* The same as \"readWord()\", but ensures that token matches to given pattern. */\n std::string readWord(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readWord(const pattern& p, const std::string& variableName = \"\");\n std::vector readWords(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readWords(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n /* The same as \"readToken()\", but ensures that token matches to given pattern. */\n std::string readToken(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readToken(const pattern& p, const std::string& variableName = \"\");\n std::vector readTokens(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readTokens(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n\n void readWordTo(std::string& result);\n void readWordTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n void readTokenTo(std::string& result);\n void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads new long long value. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n long long readLong();\n unsigned long long readUnsignedLong();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInteger();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInt();\n\n /* As \"readLong()\" but ensures that value in the range [minv,maxv]. */\n long long readLong(long long minv, long long maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of long longs. */\n std::vector readLongs(int size, long long minv, long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n unsigned long long readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* As \"readInteger()\" but ensures that value in the range [minv,maxv]. */\n int readInteger(int minv, int maxv, const std::string& variableName = \"\");\n /* As \"readInt()\" but ensures that value in the range [minv,maxv]. */\n int readInt(int minv, int maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of integers. */\n std::vector readIntegers(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* Reads space-separated sequence of integers. */\n std::vector readInts(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readReal();\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readDouble();\n \n /* As \"readReal()\" but ensures that value in the range [minv,maxv]. */\n double readReal(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readReals(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* As \"readDouble()\" but ensures that value in the range [minv,maxv]. */\n double readDouble(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readDoubles(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n \n /* \n * As \"readReal()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * As \"readDouble()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n \n /* As readLine(). */\n std::string readString();\n /* Read many lines. */\n std::vector readStrings(int size, int indexBase = 1);\n /* See readLine(). */\n void readStringTo(std::string& result);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readStrings(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readStrings(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads line from the current position to EOLN or EOF. Moves stream pointer to \n * the first character of the new line (if possible). \n */\n std::string readLine();\n /* Read many lines. */\n std::vector readLines(int size, int indexBase = 1);\n /* See readLine(). */\n void readLineTo(std::string& result);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readLines(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readLines(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* Reads EOLN or fails. Use it in validators. Calls \"eoln()\" method internally. */\n void readEoln();\n /* Reads EOF or fails. Use it in validators. Calls \"eof()\" method internally. */\n void readEof();\n\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quit(TResult result, const char* msg);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quitf(TResult result, const char* msg, ...);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quits(TResult result, std::string msg);\n\n /* \n * Checks condition and aborts a program if codition is false.\n * Returns _wa for ouf and _fail on any other streams.\n */\n #ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n #endif\n void ensuref(bool cond, const char* format, ...);\n void __testlib_ensure(bool cond, std::string message);\n\n void close();\n\n const static int NO_INDEX = INT_MAX;\n\n const static WORD LightGray = 0x07; \n const static WORD LightRed = 0x0c; \n const static WORD LightCyan = 0x0b; \n const static WORD LightGreen = 0x0a; \n const static WORD LightYellow = 0x0e; \n const static WORD LightMagenta = 0x0d; \n\n static void textColor(WORD color);\n static void quitscr(WORD color, const char* msg);\n static void quitscrS(WORD color, std::string msg);\n void xmlSafeWrite(std::FILE * file, const char* msg);\n\n void readSecret(std::string secret);\n void readGraderResult();\n\nprivate:\n InStream(const InStream&);\n InStream& operator =(const InStream&);\n};\n\nInStream inf;\nInStream ouf;\nInStream ans;\nbool appesMode;\nstd::string resultName;\nstd::string checkerName = \"untitled checker\";\nrandom_t rnd;\nTTestlibMode testlibMode = _unknown;\ndouble __testlib_points = std::numeric_limits::infinity();\n\nstruct ValidatorBoundsHit\n{\n static const double EPS;\n bool minHit;\n bool maxHit;\n\n ValidatorBoundsHit(bool minHit = false, bool maxHit = false): minHit(minHit), maxHit(maxHit)\n {\n };\n\n ValidatorBoundsHit merge(const ValidatorBoundsHit& validatorBoundsHit)\n {\n return ValidatorBoundsHit(\n __testlib_max(minHit, validatorBoundsHit.minHit),\n __testlib_max(maxHit, validatorBoundsHit.maxHit)\n );\n }\n};\n\nconst double ValidatorBoundsHit::EPS = 1E-12;\n\nclass Validator\n{\nprivate:\n std::string _testset;\n std::string _group;\n std::string _testOverviewLogFileName;\n std::map _boundsHitByVariableName;\n std::set _features;\n std::set _hitFeatures;\n\n bool isVariableNameBoundsAnalyzable(const std::string& variableName)\n {\n for (size_t i = 0; i < variableName.length(); i++)\n if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')\n return false;\n return true;\n }\n\n bool isFeatureNameAnalyzable(const std::string& featureName)\n {\n for (size_t i = 0; i < featureName.length(); i++)\n if (featureName[i] < ' ')\n return false;\n return true;\n }\npublic:\n Validator(): _testset(\"tests\"), _group()\n {\n }\n\n std::string testset() const\n {\n return _testset;\n }\n \n std::string group() const\n {\n return _group;\n }\n\n std::string testOverviewLogFileName() const\n {\n return _testOverviewLogFileName;\n }\n \n void setTestset(const char* const testset)\n {\n _testset = testset;\n }\n\n void setGroup(const char* const group)\n {\n _group = group;\n }\n\n void setTestOverviewLogFileName(const char* const testOverviewLogFileName)\n {\n _testOverviewLogFileName = testOverviewLogFileName;\n }\n\n void addBoundsHit(const std::string& variableName, ValidatorBoundsHit boundsHit)\n {\n if (isVariableNameBoundsAnalyzable(variableName))\n {\n _boundsHitByVariableName[variableName]\n = boundsHit.merge(_boundsHitByVariableName[variableName]);\n }\n }\n\n std::string getBoundsHitLog()\n {\n std::string result;\n for (std::map::iterator i = _boundsHitByVariableName.begin();\n i != _boundsHitByVariableName.end();\n i++)\n {\n result += \"\\\"\" + i->first + \"\\\":\";\n if (i->second.minHit)\n result += \" min-value-hit\";\n if (i->second.maxHit)\n result += \" max-value-hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n std::string getFeaturesLog()\n {\n std::string result;\n for (std::set::iterator i = _features.begin();\n i != _features.end();\n i++)\n {\n result += \"feature \\\"\" + *i + \"\\\":\";\n if (_hitFeatures.count(*i))\n result += \" hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n void writeTestOverviewLog()\n {\n if (!_testOverviewLogFileName.empty())\n {\n std::string fileName(_testOverviewLogFileName);\n _testOverviewLogFileName = \"\";\n FILE* testOverviewLogFile = fopen(fileName.c_str(), \"w\");\n if (NULL == testOverviewLogFile)\n __testlib_fail(\"Validator::writeTestOverviewLog: can't test overview log to (\" + fileName + \")\");\n fprintf(testOverviewLogFile, \"%s%s\", getBoundsHitLog().c_str(), getFeaturesLog().c_str());\n if (fclose(testOverviewLogFile))\n __testlib_fail(\"Validator::writeTestOverviewLog: can't close test overview log file (\" + fileName + \")\");\n }\n }\n\n void addFeature(const std::string& feature)\n {\n if (_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" registered twice.\");\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n _features.insert(feature);\n }\n\n void feature(const std::string& feature)\n {\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n if (!_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" didn't registered via addFeature(feature).\");\n\n _hitFeatures.insert(feature);\n }\n} validator;\n\nstruct TestlibFinalizeGuard\n{\n static bool alive;\n int quitCount, readEofCount;\n\n TestlibFinalizeGuard() : quitCount(0), readEofCount(0)\n {\n // No operations.\n }\n\n ~TestlibFinalizeGuard()\n {\n bool _alive = alive;\n alive = false;\n\n if (_alive)\n {\n if (testlibMode == _checker && quitCount == 0)\n __testlib_fail(\"Checker must end with quit or quitf call.\");\n\n if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)\n __testlib_fail(\"Validator must end with readEof call.\");\n }\n\n validator.writeTestOverviewLog();\n }\n};\n\nbool TestlibFinalizeGuard::alive = true;\nTestlibFinalizeGuard testlibFinalizeGuard;\n\n/*\n * Call it to disable checks on finalization.\n */\nvoid disableFinalizeGuard()\n{\n TestlibFinalizeGuard::alive = false;\n}\n\n/* Interactor streams.\n */\nstd::fstream tout;\n\n/* implementation\n */\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate\nstatic std::string vtos(const T& t, std::true_type)\n{ \n if (t == 0)\n return \"0\";\n else\n {\n T n(t);\n bool negative = n < 0;\n std::string s;\n while (n != 0) {\n T digit = n % 10;\n if (digit < 0)\n digit = -digit;\n s += char('0' + digit);\n n /= 10;\n }\n std::reverse(s.begin(), s.end());\n return negative ? \"-\" + s : s;\n }\n}\n\ntemplate\nstatic std::string vtos(const T& t, std::false_type)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n\ntemplate \nstatic std::string vtos(const T& t)\n{\n return vtos(t, std::is_integral());\n}\n#else\ntemplate\nstatic std::string vtos(const T& t)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n#endif\n\ntemplate \nstatic std::string toString(const T& t)\n{\n return vtos(t);\n}\n\nInStream::InStream()\n{\n reader = NULL;\n lastLine = -1;\n name = \"\";\n mode = _input;\n strict = false;\n stdfile = false;\n wordReserveSize = 4;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::InStream(const InStream& baseStream, std::string content)\n{\n reader = new StringInputStreamReader(content);\n lastLine = -1;\n opened = true;\n strict = baseStream.strict;\n mode = baseStream.mode;\n name = \"based on \" + baseStream.name;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::~InStream()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\nint resultExitCode(TResult r)\n{\n if (testlibMode == _checker)\n return 0;//CMS Checkers should always finish with zero exit code.\n if (r == _ok)\n return OK_EXIT_CODE;\n if (r == _wa)\n return WA_EXIT_CODE;\n if (r == _pe)\n return PE_EXIT_CODE;\n if (r == _fail)\n return FAIL_EXIT_CODE;\n if (r == _dirt)\n return DIRT_EXIT_CODE;\n if (r == _points)\n return POINTS_EXIT_CODE;\n if (r == _unexpected_eof)\n#ifdef ENABLE_UNEXPECTED_EOF\n return UNEXPECTED_EOF_EXIT_CODE;\n#else\n return PE_EXIT_CODE;\n#endif\n if (r == _sv)\n return SV_EXIT_CODE;\n if (r >= _partially)\n return PC_BASE_EXIT_CODE + (r - _partially);\n return FAIL_EXIT_CODE;\n}\n\nvoid InStream::textColor(\n#if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)) && defined(__GNUC__)\n __attribute__((unused)) \n#endif\n WORD color\n)\n{\n#if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)\n HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(handle, color);\n#endif\n#if !defined(ON_WINDOWS) && defined(__GNUC__)\n if (isatty(2))\n {\n switch (color)\n {\n case LightRed:\n fprintf(stderr, \"\\033[1;31m\");\n break;\n case LightCyan:\n fprintf(stderr, \"\\033[1;36m\");\n break;\n case LightGreen:\n fprintf(stderr, \"\\033[1;32m\");\n break;\n case LightYellow:\n fprintf(stderr, \"\\033[1;33m\");\n break;\n case LightMagenta:\n fprintf(stderr, \"\\033[1;35m\");\n break;\n case LightGray:\n default:\n fprintf(stderr, \"\\033[0m\");\n }\n }\n#endif\n}\n\nNORETURN void halt(int exitCode)\n{\n callHaltListeners();\n#ifdef FOOTER\n InStream::textColor(InStream::LightGray);\n std::fprintf(stderr, \"Checker: \\\"%s\\\"\\n\", checkerName.c_str());\n std::fprintf(stderr, \"Exit code: %d\\n\", exitCode);\n InStream::textColor(InStream::LightGray);\n#endif\n std::exit(exitCode);\n}\n\nstatic bool __testlib_shouldCheckDirt(TResult result)\n{\n return result == _ok || result == _points || result >= _partially;\n}\n\nNORETURN void InStream::quit(TResult result, const char* msg)\n{\n if (TestlibFinalizeGuard::alive)\n testlibFinalizeGuard.quitCount++;\n\n // You can change maxMessageLength.\n // Example: 'inf.maxMessageLength = 1024 * 1024;'.\n if (strlen(msg) > maxMessageLength)\n {\n std::string message(msg);\n std::string warn = \"message length exceeds \" + vtos(maxMessageLength)\n + \", the message is truncated: \";\n msg = (warn + message.substr(0, maxMessageLength - warn.length())).c_str();\n }\n\n#ifndef ENABLE_UNEXPECTED_EOF\n if (result == _unexpected_eof)\n result = _pe;\n#endif\n\n if (mode != _output && result != _fail)\n {\n if (mode == _input && testlibMode == _validator && lastLine != -1)\n quits(_fail, std::string(msg) + \" (\" + name + \", line \" + vtos(lastLine) + \")\");\n else\n quits(_fail, std::string(msg) + \" (\" + name + \")\");\n }\n\n std::FILE * resultFile;\n std::string errorName;\n \n if (__testlib_shouldCheckDirt(result))\n {\n if (testlibMode != _interactor && !ouf.seekEof())\n quit(_dirt, \"Extra information in the output file\");\n }\n\n int pctype = result - _partially;\n bool isPartial = false;\n\n if (testlibMode == _checker) {\n WORD color;\n std::string pointsStr = \"0\";\n switch (result)\n {\n case _ok:\n pointsStr = format(\"%d\", 1);\n color = LightGreen;\n errorName = \"Correct\";\n break;\n case _wa:\n case _pe:\n case _dirt:\n case _unexpected_eof:\n color = LightRed;\n errorName = \"Wrong Answer\";\n break;\n case _fail:\n color = LightMagenta;\n errorName = \"Judge Failure; Contact staff!\";\n break;\n case _sv:\n color = LightMagenta;\n errorName = \"Security Violation\";\n break;\n case _points:\n if (__testlib_points < 1e-5)\n pointsStr = \"0.00001\";//prevent zero scores in CMS as zero is considered wrong\n else if (__testlib_points < 0.0001)\n pointsStr = format(\"%lf\", __testlib_points);//prevent rounding the numbers below 0.0001\n else\n pointsStr = format(\"%.4lf\", __testlib_points);\n color = LightYellow;\n errorName = \"Partially Correct\";\n break;\n default:\n if (result >= _partially)\n quit(_fail, \"testlib partially mode not supported\");\n else\n quit(_fail, \"What is the code ??? \");\n } \n std::fprintf(stdout, \"%s\\n\", pointsStr.c_str());\n quitscrS(color, errorName);\n std::fprintf(stderr, \"\\n\");\n } else {\n switch (result)\n {\n case _ok:\n errorName = \"ok \";\n quitscrS(LightGreen, errorName);\n break;\n case _wa:\n errorName = \"wrong answer \";\n quitscrS(LightRed, errorName);\n break;\n case _pe:\n errorName = \"wrong output format \";\n quitscrS(LightRed, errorName);\n break;\n case _fail:\n errorName = \"FAIL \";\n quitscrS(LightRed, errorName);\n break;\n case _dirt:\n errorName = \"wrong output format \";\n quitscrS(LightCyan, errorName);\n result = _pe;\n break;\n case _points:\n errorName = \"points \";\n quitscrS(LightYellow, errorName);\n break;\n case _unexpected_eof:\n errorName = \"unexpected eof \";\n quitscrS(LightCyan, errorName);\n break;\n default:\n if (result >= _partially)\n {\n errorName = format(\"partially correct (%d) \", pctype);\n isPartial = true;\n quitscrS(LightYellow, errorName);\n }\n else\n quit(_fail, \"What is the code ??? \");\n }\n }\n\n if (resultName != \"\")\n {\n resultFile = std::fopen(resultName.c_str(), \"w\");\n if (resultFile == NULL)\n quit(_fail, \"Can not write to the result file\");\n if (appesMode)\n {\n std::fprintf(resultFile, \"\");\n if (isPartial)\n std::fprintf(resultFile, \"\", outcomes[(int)_partially].c_str(), pctype);\n else\n {\n if (result != _points)\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str());\n else\n {\n if (__testlib_points == std::numeric_limits::infinity())\n quit(_fail, \"Expected points, but infinity found\");\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", __testlib_points));\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str(), stringPoints.c_str());\n }\n }\n xmlSafeWrite(resultFile, msg);\n std::fprintf(resultFile, \"\\n\");\n }\n else\n std::fprintf(resultFile, \"%s\", msg);\n if (NULL == resultFile || fclose(resultFile) != 0)\n quit(_fail, \"Can not write to the result file\");\n }\n\n quitscr(LightGray, msg);\n std::fprintf(stderr, \"\\n\");\n\n inf.close();\n ouf.close();\n ans.close();\n if (tout.is_open())\n tout.close();\n\n textColor(LightGray);\n\n if (resultName != \"\")\n std::fprintf(stderr, \"See file to check exit message\\n\");\n\n halt(resultExitCode(result));\n}\n\n#ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n#endif\nNORETURN void InStream::quitf(TResult result, const char* msg, ...)\n{\n FMT_TO_RESULT(msg, msg, message);\n InStream::quit(result, message.c_str());\n}\n\nNORETURN void InStream::quits(TResult result, std::string msg)\n{\n InStream::quit(result, msg.c_str());\n}\n\nvoid InStream::xmlSafeWrite(std::FILE * file, const char* msg)\n{\n size_t lmsg = strlen(msg);\n for (size_t i = 0; i < lmsg; i++)\n {\n if (msg[i] == '&')\n {\n std::fprintf(file, \"%s\", \"&\");\n continue;\n }\n if (msg[i] == '<')\n {\n std::fprintf(file, \"%s\", \"<\");\n continue;\n }\n if (msg[i] == '>')\n {\n std::fprintf(file, \"%s\", \">\");\n continue;\n }\n if (msg[i] == '\"')\n {\n std::fprintf(file, \"%s\", \""\");\n continue;\n }\n if (0 <= msg[i] && msg[i] <= 31)\n {\n std::fprintf(file, \"%c\", '.');\n continue;\n }\n std::fprintf(file, \"%c\", msg[i]);\n }\n}\n\nvoid InStream::quitscrS(WORD color, std::string msg)\n{\n quitscr(color, msg.c_str());\n}\n\nvoid InStream::quitscr(WORD color, const char* msg)\n{\n if (resultName == \"\")\n {\n textColor(color);\n std::fprintf(stderr, \"%s\", msg);\n textColor(LightGray);\n }\n}\n\nvoid InStream::reset(std::FILE* file)\n{\n if (opened && stdfile)\n quit(_fail, \"Can't reset standard handle\");\n\n if (opened)\n close();\n\n if (!stdfile)\n if (NULL == (file = std::fopen(name.c_str(), \"rb\")))\n {\n if (mode == _output)\n quits(_pe, std::string(\"Output file not found: \\\"\") + name + \"\\\"\");\n \n if (mode == _answer)\n quits(_fail, std::string(\"Answer file not found: \\\"\") + name + \"\\\"\");\n }\n\n if (NULL != file)\n {\n opened = true;\n\n __testlib_set_binary(file);\n\n if (stdfile)\n reader = new FileInputStreamReader(file, name);\n else\n reader = new BufferedFileInputStreamReader(file, name);\n }\n else\n {\n opened = false;\n reader = NULL;\n }\n}\n\nvoid InStream::init(std::string fileName, TMode mode)\n{\n opened = false;\n name = fileName;\n stdfile = false;\n this->mode = mode;\n \n std::ifstream stream;\n stream.open(fileName.c_str(), std::ios::in);\n if (stream.is_open())\n {\n std::streampos start = stream.tellg();\n stream.seekg(0, std::ios::end);\n std::streampos end = stream.tellg();\n size_t fileSize = size_t(end - start);\n stream.close();\n \n // You can change maxFileSize.\n // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'.\n if (fileSize > maxFileSize)\n quitf(_pe, \"File size exceeds %d bytes, size is %d\", int(maxFileSize), int(fileSize));\n }\n\n reset();\n}\n\nvoid InStream::init(std::FILE* f, TMode mode)\n{\n opened = false;\n name = \"untitled\";\n this->mode = mode;\n \n if (f == stdin)\n name = \"stdin\", stdfile = true;\n if (f == stdout)\n name = \"stdout\", stdfile = true;\n if (f == stderr)\n name = \"stderr\", stdfile = true;\n\n reset(f);\n}\n\nchar InStream::curChar()\n{\n return char(reader->curChar());\n}\n\nchar InStream::nextChar()\n{\n return char(reader->nextChar());\n}\n\nchar InStream::readChar()\n{\n return nextChar();\n}\n\nchar InStream::readChar(char c)\n{\n lastLine = reader->getLine();\n char found = readChar();\n if (c != found)\n {\n if (!isEoln(found))\n quit(_pe, (\"Unexpected character '\" + std::string(1, found) + \"', but '\" + std::string(1, c) + \"' expected\").c_str());\n else\n quit(_pe, (\"Unexpected character \" + (\"#\" + vtos(int(found))) + \", but '\" + std::string(1, c) + \"' expected\").c_str());\n }\n return found;\n}\n\nchar InStream::readSpace()\n{\n return readChar(' ');\n}\n\nvoid InStream::unreadChar(char c)\n{\n reader->unreadChar(c);\n}\n\nvoid InStream::skipChar()\n{\n reader->skipChar();\n}\n\nvoid InStream::skipBlanks()\n{\n while (isBlanks(reader->curChar()))\n reader->skipChar();\n}\n\nstd::string InStream::readWord()\n{\n readWordTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nvoid InStream::readWordTo(std::string& result)\n{\n if (!strict)\n skipBlanks();\n\n lastLine = reader->getLine();\n int cur = reader->nextChar();\n\n if (cur == EOFC)\n quit(_unexpected_eof, \"Unexpected end of file - token expected\");\n\n if (isBlanks(cur))\n quit(_pe, \"Unexpected white-space - token expected\");\n\n result.clear();\n\n while (!(isBlanks(cur) || cur == EOFC))\n {\n result += char(cur);\n \n // You can change maxTokenLength.\n // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'.\n if (result.length() > maxTokenLength)\n quitf(_pe, \"Length of token exceeds %d, token is '%s...'\", int(maxTokenLength), __testlib_part(result).c_str());\n\n cur = reader->nextChar();\n }\n\n reader->unreadChar(cur);\n\n if (result.length() == 0)\n quit(_unexpected_eof, \"Unexpected end of file or white-space - token expected\");\n}\n\nstd::string InStream::readToken()\n{\n return readWord();\n}\n\nvoid InStream::readTokenTo(std::string& result)\n{\n readWordTo(result);\n}\n\nstatic std::string __testlib_part(const std::string& s)\n{\n if (s.length() <= 64)\n return s;\n else\n return s.substr(0, 30) + \"...\" + s.substr(s.length() - 31, 31);\n}\n\n#define __testlib_readMany(readMany, readOne, typeName, space) \\\n if (size < 0) \\\n quit(_fail, #readMany \": size should be non-negative.\"); \\\n if (size > 100000000) \\\n quit(_fail, #readMany \": size should be at most 100000000.\"); \\\n \\\n std::vector result(size); \\\n readManyIteration = indexBase; \\\n \\\n for (int i = 0; i < size; i++) \\\n { \\\n result[i] = readOne; \\\n readManyIteration++; \\\n if (strict && space && i + 1 < size) \\\n readSpace(); \\\n } \\\n \\\n readManyIteration = NO_INDEX; \\\n return result; \\\n\nstd::string InStream::readWord(const pattern& p, const std::string& variableName)\n{\n readWordTo(_tmpReadToken);\n if (!p.matches(_tmpReadToken))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Token element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token element \" + variableName + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n return _tmpReadToken;\n}\n\nstd::vector InStream::readWords(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readWord(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(pattern(ptrn), variableName);\n}\n\nstd::vector InStream::readWords(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const pattern& p, const std::string& variableName)\n{\n return readWord(p, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(ptrn, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true);\n}\n\nvoid InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readWordTo(result);\n if (!p.matches(result))\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n}\n\nvoid InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, pattern(ptrn), variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n return readWordTo(result, p, variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, ptrn, variableName);\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(long long integer, const char* s)\n{\n if (integer == LLONG_MIN)\n return strcmp(s, \"-9223372036854775808\") == 0;\n\n if (integer == 0LL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n if (integer < 0 && s[0] != '-')\n return false;\n\n if (integer < 0)\n s++, length--, integer = -integer;\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(unsigned long long integer, const char* s)\n{\n if (integer == ULLONG_MAX)\n return strcmp(s, \"18446744073709551615\") == 0;\n\n if (integer == 0ULL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\nstatic inline double stringToDouble(InStream& in, const char* buffer)\n{\n double retval;\n\n size_t length = strlen(buffer);\n\n int minusCount = 0;\n int plusCount = 0;\n int decimalPointCount = 0;\n int digitCount = 0;\n int eCount = 0;\n\n for (size_t i = 0; i < length; i++)\n {\n if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.'\n || buffer[i] == 'e' || buffer[i] == 'E'\n || buffer[i] == '-' || buffer[i] == '+')\n {\n if ('0' <= buffer[i] && buffer[i] <= '9')\n digitCount++;\n if (buffer[i] == 'e' || buffer[i] == 'E')\n eCount++;\n if (buffer[i] == '-')\n minusCount++;\n if (buffer[i] == '+')\n plusCount++;\n if (buffer[i] == '.')\n decimalPointCount++;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n // If for sure is not a number in standard notation or in e-notation.\n if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)\n{\n if (minAfterPointDigitCount < 0)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be non-negative.\");\n \n if (minAfterPointDigitCount > maxAfterPointDigitCount)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.\");\n\n double retval;\n\n size_t length = strlen(buffer);\n\n if (length == 0 || length > 1000)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int pointPos = -1; \n for (size_t i = 1; i + 1 < length; i++)\n {\n if (buffer[i] == '.')\n {\n if (pointPos > -1)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n pointPos = int(i);\n }\n if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n if (buffer[length - 1] < '0' || buffer[length - 1] > '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);\n if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)\n in.quit(_pe, (\"Expected strict double with number of digits after point in range [\"\n + vtos(minAfterPointDigitCount)\n + \",\"\n + vtos(maxAfterPointDigitCount)\n + \"], but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str()\n );\n\n int firstDigitPos = -1;\n for (size_t i = 0; i < length; i++)\n if (buffer[i] >= '0' && buffer[i] <= '9')\n {\n firstDigitPos = int(i);\n break;\n }\n\n if (firstDigitPos > 1 || firstDigitPos == -1) \n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)\n && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline long long stringToLongLong(InStream& in, const char* buffer)\n{\n if (strcmp(buffer, \"-9223372036854775808\") == 0)\n return LLONG_MIN;\n\n bool minus = false;\n size_t length = strlen(buffer);\n \n if (length > 1 && buffer[0] == '-')\n minus = true;\n\n if (length > 20)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n long long retval = 0LL;\n\n int zeroes = 0;\n int processingZeroes = true;\n \n for (int i = (minus ? 1 : 0); i < int(length); i++)\n {\n if (buffer[i] == '0' && processingZeroes)\n zeroes++;\n else\n processingZeroes = false;\n\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (retval < 0)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n \n if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n retval = (minus ? -retval : +retval);\n\n if (length < 19)\n return retval;\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline unsigned long long stringToUnsignedLongLong(InStream& in, const char* buffer)\n{\n size_t length = strlen(buffer);\n\n if (length > 20)\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n if (length > 1 && buffer[0] == '0')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n unsigned long long retval = 0LL;\n for (int i = 0; i < int(length); i++)\n {\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (length < 19)\n return retval;\n\n if (length == 20 && strcmp(buffer, \"18446744073709551615\") == 1)\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nint InStream::readInteger()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int32 expected\");\n\n readWordTo(_tmpReadToken);\n \n long long value = stringToLongLong(*this, _tmpReadToken.c_str());\n if (value < INT_MIN || value > INT_MAX)\n quit(_pe, (\"Expected int32, but \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" found\").c_str());\n \n return int(value);\n}\n\nlong long InStream::readLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToLongLong(*this, _tmpReadToken.c_str());\n}\n\nunsigned long long InStream::readUnsignedLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToUnsignedLongLong(*this, _tmpReadToken.c_str());\n}\n\nlong long InStream::readLong(long long minv, long long maxv, const std::string& variableName)\n{\n long long result = readLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readLongs(int size, long long minv, long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true)\n}\n\nunsigned long long InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n unsigned long long result = readUnsignedLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true)\n}\n\nunsigned long long InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n return readUnsignedLong(minv, maxv, variableName);\n}\n\nint InStream::readInt()\n{\n return readInteger();\n}\n\nint InStream::readInt(int minv, int maxv, const std::string& variableName)\n{\n int result = readInt();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nint InStream::readInteger(int minv, int maxv, const std::string& variableName)\n{\n return readInt(minv, maxv, variableName);\n}\n\nstd::vector InStream::readInts(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true)\n}\n\nstd::vector InStream::readIntegers(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true)\n}\n\ndouble InStream::readReal()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - double expected\");\n\n return stringToDouble(*this, readWord().c_str());\n}\n\ndouble InStream::readDouble()\n{\n return readReal();\n}\n\ndouble InStream::readReal(double minv, double maxv, const std::string& variableName)\n{\n double result = readReal();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readReals(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readDouble(double minv, double maxv, const std::string& variableName)\n{\n return readReal(minv, maxv, variableName);\n} \n\nstd::vector InStream::readDoubles(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - strict double expected\");\n\n double result = stringToStrictDouble(*this, readWord().c_str(),\n minAfterPointDigitCount, maxAfterPointDigitCount);\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictReals, readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\ndouble InStream::readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n return readStrictReal(minv, maxv,\n minAfterPointDigitCount, maxAfterPointDigitCount,\n variableName);\n}\n\nstd::vector InStream::readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictDoubles, readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\nbool InStream::eof()\n{\n if (!strict && NULL == reader)\n return true;\n\n return reader->eof();\n}\n\nbool InStream::seekEof()\n{\n if (!strict && NULL == reader)\n return true;\n skipBlanks();\n return eof();\n}\n\nbool InStream::eoln()\n{\n if (!strict && NULL == reader)\n return true;\n\n int c = reader->nextChar();\n\n if (!strict)\n {\n if (c == EOFC)\n return true;\n\n if (c == CR)\n {\n c = reader->nextChar();\n\n if (c != LF)\n {\n reader->unreadChar(c);\n reader->unreadChar(CR);\n return false;\n }\n else\n return true;\n }\n \n if (c == LF)\n return true;\n\n reader->unreadChar(c);\n return false;\n }\n else\n {\n bool returnCr = false;\n\n#if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS)\n if (c != CR)\n {\n reader->unreadChar(c);\n return false;\n }\n else\n {\n if (!returnCr)\n returnCr = true;\n c = reader->nextChar();\n }\n#endif \n if (c != LF)\n {\n reader->unreadChar(c);\n if (returnCr)\n reader->unreadChar(CR);\n return false;\n }\n\n return true;\n }\n}\n\nvoid InStream::readEoln()\n{\n lastLine = reader->getLine();\n if (!eoln())\n quit(_pe, \"Expected EOLN\");\n}\n\nvoid InStream::readEof()\n{\n lastLine = reader->getLine();\n if (!eof())\n quit(_pe, \"Expected EOF\");\n\n if (TestlibFinalizeGuard::alive && this == &inf)\n testlibFinalizeGuard.readEofCount++;\n}\n\nbool InStream::seekEoln()\n{\n if (!strict && NULL == reader)\n return true;\n \n int cur;\n do\n {\n cur = reader->nextChar();\n } \n while (cur == SPACE || cur == TAB);\n\n reader->unreadChar(cur);\n return eoln();\n}\n\nvoid InStream::nextLine()\n{\n readLine();\n}\n\nvoid InStream::readStringTo(std::string& result)\n{\n if (NULL == reader)\n quit(_pe, \"Expected line\");\n\n result.clear();\n\n for (;;)\n {\n int cur = reader->curChar();\n\n if (cur == LF || cur == EOFC)\n break;\n\n if (cur == CR)\n {\n cur = reader->nextChar();\n if (reader->curChar() == LF)\n {\n reader->unreadChar(cur);\n break;\n }\n }\n\n lastLine = reader->getLine();\n result += char(reader->nextChar());\n }\n\n if (strict)\n readEoln();\n else\n eoln();\n}\n\nstd::string InStream::readString()\n{\n readStringTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, int indexBase)\n{\n __testlib_readMany(readStrings, readString(), std::string, false)\n}\n\nvoid InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result);\n if (!p.matches(result))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Line \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Line element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n}\n\nvoid InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, pattern(ptrn), variableName);\n}\n\nstd::string InStream::readString(const pattern& p, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, p, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readString(const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, ptrn, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result)\n{\n readStringTo(result);\n}\n\nstd::string InStream::readLine()\n{\n return readString();\n}\n\nstd::vector InStream::readLines(int size, int indexBase)\n{\n __testlib_readMany(readLines, readString(), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result, p, variableName);\n}\n\nvoid InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, ptrn, variableName);\n}\n\nstd::string InStream::readLine(const pattern& p, const std::string& variableName)\n{\n return readString(p, variableName);\n}\n\nstd::vector InStream::readLines(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readLine(const std::string& ptrn, const std::string& variableName)\n{\n return readString(ptrn, variableName);\n}\n\nstd::vector InStream::readLines(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid InStream::ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n this->__testlib_ensure(cond, message);\n }\n}\n\nvoid InStream::__testlib_ensure(bool cond, std::string message)\n{\n if (!cond)\n this->quit(_wa, message.c_str()); \n}\n\nvoid InStream::close()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n \n opened = false;\n}\n\nNORETURN void quit(TResult result, const std::string& msg)\n{\n ouf.quit(result, msg.c_str());\n}\n\nNORETURN void quit(TResult result, const char* msg)\n{\n ouf.quit(result, msg);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...);\n\nNORETURN void __testlib_quitp(double points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %lf, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", points));\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void __testlib_quitp(int points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %d, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = format(\"%d\", points);\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void quitp(float points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(double points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\nNORETURN void quitp(long double points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(int points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\ntemplate\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitp(F points, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quitp(points, message);\n}\n\ntemplate\nNORETURN void quitp(F points)\n{\n __testlib_quitp(points, std::string(\"\"));\n}\n\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid quitif(bool condition, TResult result, const char* format, ...)\n{\n if (condition)\n {\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n }\n}\n\nNORETURN void __testlib_help()\n{\n InStream::textColor(InStream::LightCyan);\n std::fprintf(stderr, \"TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ \", VERSION);\n std::fprintf(stderr, \"by Mike Mirzayanov, copyright(c) 2005-2018\\n\");\n std::fprintf(stderr, \"Checker name: \\\"%s\\\"\\n\", checkerName.c_str());\n InStream::textColor(InStream::LightGray);\n\n std::fprintf(stderr, \"\\n\");\n std::fprintf(stderr, \"Latest features: \\n\");\n for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)\n {\n std::fprintf(stderr, \"*) %s\\n\", latestFeatures[i]);\n }\n std::fprintf(stderr, \"\\n\");\n\n std::fprintf(stderr, \"Program must be run with the following arguments: \\n\");\n std::fprintf(stderr, \" [ [<-appes>]]\\n\\n\");\n\n std::exit(FAIL_EXIT_CODE);\n}\n\nstatic void __testlib_ensuresPreconditions()\n{\n // testlib assumes: sizeof(int) = 4.\n __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);\n\n // testlib assumes: INT_MAX == 2147483647.\n __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);\n\n // testlib assumes: sizeof(long long) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);\n\n // testlib assumes: sizeof(double) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);\n\n // testlib assumes: no -ffast-math.\n if (!__testlib_isNaN(+__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n if (!__testlib_isNaN(-__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n}\n\nvoid registerGen(int argc, char* argv[], int randomGeneratorVersion)\n{\n if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)\n quitf(_fail, \"Random generator version is expected to be 0 or 1.\");\n random_t::version = randomGeneratorVersion;\n\n __testlib_ensuresPreconditions();\n\n testlibMode = _generator;\n __testlib_set_binary(stdin);\n rnd.setSeed(argc, argv);\n}\n\n#ifdef USE_RND_AS_BEFORE_087\nvoid registerGen(int argc, char* argv[])\n{\n registerGen(argc, argv, 0);\n}\n#else\n#ifdef __GNUC__\n#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4))\n __attribute__ ((deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\")))\n#else\n __attribute__ ((deprecated))\n#endif\n#endif\n#ifdef _MSC_VER\n __declspec(deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\"))\n#endif\nvoid registerGen(int argc, char* argv[])\n{\n std::fprintf(stderr, \"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\\n\\n\");\n registerGen(argc, argv, 0);\n}\n#endif\n\nvoid registerInteraction(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _interactor;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n \n if (argc < 3 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [ [<-appes>]]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc <= 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n#ifndef EJUDGE\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n#endif\n\n inf.init(argv[1], _input);\n\n tout.open(argv[2], std::ios_base::out);\n if (tout.fail() || !tout.is_open())\n quit(_fail, std::string(\"Can not write to the test-output-file '\") + argv[2] + std::string(\"'\"));\n\n ouf.init(stdin, _output);\n \n if (argc >= 4)\n ans.init(argv[3], _answer);\n else\n ans.name = \"unopened answer stream\";\n}\n\nvoid registerValidation()\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _validator;\n __testlib_set_binary(stdin);\n\n inf.init(stdin, _input);\n inf.strict = true;\n}\n\nvoid registerValidation(int argc, char* argv[])\n{\n registerValidation();\n\n for (int i = 1; i < argc; i++)\n {\n if (!strcmp(\"--testset\", argv[i]))\n {\n if (i + 1 < argc && strlen(argv[i + 1]) > 0)\n validator.setTestset(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--group\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setGroup(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--testOverviewLogFileName\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setTestOverviewLogFileName(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n } \n}\n\nvoid addFeature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.addFeature(feature); \n}\n\nvoid feature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.feature(feature); \n}\n\nvoid registerTestlibCmd(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _checker;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n\n if (argc < 4 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [<-appes>]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc == 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n\n inf.init(argv[1], _input);\n ans.init(argv[2], _answer);\n ouf.init(argv[3], _output);\n}\n\nvoid registerTestlib(int argc, ...)\n{\n if (argc < 3 || argc > 5)\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n\n char** argv = new char*[argc + 1];\n \n va_list ap;\n va_start(ap, argc);\n argv[0] = NULL;\n for (int i = 0; i < argc; i++)\n {\n argv[i + 1] = va_arg(ap, char*);\n }\n va_end(ap);\n\n registerTestlibCmd(argc + 1, argv);\n delete[] argv;\n}\n\nstatic inline void __testlib_ensure(bool cond, const std::string& msg)\n{\n if (!cond)\n quit(_fail, msg.c_str());\n}\n\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\nstatic inline void __testlib_ensure(bool cond, const char* msg)\n{\n if (!cond)\n quit(_fail, msg);\n}\n\n#define ensure(cond) __testlib_ensure(cond, \"Condition failed: \\\"\" #cond \"\\\"\")\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\ninline void ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n __testlib_ensure(cond, message);\n }\n}\n\nNORETURN static void __testlib_fail(const std::string& message)\n{\n quitf(_fail, \"%s\", message.c_str());\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid setName(const char* format, ...)\n{\n FMT_TO_RESULT(format, format, name);\n checkerName = name;\n}\n\n/* \n * Do not use random_shuffle, because it will produce different result\n * for different C++ compilers.\n *\n * This implementation uses testlib random_t to produce random numbers, so\n * it is stable.\n */ \ntemplate\nvoid shuffle(_RandomAccessIter __first, _RandomAccessIter __last)\n{\n if (__first == __last) return;\n for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)\n std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));\n}\n\n\ntemplate\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use random_shuffle(), use shuffle() instead\")))\n#endif\nvoid random_shuffle(_RandomAccessIter , _RandomAccessIter )\n{\n quitf(_fail, \"Don't use random_shuffle(), use shuffle() instead\");\n}\n\n#ifdef __GLIBC__\n# define RAND_THROW_STATEMENT throw()\n#else\n# define RAND_THROW_STATEMENT\n#endif\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use rand(), use rnd.next() instead\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nint rand() RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use rand(), use rnd.next() instead\");\n \n /* This line never runs. */\n //throw \"Don't use rand(), use rnd.next() instead\";\n}\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1).\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nvoid srand(unsigned int seed) RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1) [ignored seed=%d].\", seed);\n}\n\nvoid startTest(int test)\n{\n const std::string testFileName = vtos(test);\n if (NULL == freopen(testFileName.c_str(), \"wt\", stdout))\n __testlib_fail(\"Unable to write file '\" + testFileName + \"'\");\n}\n\ninline std::string upperCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('a' <= s[i] && s[i] <= 'z')\n s[i] = char(s[i] - 'a' + 'A');\n return s;\n}\n\ninline std::string lowerCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('A' <= s[i] && s[i] <= 'Z')\n s[i] = char(s[i] - 'A' + 'a');\n return s;\n}\n\ninline std::string compress(const std::string& s)\n{\n return __testlib_part(s);\n}\n\ninline std::string englishEnding(int x)\n{\n x %= 100;\n if (x / 10 == 1)\n return \"th\";\n if (x % 10 == 1)\n return \"st\";\n if (x % 10 == 2)\n return \"nd\";\n if (x % 10 == 3)\n return \"rd\";\n return \"th\";\n}\n\ninline std::string trim(const std::string& s)\n{\n if (s.empty())\n return s;\n\n int left = 0;\n while (left < int(s.length()) && isBlanks(s[left]))\n left++;\n if (left >= int(s.length()))\n return \"\";\n\n int right = int(s.length()) - 1;\n while (right >= 0 && isBlanks(s[right]))\n right--;\n if (right < 0)\n return \"\";\n\n return s.substr(left, right - left + 1);\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator)\n{\n std::stringstream ss;\n bool repeated = false;\n for (_ForwardIterator i = first; i != last; i++)\n {\n if (repeated)\n ss << separator;\n else\n repeated = true;\n ss << *i;\n }\n return ss.str();\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last)\n{\n return join(first, last, ' ');\n}\n\ntemplate \nstd::string join(const _Collection& collection, _Separator separator)\n{\n return join(collection.begin(), collection.end(), separator);\n}\n\ntemplate \nstd::string join(const _Collection& collection)\n{\n return join(collection, ' ');\n}\n\n/**\n * Splits string s by character separator returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separator returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n if (!item.empty())\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n \n if (!item.empty())\n result.push_back(item);\n\n return result;\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char* prepend)\n{\n std::string message;\n if (strlen(prepend) != 0)\n message = format(\"%s: expected '%s', but found '%s'\",\n compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());\n else\n message = format(\"expected '%s', but found '%s'\",\n compress(expected).c_str(), compress(found).c_str());\n quit(result, message);\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char* prepend)\n{\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend);\n}\n\ntemplate \n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, T expected, T found, const char* prependFormat = \"\", ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = vtos(expected);\n std::string foundString = vtos(found);\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, std::string expected, std::string found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, expected, found, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, double expected, double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, const char* expected, const char* found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, float expected, float found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, long double expected, long double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\n#endif\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate \nstruct is_iterable\n{\n template \n static char test(typename U::iterator* x);\n \n template \n static long test(U* x);\n \n static const bool value = sizeof(test(0)) == 1;\n};\n\ntemplate\nstruct __testlib_enable_if {};\n \ntemplate\nstruct __testlib_enable_if { typedef T type; };\n\ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n std::cout << t;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n bool first = true;\n for (typename T::const_iterator i = t.begin(); i != t.end(); i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n std::cout << *i;\n }\n}\n\ntemplate<>\ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const std::string& t)\n{\n std::cout << t;\n}\n \ntemplate\nvoid __println_range(A begin, B end)\n{\n bool first = true;\n for (B i = B(begin); i != end; i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n __testlib_print_one(*i);\n }\n std::cout << std::endl;\n}\n\ntemplate\nstruct is_iterator\n{ \n static T makeT();\n typedef void * twoptrs[2];\n static twoptrs & test(...);\n template static typename R::iterator_category * test(R);\n template static void * test(R *);\n static const bool value = sizeof(test(makeT())) == sizeof(void *); \n};\n\ntemplate\nstruct is_iterator::value >::type>\n{\n static const bool value = false; \n};\n\ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __println_range(a, b);\n}\n\ntemplate \nvoid println(const A* a, const A* b)\n{\n __println_range(a, b);\n}\n\ntemplate <>\nvoid println(const char* a, const char* b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const T& x)\n{\n __testlib_print_one(x);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f, const G& g)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << \" \";\n __testlib_print_one(g);\n std::cout << std::endl;\n}\n#endif\n\n\n\nvoid registerChecker(std::string probName, int argc, char* argv[])\n{\n setName(\"checker for problem %s\", probName.c_str());\n registerTestlibCmd(argc, argv);\n}\n\n\n\nconst std::string _grader_OK = \"OK\";\nconst std::string _grader_SV = \"SV\";\nconst std::string _grader_WA = \"WA\";\nconst std::string _grader_FAIL = \"FAIL\";\n\n\nvoid InStream::readSecret(std::string secret)\n{\n if (readWord() != secret)\n quitf(_sv, \"secret mismatch\");\n eoln();\n}\n\nvoid readBothSecrets(std::string secret)\n{\n ans.readSecret(secret);\n ouf.readSecret(secret);\n}\n\nvoid InStream::readGraderResult()\n{\n std::string result = readWord();\n eoln();\n if (result == _grader_OK)\n return;\n if (result == _grader_SV)\n {\n if (eof())\n quitf(_sv, \"Security violation in grader\");\n std::string msg = readLine();\n quitf(_wa, \"Security violation in grader: %s\", msg.c_str());\n }\n if (result == _grader_WA)\n {\n if (eof())\n quitf(_wa, \"WA in grader\");\n std::string msg = readLine();\n quitf(_wa, \"WA in grader: %s\", msg.c_str());\n }\n if (result == _grader_FAIL)\n {\n if (eof())\n quitf(_fail, \"FAIL in grader\");\n std::string msg = readLine();\n quitf(_fail, \"FAIL in grader: %s\", msg.c_str());\n }\n quitf(_fail, \"Unknown grader result\");\n}\n\nvoid readBothGraderResults()\n{\n ans.readGraderResult();\n ouf.readGraderResult();\n}\n\n\nNORETURN void quit(TResult result)\n{\n ouf.quit(result, \"\");\n}\n\n/// Used in validators: skips the rest of input, assuming it to be correct\nNORETURN void skip_ok()\n{\n if (testlibMode != _validator)\n quitf(_fail, \"skip_ok() only works in validators\");\n testlibFinalizeGuard.quitCount++;\n halt(0);\n}\n\n/// 1 -> 1st, 2 -> 2nd, 3 -> 3rd, 4 -> 4th, ...\nstd::string englishTh(int x)\n{\n char c[100];\n sprintf(c, \"%d%s\", x, englishEnding(x).c_str());\n return c;\n}\n\n/// Compares the tokens of two lines\nvoid compareTokens(int lineNo, std::string a, std::string b, char separator=' ')\n{\n std::vector toka = tokenize(a, separator);\n std::vector tokb = tokenize(b, separator);\n if (toka == tokb)\n return;\n std::string dif = format(\"%s lines differ - \", englishTh(lineNo).c_str());\n if (toka.size() != tokb.size())\n quitf(_wa, \"%sexpected: %d tokens, found %d tokens\", dif.c_str(), int(toka.size()), int(tokb.size()));\n for (int i=0; i\n#include \n#include \n#include \n#include \"combo.h\"\n\nnamespace {\n\nconstexpr int MAX_N = 2000;\nconstexpr int MAX_NUM_MOVES = 8000;\n\nint N;\nstd::string S;\n\nint num_moves;\n\nvoid wrong_answer(const char *MSG) {\n printf(\"Wrong Answer: %s\\n\", MSG);\n exit(0);\n}\n\n} // namespace\n\nint press(std::string p) {\n if (++num_moves > MAX_NUM_MOVES) {\n wrong_answer(\"too many moves\");\n }\n int len = p.length();\n if (len > 4 * N) {\n wrong_answer(\"invalid press\");\n }\n for (int i = 0; i < len; ++i) {\n if (p[i] != 'A' && p[i] != 'B' && p[i] != 'X' && p[i] != 'Y') {\n wrong_answer(\"invalid press\");\n }\n }\n int coins = 0;\n for (int i = 0, j = 0; i < len; ++i) {\n if (j < N && S[j] == p[i]) {\n ++j;\n } else if (S[0] == p[i]) {\n j = 1;\n } else {\n j = 0;\n }\n coins = std::max(coins, j);\n }\n return coins;\n}\n\nint main() {\n char buffer[MAX_N + 1];\n if (scanf(\"%s\", buffer) != 1) {\n fprintf(stderr, \"Error while reading input\\n\");\n exit(1);\n }\n S = buffer;\n N = S.length();\n\n num_moves = 0;\n std::string answer = guess_sequence(N);\n if (answer != S) {\n wrong_answer(\"wrong guess\");\n exit(0);\n }\n printf(\"Accepted: %d\\n\", num_moves);\n return 0;\n}\n", "combo.h": "#include \n\nstd::string guess_sequence(int N);\n\nint press(std::string p);\n"}} {"problem_id": "ioi25_a", "cate": ["math", "data structures"], "difficulty": "medium", "cpu_time_limit_ms": 2000, "memory_limit_mb": 2048, "description": "Amaru is buying souvenirs in a foreign shop. There are $$$N$$$ types of souvenirs. There are infinitely many souvenirs of each type available in the shop.\n\nEach type of souvenir has a fixed price. Namely, a souvenir of type $$$i$$$ ($$$0 \\leq i < N$$$) has a price of $$$P[i]$$$ coins, where $$$P[i]$$$ is a positive integer.\n\nAmaru knows that souvenir types are sorted in decreasing order by price, and that the souvenir prices are distinct. Specifically, $$$P[0] > P[1] > \\ldots > P[N-1] > 0$$$. Moreover, he was able to learn the value of $$$P[0]$$$. Unfortunately, Amaru does not have any other information about the prices of the souvenirs.\n\nTo buy some souvenirs, Amaru will perform a number of transactions with the seller.\n\nEach transaction consists of the following steps:\n\n1. Amaru hands some (positive) number of coins to the seller.\n2. The seller puts these coins in a pile on the table in the back room, where Amaru cannot see them.\n3. The seller considers each souvenir type $$$0, 1, \\ldots, N-1$$$ in that order, one by one. Each type is considered exactly once per transaction.\n * When considering souvenir type $$$i$$$, if the current number of coins in the pile is at least $$$P[i]$$$, then\n + the seller removes $$$P[i]$$$ coins from the pile, and\n + the seller puts one souvenir of type $$$i$$$ on the table.\n4. The seller gives Amaru all the coins remaining in the pile and all souvenirs on the table.\n\nNote that there are no coins or souvenirs on the table before a transaction begins.\n\nYour task is to instruct Amaru to perform some number of transactions, so that:\n\n* in each transaction he buys at least one souvenir, and\n* overall he buys exactly $$$i$$$ souvenirs of type $$$i$$$, for each $$$i$$$ such that $$$0 \\leq i < N$$$. Note that this means that Amaru should not buy any souvenir of type $$$0$$$.\n\nAmaru does not have to minimize the number of transactions and has an unlimited supply of coins.\n\nImplementation Details\n\nYou should implement the following procedure.\n\nvoid buy\\_souvenirs(int N, long long P0)\n\n* $$$N$$$: the number of souvenir types.\n* $$$P0$$$: the value of $$$P[0]$$$.\n* This procedure is called exactly once for each test case.\n\nThe above procedure can make calls to the following procedure to instruct Amaru to perform a transaction:\n\nstd::pair, long long> transaction(long long M)\n\n* $$$M$$$: the number of coins handed to the seller by Amaru.\n* The procedure returns a pair. The first element of the pair is an array $$$L$$$, containing the types of souvenirs that have been bought (in increasing order). The second element is an integer $$$R$$$, the number of coins returned to Amaru after the transaction.\n* It is required that $$$P[0] > M \\geq P[N-1]$$$. The condition $$$P[0] > M$$$ ensures that Amaru does not buy any souvenir of type $$$0$$$, and $$$M \\geq P[N-1]$$$ ensures that Amaru buys at least one souvenir. If these conditions are not met, your solution will receive the verdict Output isn't correct: Invalid argument. Note that contrary to $$$P[0]$$$, the value of $$$P[N-1]$$$ is not provided in the input.\n* The procedure can be called at most $$$5000$$$ times in each test case.\n\nThe behavior of the grader is not adaptive. This means that the sequence of prices $$$P$$$ is fixed before buy\\_souvenirs is called.\n\nInput\n\nThe sample grader reads in the input in the following format:\n\n* line $$$1$$$: $$$N$$$ ($$$2 \\leq N \\leq 100$$$)\n* line $$$2$$$: $$$P[0]\\ P[1]\\ldots \\ P[N-1]$$$ ($$$1 \\leq P[i] \\leq 10^{15}$$$)\n\n$$$P[i] > P[i+1]$$$ for each $$$i$$$ such that $$$0 \\leq i < N - 1$$$.\n\nOutput\n\nThe sample grader prints your answers in the following format:\n\n* line $$$1$$$: $$$Q[0]\\ Q[1]\\ldots \\ Q[N-1]$$$\n\nHere $$$Q[i]$$$ is the number of souvenirs of type $$$i$$$ bought in total for each $$$i$$$ such that $$$0 \\leq i < N$$$.\n\nScoring\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 1 | 4 | $$$N = 2$$$ |\n| 2 | 3 | $$$P[i] = N - i$$$ for each $$$i$$$ such that $$$0 \\leq i < N$$$. |\n| 3 | 14 | $$$P[i] \\leq P[i+1] + 2$$$ for each $$$i$$$ such that $$$0 \\leq i < N - 1$$$. |\n| 4 | 18 | $$$N = 3$$$ |\n| 5 | 28 | $$$P[i+1] + P[i+2] \\leq P[i]$$$, $$$P[i] \\leq 2 \\cdot P[i+1]$$$ |\n| 6 | 33 | No additional constraints |\n\nExample\n\nInput\n\n```\n3\n4 3 1\n```\n\nOutput\n\n```\n4 3 1\n```\n\nNote\n\nConsider the following call.\n\nbuy\\_souvenirs(3, 4)\n\nThere are $$$N = 3$$$ types of souvenirs and $$$P[0] = 4$$$. Observe that there are only three possible sequences of prices $$$P$$$: $$$[4, 3, 2]$$$, $$$[4, 3, 1]$$$, and $$$[4, 2, 1]$$$.\n\nAssume that buy\\_souvenirs calls transaction(2). Suppose the call returns $$$([2], 1)$$$, meaning that Amaru bought one souvenir of type $$$2$$$ and the seller gave him back $$$1$$$ coin. Observe that this allows us to deduce that $$$P = [4, 3, 1]$$$, since:\n\n* For $$$P = [4, 3, 2]$$$, transaction(2) would have returned $$$([2], 0)$$$.\n* For $$$P = [4, 2, 1]$$$, transaction(2) would have returned $$$([1], 0)$$$.\n\nThen buy\\_souvenirs can call transaction(3), which returns $$$([1], 0)$$$, meaning that Amaru bought one souvenir of type $$$1$$$ and the seller gave him back $$$0$$$ coins. So far, in total, he has bought one souvenir of type $$$1$$$ and one souvenir of type $$$2$$$.\n\nFinally, buy\\_souvenirs can call transaction(1), which returns $$$([2], 0)$$$, meaning that Amaru bought one souvenir of type $$$2$$$. Note that we could have also used transaction(2) here. At this point, in total Amaru has one souvenir of type $$$1$$$ and two souvenirs of type $$$2$$$, as required.", "interactor_files": {"manager.cpp": "#include \"testlib.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\n/******************************** Begin testlib-related material ********************************/\n\ninline FILE* openFile(const char* name, const char* mode) {\n FILE* file = fopen(name, mode);\n if (!file)\n quitf(_fail, \"Could not open file '%s' with mode '%s'.\", name, mode);\n closeOnHalt(file);\n return file;\n}\n\nvector mgr2sol, sol2mgr;\nFILE* log_file = nullptr;\n\nvoid nullifyFile(int idx) {\n mgr2sol[idx] = sol2mgr[idx] = nullptr;\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 1, 2)))\n#endif\nvoid\nlog_printf(const char* fmt, ...) {\n if (log_file) {\n FMT_TO_RESULT(fmt, fmt, message);\n fprintf(log_file, \"%s\", message.c_str());\n fflush(log_file);\n }\n}\n\nvoid registerManager(std::string probName, int num_processes, int argc, char* argv[]) {\n setName(\"manager for problem %s\", probName.c_str());\n __testlib_ensuresPreconditions();\n testlibMode = _checker;\n random_t::version = 1; // Random generator version\n __testlib_set_binary(stdin);\n ouf.mode = _output;\n\n { // Keep alive on broken pipes\n // signal(SIGPIPE, SIG_IGN);\n struct sigaction sa;\n sa.sa_handler = SIG_IGN;\n sigaction(SIGPIPE, &sa, NULL);\n }\n\n int required_args = 1 + 2 * num_processes;\n if (argc < required_args || required_args + 1 < argc) {\n string usage = format(\"'%s'\", argv[0]);\n for (int i = 0; i < num_processes; i++)\n usage += format(\" sol%d-to-mgr mgr-to-sol%d\", i, i);\n usage += \" [mgr_log] < input-file\";\n quitf(_fail,\n \"Manager for problem %s:\\n\"\n \"Invalid number of arguments: %d\\n\"\n \"Usage: %s\",\n probName.c_str(), argc - 1, usage.c_str());\n }\n\n inf.init(stdin, _input);\n closeOnHalt(stdout);\n closeOnHalt(stderr);\n\n mgr2sol.resize(num_processes);\n sol2mgr.resize(num_processes);\n for (int i = 0; i < num_processes; i++) {\n mgr2sol[i] = openFile(argv[1 + 2 * i + 1], \"a\");\n sol2mgr[i] = openFile(argv[1 + 2 * i + 0], \"r\");\n }\n\n if (argc > required_args) {\n log_file = openFile(argv[required_args], \"w\");\n } else {\n log_file = nullptr;\n }\n}\n/********************************* End testlib-related material *********************************/\n\n// utils\n\n#define rep(i, n) for (int i = 0, i##__n = (int)(n); i < i##__n; ++i)\n\ntemplate \nint sz(const C& c) {\n return int(std::size(c));\n}\n\nusing LL = long long;\n\ntemplate \nconstexpr T div_ceil(T a, T b) {\n return (a + b - 1) / b;\n}\n\nvoid set_vi_bit(vector& v, int i, int b) {\n int& x = v[i / 32];\n int j = i % 32;\n if (b == 1)\n x |= (1 << j);\n else\n x &= ~(1 << j);\n}\n\n#define log_var(var_name) log_printf(\"%s = %s\\n\", #var_name, toString(var_name).c_str());\n\ntemplate \nvoid log_array(const C& c, string delim = \" \", string ending = \"\\n\") {\n string d = \"\";\n for (const auto& x : c) {\n log_printf(\"%s%s\", d.c_str(), toString(x).c_str());\n d = delim;\n }\n log_printf(\"%s\", ending.c_str());\n}\n\n// grader/manager protocol\n\nconst int secret_g2m = 0x729B3F30;\nconst int secret_m2g = 0x35397FC0;\nconst int code_mask = 0x0000000F;\n\nconst int M2G_CODE__OK = 0;\nconst int M2G_CODE__DIE = 1;\n\nconst int G2M_CODE__OK_NEW_TRANSACTION = 0;\nconst int G2M_CODE__OK_END_OF_TRANSACTIONS = 1;\nconst int G2M_CODE__PV_CALL_EXIT = 13;\nconst int G2M_CODE__TAMPER_M2G = 14;\nconst int G2M_CODE__SILENT = 15;\n\nint fifo_idx = 0;\n\nenum class ActionMode {\n ok_new_transaction,\n ok_end_of_transactions,\n} ok_action_mode;\n\nvoid out_flush() {\n fflush(mgr2sol[fifo_idx]);\n}\n\nvoid write_int(int x) {\n if (1 != fwrite(&x, sizeof(x), 1, mgr2sol[fifo_idx])) {\n nullifyFile(fifo_idx);\n // add logging here\n }\n}\n\nvoid write_ll(LL x) {\n if (1 != fwrite(&x, sizeof(x), 1, mgr2sol[fifo_idx])) {\n nullifyFile(fifo_idx);\n // add logging here\n }\n}\n\nvoid write_int_vector(const vector& arr) {\n int len = (int)sz(arr);\n if (len != (int)fwrite(arr.data(), sizeof(int), len, mgr2sol[fifo_idx])) {\n nullifyFile(fifo_idx);\n // add logging here\n }\n}\n\nvoid write_secret(int m2g_code = M2G_CODE__OK) {\n write_int(secret_m2g | m2g_code);\n}\n\n#ifdef __GNUC__\n__attribute__((format(printf, 2, 3)))\n#endif\nNORETURN void\ndie(TResult result, const char* format, ...) {\n FMT_TO_RESULT(format, format, message);\n log_printf(\"Dying with message '%s'\\n\", message.c_str());\n rep(i, sz(mgr2sol)) if (mgr2sol[i] != nullptr) {\n fifo_idx = i;\n log_printf(\"Sending secret with code DIE to mgr2sol[%d]\\n\", fifo_idx);\n write_secret(M2G_CODE__DIE);\n out_flush();\n }\n log_printf(\"Quitting with result code %d\\n\", int(result));\n quit(result, message);\n}\n\nNORETURN void die_invalid_argument(const string& msg) {\n RESULT_MESSAGE_WRONG += \": Invalid argument\";\n die(_wa, \"%s\", msg.c_str());\n}\n\nNORETURN void die_too_many_calls(const string& msg) {\n RESULT_MESSAGE_WRONG += \": Too many calls\";\n die(_wa, \"%s\", msg.c_str());\n}\n\nint read_int() {\n int x;\n if (1 != fread(&x, sizeof(x), 1, sol2mgr[fifo_idx])) {\n nullifyFile(fifo_idx);\n die(_fail, \"Could not read int from sol2mgr[%d]\", fifo_idx);\n }\n return x;\n}\n\nLL read_ll() {\n LL x;\n if (1 != fread(&x, sizeof(x), 1, sol2mgr[fifo_idx])) {\n nullifyFile(fifo_idx);\n die(_fail, \"Could not read ll from sol2mgr[%d]\", fifo_idx);\n }\n return x;\n}\n\nvoid read_int_array(int* arr, int len) {\n if (len != (int)fread(arr, sizeof(*arr), len, sol2mgr[fifo_idx])) {\n nullifyFile(fifo_idx);\n die(_fail, \"Could not read int array from sol2mgr[%d]\", fifo_idx);\n }\n}\n\nvoid read_secret() {\n int secret = read_int();\n if ((secret & ~code_mask) != secret_g2m)\n die(_pv, \"Possible tampering with sol2mgr[%d]\", fifo_idx);\n int g2m_code = secret & code_mask;\n switch (g2m_code) {\n case G2M_CODE__OK_NEW_TRANSACTION:\n ok_action_mode = ActionMode::ok_new_transaction;\n return;\n case G2M_CODE__OK_END_OF_TRANSACTIONS:\n ok_action_mode = ActionMode::ok_end_of_transactions;\n return;\n case G2M_CODE__SILENT:\n die(_fail, \"Unexpected g2m_code SILENT from sol2mgr[%d]\", fifo_idx);\n case G2M_CODE__TAMPER_M2G:\n die(_pv, \"Possible tampering with mgr2sol[%d]\", fifo_idx);\n case G2M_CODE__PV_CALL_EXIT:\n die(_pv, \"Solution[%d] called exit()\", fifo_idx);\n default:\n die(_fail, \"Unknown g2m_code %d from sol2mgr[%d]\", g2m_code, fifo_idx);\n }\n}\n\n// problem logic\n\nusing Index = int;\nusing Compressed = int;\nusing Count = int;\nusing Money = LL;\n\n#define read_index read_int\n#define read_money read_ll\n#define write_index write_int\n#define write_money write_ll\n\nconst bool log_details = false;\n\nconst Count TRANSACTIONS_CNT_LIMIT = 5'000;\n\nIndex N;\n\nconstexpr Compressed compressed_len(Index len) {\n return div_ceil(len, 32);\n}\n\nvoid write_indices(const vector& X) {\n vector X_f(compressed_len(N), 0);\n for (Index idx : X)\n set_vi_bit(X_f, idx, 1);\n write_int_vector(X_f);\n}\n\nint main(int argc, char** argv) {\n registerManager(\"souvenirs\", 1, argc, argv);\n\n N = inf.readInt();\n vector P(N);\n rep(i, N)\n P[i] = inf.readLong();\n fclose(stdin);\n\n log_var(N);\n log_printf(\"P:\\n\");\n log_array(P);\n\n write_secret();\n write_index(N);\n write_money(P[0]);\n out_flush();\n\n Count transactions_cnt = 0;\n vector bought(N, 0);\n\n while (true) {\n log_printf(\"Checking for new transaction...\\n\");\n read_secret();\n if (ok_action_mode != ActionMode::ok_new_transaction)\n break;\n log_printf(\"Received a new transaction\\n\");\n\n const Money M = read_money();\n log_var(M);\n\n if (++transactions_cnt > TRANSACTIONS_CNT_LIMIT)\n die_too_many_calls(\"Used too many transactions\");\n if (M >= P[0])\n die_invalid_argument(format(\"M (%lld) >= P[0] (%lld)\", M, P[0]));\n if (M < P[N - 1])\n die_invalid_argument(format(\"M (%lld) < P[N-1] (%lld)\", M, P[N - 1]));\n\n vector L;\n Money R = M;\n rep(idx, N) if (P[idx] <= R) {\n L.push_back(idx);\n R -= P[idx];\n }\n\n if (log_details) {\n log_printf(\"L:\\n\");\n log_array(L);\n } else {\n log_printf(\"L size=%d\\n\", sz(L));\n }\n log_var(R);\n\n ensuref(0 <= R, \"negative value of R=%lld\", R);\n if (L.empty())\n quitf(_wa, \"Nothing is bought with M=%lld\", M);\n ensuref(0 <= L[0], \"negative index L[%d]=%d\", 0, L[0]);\n rep(i, sz(L)) {\n ensuref(L[i] < N, \"too large index L[%d]=%d\", i, L[i]);\n ensuref(i == 0 || L[i - 1] < L[i], \"L is not increasing, L[%d]=%d, L[%d]=%d\", i - 1, L[i - 1], i, L[i]);\n }\n\n for (Index idx : L)\n bought[idx]++;\n\n log_printf(\"Sending transaction results...\\n\");\n write_secret();\n write_indices(L);\n write_money(R);\n out_flush();\n log_printf(\"Transaction results sent.\\n\");\n }\n\n ensuref(ok_action_mode == ActionMode::ok_end_of_transactions, \"Expected action code ok_end_of_transactions\");\n log_printf(\"No more transactions.\\n\");\n\n // Final checking\n rep(idx, N) if (bought[idx] != idx)\n quitf(_wa, \"Item %d is bought %d times, expected %d\", idx, bought[idx], idx);\n quitf(_ok, \"Finished successfully with %d transaction(s)\", transactions_cnt);\n}\n", "stub.cpp": "#include \"souvenirs.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace {\n\n/******************************** Begin testlib-related material ********************************/\n#ifdef _MSC_VER\n#define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n#define NORETURN __attribute__((noreturn))\n#else\n#define NORETURN\n#endif\n/********************************* End testlib-related material *********************************/\n\n// utils\n\n#define rep(i, n) for (int i = 0, i##__n = (int)(n); i < i##__n; ++i)\n\ntemplate \nint sz(const C& c) {\n return int(std::size(c));\n}\n\nusing LL = long long;\n\ntemplate \nconstexpr T div_ceil(T a, T b) {\n return (a + b - 1) / b;\n}\n\nint get_vi_bit(const vector& v, int i) {\n const int& x = v[i / 32];\n int j = i % 32;\n return (x >> j) & 1;\n}\n\n// grader/manager protocol\n\nconst int secret_g2m = 0x729B3F30;\nconst int secret_m2g = 0x35397FC0;\nconst int code_mask = 0x0000000F;\n\nconst int M2G_CODE__OK = 0;\n\nconst int G2M_CODE__OK_NEW_TRANSACTION = 0;\nconst int G2M_CODE__OK_END_OF_TRANSACTIONS = 1;\nconst int G2M_CODE__PV_CALL_EXIT = 13;\nconst int G2M_CODE__TAMPER_M2G = 14;\nconst int G2M_CODE__SILENT = 15;\n\nbool exit_allowed = false;\n\nNORETURN void authorized_exit(int exit_code) {\n exit_allowed = true;\n exit(exit_code);\n}\n\nFILE* fin = stdin;\nFILE* fout = stdout;\n\nvoid out_flush() {\n fflush(fout);\n}\n\nvoid write_int(int x) {\n if (1 != fwrite(&x, sizeof(x), 1, fout)) {\n fprintf(stderr, \"Could not write int to fout\\n\");\n authorized_exit(3);\n }\n}\n\nvoid write_ll(LL x) {\n if (1 != fwrite(&x, sizeof(x), 1, fout)) {\n fprintf(stderr, \"Could not write ll to fout\\n\");\n authorized_exit(3);\n }\n}\n\nvoid write_secret(int g2m_code) {\n write_int(secret_g2m | g2m_code);\n}\n\nNORETURN void die(int g2m_code) {\n if (g2m_code == G2M_CODE__OK_NEW_TRANSACTION || g2m_code == G2M_CODE__OK_END_OF_TRANSACTIONS) {\n fprintf(stderr, \"Shall not die with code OK\\n\");\n authorized_exit(5);\n }\n fprintf(stderr, \"Dying with code %d\\n\", g2m_code);\n if (g2m_code != G2M_CODE__SILENT)\n write_secret(g2m_code);\n fclose(fin);\n fclose(fout);\n authorized_exit(0);\n}\n\nint read_int() {\n int x;\n if (1 != fread(&x, sizeof(x), 1, fin)) {\n fprintf(stderr, \"Could not read int from fin\\n\");\n authorized_exit(3);\n }\n return x;\n}\n\nLL read_ll() {\n LL x;\n if (1 != fread(&x, sizeof(x), 1, fin)) {\n fprintf(stderr, \"Could not read ll from fin\\n\");\n authorized_exit(3);\n }\n return x;\n}\n\nvoid read_int_array(int* arr, int len) {\n if (len != (int)fread(arr, sizeof(*arr), len, fin)) {\n fprintf(stderr, \"Could not read int array from fin\\n\");\n authorized_exit(3);\n }\n}\n\nvoid read_int_vector(vector& v) {\n read_int_array(v.data(), sz(v));\n}\n\nvoid read_secret() {\n int secret = read_int();\n if ((secret & ~code_mask) != secret_m2g)\n die(G2M_CODE__TAMPER_M2G);\n int m2g_code = secret & code_mask;\n if (m2g_code != M2G_CODE__OK)\n die(G2M_CODE__SILENT);\n}\n\nvoid check_exit_protocol() {\n if (!exit_allowed)\n die(G2M_CODE__PV_CALL_EXIT);\n}\n\n// problem logic\n\nusing Index = int;\nusing Compressed = int;\nusing Count = int;\nusing Money = LL;\n\n#define read_index read_int\n#define read_money read_ll\n#define write_index write_int\n#define write_money write_ll\n\nIndex N;\n\nconstexpr Compressed compressed_len(Index len) {\n return div_ceil(len, 32);\n}\n\nvector read_indices() {\n vector X_f(compressed_len(N), 0);\n read_int_vector(X_f);\n vector X;\n rep(i, N) if (get_vi_bit(X_f, i))\n X.push_back(i);\n return X;\n}\n\n} // namespace\n\npair, Money> transaction(Money M) {\n write_secret(G2M_CODE__OK_NEW_TRANSACTION);\n write_money(M);\n out_flush();\n\n read_secret();\n vector L = read_indices();\n Money R = read_money();\n return make_pair(L, R);\n}\n\nint main() {\n signal(SIGPIPE, SIG_IGN);\n atexit(check_exit_protocol);\n at_quick_exit(check_exit_protocol);\n\n read_secret();\n N = read_index();\n Money P0 = read_money();\n\n buy_souvenirs(N, P0);\n\n write_secret(G2M_CODE__OK_END_OF_TRANSACTIONS);\n out_flush();\n authorized_exit(0);\n}\n", "souvenirs.h": "#include \n#include \n\nvoid buy_souvenirs(int N, long long P0);\n\nstd::pair, long long> transaction(long long M);\n", "testlib.h": "/* \n * It is strictly recommended to include \"testlib.h\" before any other include \n * in your code. In this case testlib overrides compiler specific \"random()\".\n *\n * If you can't compile your code and compiler outputs something about \n * ambiguous call of \"random_shuffle\", \"rand\" or \"srand\" it means that \n * you shouldn't use them. Use \"shuffle\", and \"rnd.next()\" instead of them\n * because these calls produce stable result for any C++ compiler. Read \n * sample generator sources for clarification.\n *\n * Please read the documentation for class \"random_t\" and use \"rnd\" instance in\n * generators. Probably, these sample calls will be usefull for you:\n * rnd.next(); rnd.next(100); rnd.next(1, 2); \n * rnd.next(3.14); rnd.next(\"[a-z]{1,100}\").\n *\n * Also read about wnext() to generate off-center random distribution.\n *\n * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker.\n */\n\n#ifndef _TESTLIB_H_\n#define _TESTLIB_H_\n\n/*\n * Copyright (c) 2005-2018\n */\n\n#define VERSION \"0.9.21\"\n\n/* \n * Mike Mirzayanov\n *\n * This material is provided \"as is\", with absolutely no warranty expressed\n * or implied. Any use is at your own risk.\n *\n * Permission to use or copy this software for any purpose is hereby granted \n * without fee, provided the above notices are retained on all copies.\n * Permission to modify the code and to distribute modified code is granted,\n * provided the above notices are retained, and a notice that the code was\n * modified is included with the above copyright notice.\n *\n */\n\n/*\n * Kian Mirjalali:\n *\n * Modified to be compatible with CMS & requirements for preparing IOI tasks\n *\n * * defined FOR_LINUX in order to force linux-based line endings in validators.\n *\n * * Changed the ordering of checker arguments\n * from \n * to \n *\n * * Added \"Security Violation\" & \"Protocol Violation\" as new result types.\n *\n * * Changed checker quit behaviors to make it compliant with CMS.\n *\n * * The checker exit codes should always be 0 in CMS.\n *\n * * For partial scoring, forced quitp() functions to accept only scores in the range [0,1].\n * If the partial score is less than 1e-5, it becomes 1e-5, because 0 grades are considered wrong in CMS.\n * Grades in range [1e-5, 0.0001) are printed exactly (to prevent rounding to zero).\n * Grades in [0.0001, 1] are printed with 4 digits after decimal point.\n *\n * * Added the following utility types/variables/functions/methods:\n * type HaltListener (as a function with no parameters or return values)\n * vector __haltListeners\n * void registerHaltListener(HaltListener haltListener)\n * void callHaltListeners() (which is called in quit)\n * void closeOnHalt(FILE* file)\n * void closeOnHalt(F& f) (template using f.close())\n * void InStream::readSecret(string secret, TResult mismatchResult, string mismatchMessage, string eofMessage)\n * void InStream::readGraderResult()\n * +supporting conversion of graderResult to CMS result\n * void quitp(double), quitp(int)\n * void registerChecker(string probName, argc, argv)\n * void readBothSecrets(string secret)\n * void readBothGraderResults()\n * void quit(TResult)\n * bool compareTokens(string a, string b, char separator=' ')\n * void compareRemainingLines(int lineNo=1)\n * void skip_ok()\n *\n */\n\n/* NOTE: This file contains testlib library for C++.\n *\n * Check, using testlib running format:\n * check.exe [ [-appes]],\n * If result file is specified it will contain results.\n *\n * Validator, using testlib running format: \n * validator.exe < input.txt,\n * It will return non-zero exit code and writes message to standard output.\n *\n * Generator, using testlib running format: \n * gen.exe [parameter-1] [parameter-2] [... paramerter-n]\n * You can write generated test(s) into standard output or into the file(s).\n *\n * Interactor, using testlib running format: \n * interactor.exe [ [ [-appes]]],\n * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],\n * can be judged by checker later), reads program output from ouf (mapped to stdin),\n * writes output to program via stdout (use cout, printf, etc).\n */\n\nconst char* latestFeatures[] = {\n \"Fixed stringstream repeated usage issue\",\n \"Fixed compilation in g++ (for std=c++03)\",\n \"Batch of println functions (support collections, iterator ranges)\",\n \"Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation\",\n \"Allow any whitespace in readInts-like functions for non-validators\",\n \"Ignore 4+ command line arguments ifdef EJUDGE\",\n \"Speed up of vtos\",\n \"Show line number in validators in case of incorrect format\",\n \"Truncate huge checker/validator/interactor message\",\n \"Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type\",\n \"Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type\",\n \"Fixed compilation in VS 2015+\",\n \"Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines\",\n \"Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals\",\n \"Introduced split/tokenize functions to separate string by given char\",\n \"Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters\",\n \"Supported --testOverviewLogFileName for validator: bounds hits + features\",\n \"Fixed UB (sequence points) in random_t\",\n \"POINTS_EXIT_CODE returned back to 7 (instead of 0)\",\n \"Removed disable buffers for interactive problems, because it works unexpectedly in wine\",\n \"InStream over string: constructor of InStream from base InStream to inherit policies and std::string\",\n \"Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \\\"[n=%d,m=%d]\\\", n, m)\",\n \"Fixed incorrect interval parsing in patterns\",\n \"Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)\",\n \"Introduced disableFinalizeGuard() to switch off finalization checkings\",\n \"Use join() functions to format a range of items as a single string (separated by spaces or other separators)\",\n \"Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors\",\n \"Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7\",\n \"Fixed bug with nan in stringToDouble\", \n \"Fixed issue around overloads for size_t on x64\", \n \"Added attribute 'points' to the XML output in case of result=_points\", \n \"Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14\", \n \"Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading\", \n \"Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()\", \n \"Manual buffer in InStreams, some IO speed improvements\", \n \"Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true\", \n \"Introduced guard against missed quitf() in checker or readEof() in validators\", \n \"Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers\", \n \"Supported registerInteraction(argc, argv)\", \n \"Print checker message to the stderr instead of stdout\", \n \"Supported TResult _points to output calculated score, use quitp(...) functions\", \n \"Fixed to be compilable on Mac\", \n \"PC_BASE_EXIT_CODE=50 in case of defined TESTSYS\",\n \"Fixed issues 19-21, added __attribute__ format printf\", \n \"Some bug fixes\", \n \"ouf.readInt(1, 100) and similar calls return WA\", \n \"Modified random_t to avoid integer overflow\", \n \"Truncated checker output [patch by Stepan Gatilov]\", \n \"Renamed class random -> class random_t\", \n \"Supported name parameter for read-and-validation methods, like readInt(1, 2, \\\"n\\\")\", \n \"Fixed bug in readDouble()\", \n \"Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()\", \n \"Supported \\\"partially correct\\\", example: quitf(_pc(13), \\\"result=%d\\\", result)\", \n \"Added shuffle(begin, end), use it instead of random_shuffle(begin, end)\", \n \"Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode\", \n \"Package extended with samples of generators and validators\", \n \"Written the documentation for classes and public methods in testlib.h\",\n \"Implemented random routine to support generators, use registerGen() to switch it on\",\n \"Implemented strict mode to validate tests, use registerValidation() to switch it on\",\n \"Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output\",\n \"Added InStream::readLong() and removed InStream::readLongint()\",\n \"Now no footer added to each report by default (use directive FOOTER to switch on)\",\n \"Now every checker has a name, use setName(const char* format, ...) to set it\",\n \"Now it is compatible with TTS (by Kittens Computing)\",\n \"Added \\'ensure(condition, message = \\\"\\\")\\' feature, it works like assert()\",\n \"Fixed compatibility with MS C++ 7.1\",\n \"Added footer with exit code information\",\n \"Added compatibility with EJUDGE (compile with EJUDGE directive)\",\n \"Added compatibility with Contester (compile with CONTESTER directive)\"\n };\n\n#define FOR_LINUX\n\n#ifdef _MSC_VER\n#define _CRT_SECURE_NO_DEPRECATE\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_NO_VA_START_VALIDATION\n#endif\n\n/* Overrides random() for Borland C++. */\n#define random __random_deprecated\n#include \n#include \n#include \n#include \n#undef random\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ || __CYGWIN__ )\n# if !defined(_MSC_VER) || _MSC_VER>1400\n# define NOMINMAX 1\n# include \n# else\n# define WORD unsigned short\n# include \n# endif\n# include \n# define ON_WINDOWS\n# if defined(_MSC_VER) && _MSC_VER>1400\n# pragma warning( disable : 4127 )\n# pragma warning( disable : 4146 )\n# pragma warning( disable : 4458 )\n# endif\n#else\n# define WORD unsigned short\n# include \n#endif\n\n#if defined(FOR_WINDOWS) && defined(FOR_LINUX)\n#error Only one target system is allowed\n#endif\n\n#ifndef LLONG_MIN\n#define LLONG_MIN (-9223372036854775807LL - 1)\n#endif\n\n#ifndef ULLONG_MAX\n#define ULLONG_MAX (18446744073709551615)\n#endif\n\n#define LF ((char)10)\n#define CR ((char)13)\n#define TAB ((char)9)\n#define SPACE ((char)' ')\n#define EOFC (255)\n\n#ifndef OK_EXIT_CODE\n# ifdef CONTESTER\n# define OK_EXIT_CODE 0xAC\n# else\n# define OK_EXIT_CODE 0\n# endif\n#endif\n\n#ifndef WA_EXIT_CODE\n# ifdef EJUDGE\n# define WA_EXIT_CODE 5\n# elif defined(CONTESTER)\n# define WA_EXIT_CODE 0xAB\n# else\n# define WA_EXIT_CODE 1\n# endif\n#endif\n\n#ifndef PE_EXIT_CODE\n# ifdef EJUDGE\n# define PE_EXIT_CODE 4\n# elif defined(CONTESTER)\n# define PE_EXIT_CODE 0xAA\n# else\n# define PE_EXIT_CODE 2\n# endif\n#endif\n\n#ifndef FAIL_EXIT_CODE\n# ifdef EJUDGE\n# define FAIL_EXIT_CODE 6\n# elif defined(CONTESTER)\n# define FAIL_EXIT_CODE 0xA3\n# else\n# define FAIL_EXIT_CODE 3\n# endif\n#endif\n\n#ifndef DIRT_EXIT_CODE\n# ifdef EJUDGE\n# define DIRT_EXIT_CODE 6\n# else\n# define DIRT_EXIT_CODE 4\n# endif\n#endif\n\n#ifndef POINTS_EXIT_CODE\n# define POINTS_EXIT_CODE 7\n#endif\n\n#ifndef UNEXPECTED_EOF_EXIT_CODE\n# define UNEXPECTED_EOF_EXIT_CODE 8\n#endif\n\n#ifndef SV_EXIT_CODE\n# define SV_EXIT_CODE 20\n#endif\n\n#ifndef PV_EXIT_CODE\n# define PV_EXIT_CODE 21\n#endif\n\n#ifndef PC_BASE_EXIT_CODE\n# ifdef TESTSYS\n# define PC_BASE_EXIT_CODE 50\n# else\n# define PC_BASE_EXIT_CODE 0\n# endif\n#endif\n\n#ifdef __GNUC__\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))\n#else\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]\n#endif\n\n#ifdef ON_WINDOWS\n#define I64 \"%I64d\"\n#define U64 \"%I64u\"\n#else\n#define I64 \"%lld\"\n#define U64 \"%llu\"\n#endif\n\n#ifdef _MSC_VER\n# define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n# define NORETURN __attribute__ ((noreturn))\n#else\n# define NORETURN\n#endif\n\n/**************** HaltListener material ****************/\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntypedef std::function HaltListener;\n#else\ntypedef void (*HaltListener)();\n#endif\n\nstd::vector __haltListeners;\n\ninline void registerHaltListener(HaltListener haltListener) {\n __haltListeners.push_back(haltListener);\n}\n\ninline void callHaltListeners() {\n // Removing and calling haltListeners in reverse order.\n while (!__haltListeners.empty()) {\n HaltListener haltListener = __haltListeners.back();\n __haltListeners.pop_back();\n haltListener();\n }\n}\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ninline void closeOnHalt(FILE* file) {\n registerHaltListener([file] { fclose(file); });\n}\ntemplate\ninline void closeOnHalt(F& f) {\n registerHaltListener([&f] { f.close(); });\n}\n#endif\n/*******************************************************/\n\nstatic char __testlib_format_buffer[16777216];\nstatic int __testlib_format_buffer_usage_count = 0;\n\n#define FMT_TO_RESULT(fmt, cstr, result) std::string result; \\\n if (__testlib_format_buffer_usage_count != 0) \\\n __testlib_fail(\"FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0\"); \\\n __testlib_format_buffer_usage_count++; \\\n va_list ap; \\\n va_start(ap, fmt); \\\n vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \\\n va_end(ap); \\\n __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \\\n result = std::string(__testlib_format_buffer); \\\n __testlib_format_buffer_usage_count--; \\\n\nconst long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;\n\nNORETURN static void __testlib_fail(const std::string& message);\n\ntemplate\nstatic inline T __testlib_abs(const T& x)\n{\n return x > 0 ? x : -x;\n}\n\ntemplate\nstatic inline T __testlib_min(const T& a, const T& b)\n{\n return a < b ? a : b;\n}\n\ntemplate\nstatic inline T __testlib_max(const T& a, const T& b)\n{\n return a > b ? a : b;\n}\n\nstatic bool __testlib_prelimIsNaN(double r)\n{\n volatile double ra = r;\n#ifndef __BORLANDC__\n return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);\n#else\n return std::_isnan(ra);\n#endif\n}\n\nstatic std::string removeDoubleTrailingZeroes(std::string value)\n{\n while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)\n value = value.substr(0, value.length() - 1);\n return value + '0';\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nstd::string format(const char* fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt, result);\n return result;\n}\n\nstd::string format(const std::string fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt.c_str(), result);\n return result;\n}\n\nstatic std::string __testlib_part(const std::string& s);\n\nstatic bool __testlib_isNaN(double r)\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n volatile double ra = r;\n long long llr1, llr2;\n std::memcpy((void*)&llr1, (void*)&ra, sizeof(double)); \n ra = -ra;\n std::memcpy((void*)&llr2, (void*)&ra, sizeof(double)); \n long long llnan = 0xFFF8000000000000LL;\n return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;\n}\n\nstatic double __testlib_nan()\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n#ifndef NAN\n long long llnan = 0xFFF8000000000000LL;\n double nan;\n std::memcpy(&nan, &llnan, sizeof(double));\n return nan;\n#else\n return NAN;\n#endif\n}\n\nstatic bool __testlib_isInfinite(double r)\n{\n volatile double ra = r;\n return (ra > 1E300 || ra < -1E300);\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)\n{\n if (__testlib_isNaN(expected))\n {\n return __testlib_isNaN(result);\n }\n else \n if (__testlib_isInfinite(expected))\n {\n if (expected > 0)\n {\n return result > 0 && __testlib_isInfinite(result);\n }\n else\n {\n return result < 0 && __testlib_isInfinite(result);\n }\n }\n else \n if (__testlib_isNaN(result) || __testlib_isInfinite(result))\n {\n return false;\n }\n else \n if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)\n {\n return true;\n }\n else\n {\n double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n return result + 1E-15 >= minv && result <= maxv + 1E-15;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline double doubleDelta(double expected, double result)\n{\n double absolute = __testlib_abs(result - expected);\n \n if (__testlib_abs(expected) > 1E-9)\n {\n double relative = __testlib_abs(absolute / expected);\n return __testlib_min(absolute, relative);\n }\n else\n return absolute;\n}\n\n#if !defined(_MSC_VER) || _MSC_VER<1900\n#ifndef _fileno\n#define _fileno(_stream) ((_stream)->_file)\n#endif\n#endif\n\n#ifndef O_BINARY\nstatic void __testlib_set_binary(\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\n std::FILE* file\n)\n#else\nstatic void __testlib_set_binary(std::FILE* file)\n#endif\n{\n#ifdef O_BINARY\n if (NULL != file)\n {\n#ifndef __BORLANDC__\n _setmode(_fileno(file), O_BINARY);\n#else\n setmode(fileno(file), O_BINARY);\n#endif\n }\n#endif\n}\n\n/*\n * Very simple regex-like pattern.\n * It used for two purposes: validation and generation.\n * \n * For example, pattern(\"[a-z]{1,5}\").next(rnd) will return\n * random string from lowercase latin letters with length \n * from 1 to 5. It is easier to call rnd.next(\"[a-z]{1,5}\") \n * for the same effect. \n * \n * Another samples:\n * \"mike|john\" will generate (match) \"mike\" or \"john\";\n * \"-?[1-9][0-9]{0,3}\" will generate (match) non-zero integers from -9999 to 9999;\n * \"id-([ac]|b{2})\" will generate (match) \"id-a\", \"id-bb\", \"id-c\";\n * \"[^0-9]*\" will match sequences (empty or non-empty) without digits, you can't \n * use it for generations.\n *\n * You can't use pattern for generation if it contains meta-symbol '*'. Also it\n * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].\n *\n * For matching very simple greedy algorithm is used. For example, pattern\n * \"[0-9]?1\" will not match \"1\", because of greedy nature of matching.\n * Alternations (meta-symbols \"|\") are processed with brute-force algorithm, so \n * do not use many alternations in one expression.\n *\n * If you want to use one expression many times it is better to compile it into\n * a single pattern like \"pattern p(\"[a-z]+\")\". Later you can use \n * \"p.matches(std::string s)\" or \"p.next(random_t& rd)\" to check matching or generate\n * new string by pattern.\n * \n * Simpler way to read token and check it for pattern matching is \"inf.readToken(\"[a-z]+\")\".\n */\nclass random_t;\n\nclass pattern\n{\npublic:\n /* Create pattern instance by string. */\n pattern(std::string s);\n /* Generate new string by pattern and given random_t. */\n std::string next(random_t& rnd) const;\n /* Checks if given string match the pattern. */\n bool matches(const std::string& s) const;\n /* Returns source string of the pattern. */\n std::string src() const;\nprivate:\n bool matches(const std::string& s, size_t pos) const;\n\n std::string s;\n std::vector children;\n std::vector chars;\n int from;\n int to;\n};\n\n/* \n * Use random_t instances to generate random values. It is preffered\n * way to use randoms instead of rand() function or self-written \n * randoms.\n *\n * Testlib defines global variable \"rnd\" of random_t class.\n * Use registerGen(argc, argv, 1) to setup random_t seed be command\n * line (to use latest random generator version).\n *\n * Random generates uniformly distributed values if another strategy is\n * not specified explicitly.\n */\nclass random_t\n{\nprivate:\n unsigned long long seed;\n static const unsigned long long multiplier;\n static const unsigned long long addend;\n static const unsigned long long mask;\n static const int lim;\n\n long long nextBits(int bits) \n {\n if (bits <= 48)\n {\n seed = (seed * multiplier + addend) & mask;\n return (long long)(seed >> (48 - bits));\n }\n else\n {\n if (bits > 63)\n __testlib_fail(\"random_t::nextBits(int bits): n must be less than 64\");\n\n int lowerBitCount = (random_t::version == 0 ? 31 : 32);\n \n long long left = (nextBits(31) << 32);\n long long right = nextBits(lowerBitCount);\n \n return left ^ right;\n }\n }\n\npublic:\n static int version;\n\n /* New random_t with fixed seed. */\n random_t()\n : seed(3905348978240129619LL)\n {\n }\n\n /* Sets seed by command line. */\n void setSeed(int argc, char* argv[])\n {\n random_t p;\n\n seed = 3905348978240129619LL;\n for (int i = 1; i < argc; i++)\n {\n std::size_t le = std::strlen(argv[i]);\n for (std::size_t j = 0; j < le; j++)\n seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;\n seed += multiplier / addend;\n }\n\n seed = seed & mask;\n }\n\n /* Sets seed by given value. */ \n void setSeed(long long _seed)\n {\n _seed = (_seed ^ multiplier) & mask;\n seed = _seed;\n }\n\n#ifndef __BORLANDC__\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(const std::string& ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#else\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(std::string ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#endif\n\n /* Random value in range [0, n-1]. */\n int next(int n)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(int n): n must be positive\");\n\n if ((n & -n) == n) // n is a power of 2\n return (int)((n * (long long)nextBits(31)) >> 31);\n\n const long long limit = INT_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(31);\n } while (bits >= limit);\n\n return int(bits % n);\n }\n\n /* Random value in range [0, n-1]. */\n unsigned int next(unsigned int n)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::next(unsigned int n): n must be less INT_MAX\");\n return (unsigned int)next(int(n));\n }\n\n /* Random value in range [0, n-1]. */\n long long next(long long n) \n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(long long n): n must be positive\");\n\n const long long limit = __TESTLIB_LONGLONG_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(63);\n } while (bits >= limit);\n\n return bits % n;\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long long next(unsigned long long n)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long long n): n must be less LONGLONG_MAX\");\n return (unsigned long long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n long next(long n)\n {\n return (long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long next(unsigned long n)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long n): n must be less LONG_MAX\");\n return (unsigned long)next((unsigned long long)(n));\n }\n\n /* Returns random value in range [from,to]. */\n int next(int from, int to)\n {\n return int(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n unsigned int next(unsigned int from, unsigned int to)\n {\n return (unsigned int)(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n long long next(long long from, long long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long long next(unsigned long long from, unsigned long long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n long next(long from, long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long next(unsigned long from, unsigned long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long from, unsigned long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Random double value in range [0, 1). */\n double next() \n {\n long long left = ((long long)(nextBits(26)) << 27);\n long long right = nextBits(27);\n return (double)(left + right) / (double)(1LL << 53);\n }\n\n /* Random double value in range [0, n). */\n double next(double n)\n {\n return n * next();\n }\n\n /* Random double value in range [from, to). */\n double next(double from, double to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(double from, double to): from can't not exceed to\");\n return next(to - from) + from;\n }\n\n /* Returns random element from container. */\n template \n typename Container::value_type any(const Container& c)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Container& c): c.size() must be positive\");\n return *(c.begin() + next(size));\n }\n\n /* Returns random element from iterator range. */\n template \n typename Iter::value_type any(const Iter& begin, const Iter& end)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end): range must have positive length\");\n return *(begin + next(size));\n }\n\n /* Random string value by given pattern (see pattern documentation). */\n#ifdef __GNUC__\n __attribute__ ((format (printf, 2, 3)))\n#endif\n std::string next(const char* format, ...)\n {\n FMT_TO_RESULT(format, format, ptrn);\n return next(ptrn);\n }\n\n /* \n * Weighted next. If type == 0 than it is usual \"next()\".\n *\n * If type = 1, than it returns \"max(next(), next())\"\n * (the number of \"max\" functions equals to \"type\").\n *\n * If type < 0, than \"max\" function replaces with \"min\".\n */\n int wnext(int n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(int n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n int result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));\n\n return int(n * p);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n long long wnext(long long n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(long long n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n long long result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(int type)\n {\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return p;\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(double n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(double n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return n * result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return n * p;\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned int wnext(unsigned int n, int type)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::wnext(unsigned int n, int type): n must be less INT_MAX\");\n return (unsigned int)wnext(int(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long long wnext(unsigned long long n, int type)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX\");\n\n return (unsigned long long)wnext((long long)(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n long wnext(long n, int type)\n {\n return (long)wnext((long long)(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long wnext(unsigned long n, int type)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long n, int type): n must be less LONG_MAX\");\n\n return (unsigned long)wnext((unsigned long long)(n), type);\n }\n\n /* Returns weighted random value in range [from, to]. */\n int wnext(int from, int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(int from, int to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n int wnext(unsigned int from, unsigned int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to\");\n return int(wnext(to - from + 1, type) + from);\n }\n \n /* Returns weighted random value in range [from, to]. */\n long long wnext(long long from, long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long long from, long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long long wnext(unsigned long long from, unsigned long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n long wnext(long from, long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long from, long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long wnext(unsigned long from, unsigned long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random double value in range [from, to). */\n double wnext(double from, double to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(double from, double to, int type): from can't not exceed to\");\n return wnext(to - from, type) + from;\n }\n\n /* Returns weighted random element from container. */\n template \n typename Container::value_type wany(const Container& c, int type)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::wany(const Container& c, int type): c.size() must be positive\");\n return *(c.begin() + wnext(size, type));\n }\n\n /* Returns weighted random element from iterator range. */\n template \n typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length\");\n return *(begin + wnext(size, type));\n }\n\n template\n std::vector perm(T size, E first)\n {\n if (size <= 0)\n __testlib_fail(\"random_t::perm(T size, E first = 0): size must be positive\");\n std::vector p(size);\n for (T i = 0; i < size; i++)\n p[i] = first + i;\n if (size > 1)\n for (T i = 1; i < size; i++)\n std::swap(p[i], p[next(i + 1)]);\n return p;\n }\n\n template\n std::vector perm(T size)\n {\n return perm(size, T(0));\n }\n};\n\nconst int random_t::lim = 25;\nconst unsigned long long random_t::multiplier = 0x5DEECE66DLL;\nconst unsigned long long random_t::addend = 0xBLL;\nconst unsigned long long random_t::mask = (1LL << 48) - 1;\nint random_t::version = -1;\n\n/* Pattern implementation */\nbool pattern::matches(const std::string& s) const\n{\n return matches(s, 0);\n}\n\nstatic bool __pattern_isSlash(const std::string& s, size_t pos)\n{\n return s[pos] == '\\\\';\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)\n{\n if (pos >= s.length())\n return false;\n\n int slashes = 0;\n\n int before = int(pos) - 1;\n while (before >= 0 && s[before] == '\\\\')\n before--, slashes++;\n\n return slashes % 2 == 0 && s[pos] == value;\n}\n\nstatic char __pattern_getChar(const std::string& s, size_t& pos)\n{\n if (__pattern_isSlash(s, pos))\n pos += 2;\n else\n pos++;\n\n return s[pos - 1];\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector chars)\n{\n int result = 0;\n\n while (pos < s.length())\n {\n char c = s[pos++];\n if (!std::binary_search(chars.begin(), chars.end(), c))\n break;\n else\n result++;\n }\n\n return result;\n}\n\nstd::string pattern::src() const\n{\n return s;\n}\n\nbool pattern::matches(const std::string& s, size_t pos) const\n{\n std::string result;\n\n if (to > 0)\n {\n int size = __pattern_greedyMatch(s, pos, chars);\n if (size < from)\n return false;\n if (size > to)\n size = to;\n pos += size;\n }\n\n if (children.size() > 0)\n {\n for (size_t child = 0; child < children.size(); child++)\n if (children[child].matches(s, pos))\n return true;\n return false;\n }\n else\n return pos == s.length();\n}\n\nstd::string pattern::next(random_t& rnd) const\n{\n std::string result;\n result.reserve(20);\n\n if (to == INT_MAX)\n __testlib_fail(\"pattern::next(random_t& rnd): can't process character '*' for generation\");\n\n if (to > 0)\n {\n int count = rnd.next(to - from + 1) + from;\n for (int i = 0; i < count; i++)\n result += chars[rnd.next(int(chars.size()))];\n }\n\n if (children.size() > 0)\n {\n int child = rnd.next(int(children.size()));\n result += children[child].next(rnd);\n }\n\n return result;\n}\n\nstatic void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)\n{\n if (pos >= s.length())\n {\n from = to = 1;\n return;\n }\n \n if (__pattern_isCommandChar(s, pos, '{'))\n {\n std::vector parts;\n std::string part;\n\n pos++;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))\n {\n if (__pattern_isCommandChar(s, pos, ','))\n parts.push_back(part), part = \"\", pos++;\n else\n part += __pattern_getChar(s, pos);\n }\n\n if (part != \"\")\n parts.push_back(part);\n\n if (!__pattern_isCommandChar(s, pos, '}'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (parts.size() < 1 || parts.size() > 2)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector numbers;\n\n for (size_t i = 0; i < parts.size(); i++)\n {\n if (parts[i].length() == 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n int number;\n if (std::sscanf(parts[i].c_str(), \"%d\", &number) != 1)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n numbers.push_back(number);\n }\n\n if (numbers.size() == 1)\n from = to = numbers[0];\n else\n from = numbers[0], to = numbers[1];\n\n if (from > to)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n }\n else\n {\n if (__pattern_isCommandChar(s, pos, '?'))\n {\n from = 0, to = 1, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '*'))\n {\n from = 0, to = INT_MAX, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '+'))\n {\n from = 1, to = INT_MAX, pos++;\n return;\n }\n \n from = to = 1;\n }\n}\n\nstatic std::vector __pattern_scanCharSet(const std::string& s, size_t& pos)\n{\n if (pos >= s.length())\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector result;\n\n if (__pattern_isCommandChar(s, pos, '['))\n {\n pos++;\n bool negative = __pattern_isCommandChar(s, pos, '^');\n\n char prev = 0;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))\n {\n if (__pattern_isCommandChar(s, pos, '-') && prev != 0)\n {\n pos++;\n\n if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']'))\n {\n result.push_back(prev);\n prev = '-';\n continue;\n }\n\n char next = __pattern_getChar(s, pos);\n if (prev > next)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n for (char c = prev; c != next; c++)\n result.push_back(c);\n result.push_back(next);\n\n prev = 0;\n }\n else\n {\n if (prev != 0)\n result.push_back(prev);\n prev = __pattern_getChar(s, pos);\n }\n }\n\n if (prev != 0)\n result.push_back(prev);\n\n if (!__pattern_isCommandChar(s, pos, ']'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (negative)\n {\n std::sort(result.begin(), result.end());\n std::vector actuals;\n for (int code = 0; code < 255; code++)\n {\n char c = char(code);\n if (!std::binary_search(result.begin(), result.end(), c))\n actuals.push_back(c);\n }\n result = actuals;\n }\n\n std::sort(result.begin(), result.end());\n }\n else\n result.push_back(__pattern_getChar(s, pos));\n\n return result;\n}\n\npattern::pattern(std::string s): s(s), from(0), to(0)\n{\n std::string t;\n for (size_t i = 0; i < s.length(); i++)\n if (!__pattern_isCommandChar(s, i, ' '))\n t += s[i];\n s = t;\n\n int opened = 0;\n int firstClose = -1;\n std::vector seps;\n\n for (size_t i = 0; i < s.length(); i++)\n {\n if (__pattern_isCommandChar(s, i, '('))\n {\n opened++;\n continue;\n }\n\n if (__pattern_isCommandChar(s, i, ')'))\n {\n opened--;\n if (opened == 0 && firstClose == -1)\n firstClose = int(i);\n continue;\n }\n \n if (opened < 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (__pattern_isCommandChar(s, i, '|') && opened == 0)\n seps.push_back(int(i));\n }\n\n if (opened != 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (seps.size() == 0 && firstClose + 1 == (int)s.length() \n && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))\n {\n children.push_back(pattern(s.substr(1, s.length() - 2)));\n }\n else\n {\n if (seps.size() > 0)\n {\n seps.push_back(int(s.length()));\n int last = 0;\n\n for (size_t i = 0; i < seps.size(); i++)\n {\n children.push_back(pattern(s.substr(last, seps[i] - last)));\n last = seps[i] + 1;\n }\n }\n else\n {\n size_t pos = 0;\n chars = __pattern_scanCharSet(s, pos);\n __pattern_scanCounts(s, pos, from, to);\n if (pos < s.length())\n children.push_back(pattern(s.substr(pos)));\n }\n }\n}\n/* End of pattern implementation */\n\ntemplate \ninline bool isEof(C c)\n{\n return c == EOFC;\n}\n\ntemplate \ninline bool isEoln(C c)\n{\n return (c == LF || c == CR);\n}\n\ntemplate\ninline bool isBlanks(C c)\n{\n return (c == LF || c == CR || c == SPACE || c == TAB);\n}\n\nenum TMode\n{\n _input, _output, _answer\n};\n\n/* Outcomes 6-15 are reserved for future use. */\nenum TResult\n{\n _ok = 0,\n _wa = 1,\n _pe = 2,\n _fail = 3,\n _dirt = 4,\n _points = 5,\n _unexpected_eof = 8,\n _sv = 10,\n _pv = 11,\n _partially = 16\n};\n\nenum TTestlibMode\n{\n _unknown, _checker, _validator, _generator, _interactor\n};\n\n#define _pc(exitCode) (TResult(_partially + (exitCode)))\n\n/* Outcomes 6-15 are reserved for future use. */\nconst std::string outcomes[] = {\n \"accepted\",\n \"wrong-answer\",\n \"presentation-error\",\n \"fail\",\n \"fail\",\n#ifndef PCMS2\n \"points\",\n#else\n \"relative-scoring\",\n#endif\n \"reserved\",\n \"reserved\",\n \"unexpected-eof\",\n \"reserved\",\n \"security-violation\",\n \"protocol-violation\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"partially-correct\"\n};\n\nclass InputStreamReader\n{\npublic:\n virtual int curChar() = 0; \n virtual int nextChar() = 0; \n virtual void skipChar() = 0;\n virtual void unreadChar(int c) = 0;\n virtual std::string getName() = 0;\n virtual bool eof() = 0;\n virtual void close() = 0;\n virtual int getLine() = 0;\n virtual ~InputStreamReader() = 0;\n};\n\nInputStreamReader::~InputStreamReader()\n{\n // No operations.\n}\n\nclass StringInputStreamReader: public InputStreamReader\n{\nprivate:\n std::string s;\n size_t pos;\n\npublic:\n StringInputStreamReader(const std::string& content): s(content), pos(0)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (pos >= s.length())\n return EOFC;\n else\n return s[pos];\n }\n\n int nextChar()\n {\n if (pos >= s.length())\n {\n pos++;\n return EOFC;\n }\n else\n return s[pos++];\n }\n\n void skipChar()\n {\n pos++;\n }\n\n void unreadChar(int c)\n { \n if (pos == 0)\n __testlib_fail(\"FileFileInputStreamReader::unreadChar(int): pos == 0.\");\n pos--;\n if (pos < s.length())\n s[pos] = char(c);\n }\n\n std::string getName()\n {\n return __testlib_part(s);\n }\n\n int getLine()\n {\n return -1;\n }\n\n bool eof()\n {\n return pos >= s.length();\n }\n\n void close()\n {\n // No operations.\n }\n};\n\nclass FileInputStreamReader: public InputStreamReader\n{\nprivate:\n std::FILE* file;\n std::string name;\n int line;\n std::vector undoChars;\n\n inline int postprocessGetc(int getcResult)\n {\n if (getcResult != EOF)\n return getcResult;\n else\n return EOFC;\n }\n\n int getc(FILE* file)\n {\n int c;\n if (undoChars.empty())\n c = ::getc(file);\n else\n {\n c = undoChars.back();\n undoChars.pop_back();\n }\n\n if (c == LF)\n line++;\n return c;\n }\n\n int ungetc(int c/*, FILE* file*/)\n {\n if (c == LF)\n line--;\n undoChars.push_back(c);\n return c;\n }\n\npublic:\n FileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (feof(file))\n return EOFC;\n else\n {\n int c = getc(file);\n ungetc(c/*, file*/);\n return postprocessGetc(c);\n }\n }\n\n int nextChar()\n {\n if (feof(file))\n return EOFC;\n else\n return postprocessGetc(getc(file));\n }\n\n void skipChar()\n {\n getc(file);\n }\n\n void unreadChar(int c)\n { \n ungetc(c/*, file*/);\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n\n bool eof()\n {\n if (NULL == file || feof(file))\n return true;\n else\n {\n int c = nextChar();\n if (c == EOFC || (c == EOF && feof(file)))\n return true;\n unreadChar(c);\n return false;\n }\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nclass BufferedFileInputStreamReader: public InputStreamReader\n{\nprivate:\n static const size_t BUFFER_SIZE;\n static const size_t MAX_UNREAD_COUNT; \n \n std::FILE* file;\n char* buffer;\n bool* isEof;\n int bufferPos;\n size_t bufferSize;\n\n std::string name;\n int line;\n\n bool refill()\n {\n if (NULL == file)\n __testlib_fail(\"BufferedFileInputStreamReader: file == NULL (\" + getName() + \")\");\n\n if (bufferPos >= int(bufferSize))\n {\n size_t readSize = fread(\n buffer + MAX_UNREAD_COUNT,\n 1,\n BUFFER_SIZE - MAX_UNREAD_COUNT,\n file\n );\n\n if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT\n && ferror(file))\n __testlib_fail(\"BufferedFileInputStreamReader: unable to read (\" + getName() + \")\");\n\n bufferSize = MAX_UNREAD_COUNT + readSize;\n bufferPos = int(MAX_UNREAD_COUNT);\n std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);\n\n return readSize > 0;\n }\n else\n return true;\n }\n\n char increment()\n {\n char c;\n if ((c = buffer[bufferPos++]) == LF)\n line++;\n return c;\n }\n\npublic:\n BufferedFileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n buffer = new char[BUFFER_SIZE];\n isEof = new bool[BUFFER_SIZE];\n bufferSize = MAX_UNREAD_COUNT;\n bufferPos = int(MAX_UNREAD_COUNT);\n }\n\n ~BufferedFileInputStreamReader()\n {\n if (NULL != buffer)\n {\n delete[] buffer;\n buffer = NULL;\n }\n if (NULL != isEof)\n {\n delete[] isEof;\n isEof = NULL;\n }\n }\n\n int curChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : buffer[bufferPos];\n }\n\n int nextChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : increment();\n }\n\n void skipChar()\n {\n increment();\n }\n\n void unreadChar(int c)\n { \n bufferPos--;\n if (bufferPos < 0)\n __testlib_fail(\"BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0\");\n isEof[bufferPos] = (c == EOFC);\n buffer[bufferPos] = char(c);\n if (c == LF)\n line--;\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n \n bool eof()\n {\n return !refill() || EOFC == curChar();\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nconst size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;\nconst size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2; \n\n/*\n * Streams to be used for reading data in checkers or validators.\n * Each read*() method moves pointer to the next character after the\n * read value.\n */\nstruct InStream\n{\n /* Do not use them. */\n InStream();\n ~InStream();\n\n /* Wrap std::string with InStream. */\n InStream(const InStream& baseStream, std::string content);\n\n InputStreamReader* reader;\n int lastLine;\n\n std::string name;\n TMode mode;\n bool opened;\n bool stdfile;\n bool strict;\n\n int wordReserveSize;\n std::string _tmpReadToken;\n\n int readManyIteration;\n size_t maxFileSize;\n size_t maxTokenLength;\n size_t maxMessageLength;\n\n void init(std::string fileName, TMode mode);\n void init(std::FILE* f, TMode mode);\n\n /* Moves stream pointer to the first non-white-space character or EOF. */ \n void skipBlanks();\n \n /* Returns current character in the stream. Doesn't remove it from stream. */\n char curChar();\n /* Moves stream pointer one character forward. */\n void skipChar();\n /* Returns current character and moves pointer one character forward. */\n char nextChar();\n \n /* Returns current character and moves pointer one character forward. */\n char readChar();\n /* As \"readChar()\" but ensures that the result is equal to given parameter. */\n char readChar(char c);\n /* As \"readChar()\" but ensures that the result is equal to the space (code=32). */\n char readSpace();\n /* Puts back the character into the stream. */\n void unreadChar(char c);\n\n /* Reopens stream, you should not use it. */\n void reset(std::FILE* file = NULL);\n /* Checks that current position is EOF. If not it doesn't move stream pointer. */\n bool eof();\n /* Moves pointer to the first non-white-space character and calls \"eof()\". */\n bool seekEof();\n\n /* \n * Checks that current position contains EOLN. \n * If not it doesn't move stream pointer. \n * In strict mode expects \"#13#10\" for windows or \"#10\" for other platforms.\n */\n bool eoln();\n /* Moves pointer to the first non-space and non-tab character and calls \"eoln()\". */\n bool seekEoln();\n\n /* Moves stream pointer to the first character of the next line (if exists). */\n void nextLine();\n\n /* \n * Reads new token. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n std::string readWord();\n /* The same as \"readWord()\", it is preffered to use \"readToken()\". */\n std::string readToken();\n /* The same as \"readWord()\", but ensures that token matches to given pattern. */\n std::string readWord(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readWord(const pattern& p, const std::string& variableName = \"\");\n std::vector readWords(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readWords(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n /* The same as \"readToken()\", but ensures that token matches to given pattern. */\n std::string readToken(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readToken(const pattern& p, const std::string& variableName = \"\");\n std::vector readTokens(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readTokens(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n\n void readWordTo(std::string& result);\n void readWordTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n void readTokenTo(std::string& result);\n void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads new long long value. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n long long readLong();\n unsigned long long readUnsignedLong();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInteger();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInt();\n\n /* As \"readLong()\" but ensures that value in the range [minv,maxv]. */\n long long readLong(long long minv, long long maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of long longs. */\n std::vector readLongs(int size, long long minv, long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n unsigned long long readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* As \"readInteger()\" but ensures that value in the range [minv,maxv]. */\n int readInteger(int minv, int maxv, const std::string& variableName = \"\");\n /* As \"readInt()\" but ensures that value in the range [minv,maxv]. */\n int readInt(int minv, int maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of integers. */\n std::vector readIntegers(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* Reads space-separated sequence of integers. */\n std::vector readInts(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readReal();\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readDouble();\n \n /* As \"readReal()\" but ensures that value in the range [minv,maxv]. */\n double readReal(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readReals(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* As \"readDouble()\" but ensures that value in the range [minv,maxv]. */\n double readDouble(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readDoubles(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n \n /* \n * As \"readReal()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * As \"readDouble()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n \n /* As readLine(). */\n std::string readString();\n /* Read many lines. */\n std::vector readStrings(int size, int indexBase = 1);\n /* See readLine(). */\n void readStringTo(std::string& result);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readStrings(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readStrings(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads line from the current position to EOLN or EOF. Moves stream pointer to \n * the first character of the new line (if possible). \n */\n std::string readLine();\n /* Read many lines. */\n std::vector readLines(int size, int indexBase = 1);\n /* See readLine(). */\n void readLineTo(std::string& result);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readLines(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readLines(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* Reads EOLN or fails. Use it in validators. Calls \"eoln()\" method internally. */\n void readEoln();\n /* Reads EOF or fails. Use it in validators. Calls \"eof()\" method internally. */\n void readEof();\n\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quit(TResult result, const char* msg);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quitf(TResult result, const char* msg, ...);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quits(TResult result, std::string msg);\n\n /* \n * Checks condition and aborts a program if codition is false.\n * Returns _wa for ouf and _fail on any other streams.\n */\n #ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n #endif\n void ensuref(bool cond, const char* format, ...);\n void __testlib_ensure(bool cond, std::string message);\n\n void close();\n\n const static int NO_INDEX = INT_MAX;\n\n const static WORD LightGray = 0x07; \n const static WORD LightRed = 0x0c; \n const static WORD LightCyan = 0x0b; \n const static WORD LightGreen = 0x0a; \n const static WORD LightYellow = 0x0e; \n const static WORD LightMagenta = 0x0d; \n\n static void textColor(WORD color);\n static void quitscr(WORD color, const char* msg);\n static void quitscrS(WORD color, std::string msg);\n void xmlSafeWrite(std::FILE * file, const char* msg);\n\n void readSecret(\n std::string secret,\n TResult mismatchResult = _pv,\n std::string mismatchMessage = \"Secret mismatch\",\n std::string eofMessage = \"Unexpected end of file - secret expected\");\n void readGraderResult();\n\nprivate:\n InStream(const InStream&);\n InStream& operator =(const InStream&);\n void quitByGraderResult(TResult result, std::string defaultMessage);\n};\n\nInStream inf;\nInStream ouf;\nInStream ans;\nbool appesMode;\nstd::string resultName;\nstd::string checkerName = \"untitled checker\";\nrandom_t rnd;\nTTestlibMode testlibMode = _unknown;\ndouble __testlib_points = std::numeric_limits::infinity();\n\nstruct ValidatorBoundsHit\n{\n static const double EPS;\n bool minHit;\n bool maxHit;\n\n ValidatorBoundsHit(bool minHit = false, bool maxHit = false): minHit(minHit), maxHit(maxHit)\n {\n };\n\n ValidatorBoundsHit merge(const ValidatorBoundsHit& validatorBoundsHit)\n {\n return ValidatorBoundsHit(\n __testlib_max(minHit, validatorBoundsHit.minHit),\n __testlib_max(maxHit, validatorBoundsHit.maxHit)\n );\n }\n};\n\nconst double ValidatorBoundsHit::EPS = 1E-12;\n\nclass Validator\n{\nprivate:\n std::string _testset;\n std::string _group;\n std::string _testOverviewLogFileName;\n std::map _boundsHitByVariableName;\n std::set _features;\n std::set _hitFeatures;\n\n bool isVariableNameBoundsAnalyzable(const std::string& variableName)\n {\n for (size_t i = 0; i < variableName.length(); i++)\n if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')\n return false;\n return true;\n }\n\n bool isFeatureNameAnalyzable(const std::string& featureName)\n {\n for (size_t i = 0; i < featureName.length(); i++)\n if (featureName[i] < ' ')\n return false;\n return true;\n }\npublic:\n Validator(): _testset(\"tests\"), _group()\n {\n }\n\n std::string testset() const\n {\n return _testset;\n }\n \n std::string group() const\n {\n return _group;\n }\n\n std::string testOverviewLogFileName() const\n {\n return _testOverviewLogFileName;\n }\n \n void setTestset(const char* const testset)\n {\n _testset = testset;\n }\n\n void setGroup(const char* const group)\n {\n _group = group;\n }\n\n void setTestOverviewLogFileName(const char* const testOverviewLogFileName)\n {\n _testOverviewLogFileName = testOverviewLogFileName;\n }\n\n void addBoundsHit(const std::string& variableName, ValidatorBoundsHit boundsHit)\n {\n if (isVariableNameBoundsAnalyzable(variableName))\n {\n _boundsHitByVariableName[variableName]\n = boundsHit.merge(_boundsHitByVariableName[variableName]);\n }\n }\n\n std::string getBoundsHitLog()\n {\n std::string result;\n for (std::map::iterator i = _boundsHitByVariableName.begin();\n i != _boundsHitByVariableName.end();\n i++)\n {\n result += \"\\\"\" + i->first + \"\\\":\";\n if (i->second.minHit)\n result += \" min-value-hit\";\n if (i->second.maxHit)\n result += \" max-value-hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n std::string getFeaturesLog()\n {\n std::string result;\n for (std::set::iterator i = _features.begin();\n i != _features.end();\n i++)\n {\n result += \"feature \\\"\" + *i + \"\\\":\";\n if (_hitFeatures.count(*i))\n result += \" hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n void writeTestOverviewLog()\n {\n if (!_testOverviewLogFileName.empty())\n {\n std::string fileName(_testOverviewLogFileName);\n _testOverviewLogFileName = \"\";\n FILE* testOverviewLogFile = fopen(fileName.c_str(), \"w\");\n if (NULL == testOverviewLogFile)\n __testlib_fail(\"Validator::writeTestOverviewLog: can't test overview log to (\" + fileName + \")\");\n fprintf(testOverviewLogFile, \"%s%s\", getBoundsHitLog().c_str(), getFeaturesLog().c_str());\n if (fclose(testOverviewLogFile))\n __testlib_fail(\"Validator::writeTestOverviewLog: can't close test overview log file (\" + fileName + \")\");\n }\n }\n\n void addFeature(const std::string& feature)\n {\n if (_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" registered twice.\");\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n _features.insert(feature);\n }\n\n void feature(const std::string& feature)\n {\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n if (!_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" didn't registered via addFeature(feature).\");\n\n _hitFeatures.insert(feature);\n }\n} validator;\n\nstruct TestlibFinalizeGuard\n{\n static bool alive;\n int quitCount, readEofCount;\n\n TestlibFinalizeGuard() : quitCount(0), readEofCount(0)\n {\n // No operations.\n }\n\n ~TestlibFinalizeGuard()\n {\n bool _alive = alive;\n alive = false;\n\n if (_alive)\n {\n if (testlibMode == _checker && quitCount == 0)\n __testlib_fail(\"Checker must end with quit or quitf call.\");\n\n if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)\n __testlib_fail(\"Validator must end with readEof call.\");\n }\n\n validator.writeTestOverviewLog();\n }\n};\n\nbool TestlibFinalizeGuard::alive = true;\nTestlibFinalizeGuard testlibFinalizeGuard;\n\n/*\n * Call it to disable checks on finalization.\n */\nvoid disableFinalizeGuard()\n{\n TestlibFinalizeGuard::alive = false;\n}\n\n/* Interactor streams.\n */\nstd::fstream tout;\n\n/* implementation\n */\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate\nstatic std::string vtos(const T& t, std::true_type)\n{ \n if (t == 0)\n return \"0\";\n else\n {\n T n(t);\n bool negative = n < 0;\n std::string s;\n while (n != 0) {\n T digit = n % 10;\n if (digit < 0)\n digit = -digit;\n s += char('0' + digit);\n n /= 10;\n }\n std::reverse(s.begin(), s.end());\n return negative ? \"-\" + s : s;\n }\n}\n\ntemplate\nstatic std::string vtos(const T& t, std::false_type)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n\ntemplate \nstatic std::string vtos(const T& t)\n{\n return vtos(t, std::is_integral());\n}\n#else\ntemplate\nstatic std::string vtos(const T& t)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n#endif\n\ntemplate \nstatic std::string toString(const T& t)\n{\n return vtos(t);\n}\n\nInStream::InStream()\n{\n reader = NULL;\n lastLine = -1;\n name = \"\";\n mode = _input;\n strict = false;\n stdfile = false;\n wordReserveSize = 4;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::InStream(const InStream& baseStream, std::string content)\n{\n reader = new StringInputStreamReader(content);\n lastLine = -1;\n opened = true;\n strict = baseStream.strict;\n mode = baseStream.mode;\n name = \"based on \" + baseStream.name;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::~InStream()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\nint resultExitCode(TResult r)\n{\n if (testlibMode == _checker)\n return 0;//CMS Checkers should always finish with zero exit code.\n if (r == _ok)\n return OK_EXIT_CODE;\n if (r == _wa)\n return WA_EXIT_CODE;\n if (r == _pe)\n return PE_EXIT_CODE;\n if (r == _fail)\n return FAIL_EXIT_CODE;\n if (r == _dirt)\n return DIRT_EXIT_CODE;\n if (r == _points)\n return POINTS_EXIT_CODE;\n if (r == _unexpected_eof)\n#ifdef ENABLE_UNEXPECTED_EOF\n return UNEXPECTED_EOF_EXIT_CODE;\n#else\n return PE_EXIT_CODE;\n#endif\n if (r == _sv)\n return SV_EXIT_CODE;\n if (r == _pv)\n return PV_EXIT_CODE;\n if (r >= _partially)\n return PC_BASE_EXIT_CODE + (r - _partially);\n return FAIL_EXIT_CODE;\n}\n\nvoid InStream::textColor(\n#if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)) && defined(__GNUC__)\n __attribute__((unused)) \n#endif\n WORD color\n)\n{\n#if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)\n HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(handle, color);\n#endif\n#if !defined(ON_WINDOWS) && defined(__GNUC__)\n if (isatty(2))\n {\n switch (color)\n {\n case LightRed:\n fprintf(stderr, \"\\033[1;31m\");\n break;\n case LightCyan:\n fprintf(stderr, \"\\033[1;36m\");\n break;\n case LightGreen:\n fprintf(stderr, \"\\033[1;32m\");\n break;\n case LightYellow:\n fprintf(stderr, \"\\033[1;33m\");\n break;\n case LightMagenta:\n fprintf(stderr, \"\\033[1;35m\");\n break;\n case LightGray:\n default:\n fprintf(stderr, \"\\033[0m\");\n }\n }\n#endif\n}\n\nNORETURN void halt(int exitCode)\n{\n callHaltListeners();\n#ifdef FOOTER\n InStream::textColor(InStream::LightGray);\n std::fprintf(stderr, \"Checker: \\\"%s\\\"\\n\", checkerName.c_str());\n std::fprintf(stderr, \"Exit code: %d\\n\", exitCode);\n InStream::textColor(InStream::LightGray);\n#endif\n std::exit(exitCode);\n}\n\nstatic bool __testlib_shouldCheckDirt(TResult result)\n{\n return result == _ok || result == _points || result >= _partially;\n}\n\n\nstd::string RESULT_MESSAGE_CORRECT = \"Output is correct\";\nstd::string RESULT_MESSAGE_PARTIALLY_CORRECT = \"Output is partially correct\";\nstd::string RESULT_MESSAGE_WRONG = \"Output isn't correct\";\nstd::string RESULT_MESSAGE_SECURITY_VIOLATION = \"Security Violation\";\nstd::string RESULT_MESSAGE_PROTOCOL_VIOLATION = \"Protocol Violation\";\nstd::string RESULT_MESSAGE_FAIL = \"Judge Failure; Contact staff!\";\n\nNORETURN void InStream::quit(TResult result, const char* msg)\n{\n if (TestlibFinalizeGuard::alive)\n testlibFinalizeGuard.quitCount++;\n\n // You can change maxMessageLength.\n // Example: 'inf.maxMessageLength = 1024 * 1024;'.\n if (strlen(msg) > maxMessageLength)\n {\n std::string message(msg);\n std::string warn = \"message length exceeds \" + vtos(maxMessageLength)\n + \", the message is truncated: \";\n msg = (warn + message.substr(0, maxMessageLength - warn.length())).c_str();\n }\n\n#ifndef ENABLE_UNEXPECTED_EOF\n if (result == _unexpected_eof)\n result = _pe;\n#endif\n\n if (mode != _output && result != _fail)\n {\n if (mode == _input && testlibMode == _validator && lastLine != -1)\n quits(_fail, std::string(msg) + \" (\" + name + \", line \" + vtos(lastLine) + \")\");\n else\n quits(_fail, std::string(msg) + \" (\" + name + \")\");\n }\n\n std::FILE * resultFile;\n std::string errorName;\n \n if (__testlib_shouldCheckDirt(result))\n {\n if (testlibMode != _interactor && !ouf.seekEof())\n quit(_dirt, \"Extra information in the output file\");\n }\n\n int pctype = result - _partially;\n bool isPartial = false;\n\n if (testlibMode == _checker) {\n WORD color;\n std::string pointsStr = \"0\";\n switch (result)\n {\n case _ok:\n pointsStr = format(\"%d\", 1);\n color = LightGreen;\n errorName = RESULT_MESSAGE_CORRECT;\n break;\n case _wa:\n case _pe:\n case _dirt:\n case _unexpected_eof:\n color = LightRed;\n errorName = RESULT_MESSAGE_WRONG;\n break;\n case _fail:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_FAIL;\n break;\n case _sv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_SECURITY_VIOLATION;\n break;\n case _pv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_PROTOCOL_VIOLATION;\n break;\n case _points:\n if (__testlib_points < 1e-5)\n pointsStr = \"0.00001\"; // Prevent zero scores in CMS as zero is considered wrong\n else if (__testlib_points < 0.0001)\n pointsStr = format(\"%lf\", __testlib_points); // Prevent rounding the numbers below 0.0001\n else\n pointsStr = format(\"%.4lf\", __testlib_points);\n color = LightYellow;\n errorName = RESULT_MESSAGE_PARTIALLY_CORRECT;\n break;\n default:\n if (result >= _partially)\n quit(_fail, \"testlib partially mode not supported\");\n else\n quit(_fail, \"What is the code ??? \");\n } \n std::fprintf(stdout, \"%s\\n\", pointsStr.c_str());\n quitscrS(color, errorName);\n std::fprintf(stderr, \"\\n\");\n } else {\n switch (result)\n {\n case _ok:\n errorName = \"ok \";\n quitscrS(LightGreen, errorName);\n break;\n case _wa:\n errorName = \"wrong answer \";\n quitscrS(LightRed, errorName);\n break;\n case _pe:\n errorName = \"wrong output format \";\n quitscrS(LightRed, errorName);\n break;\n case _fail:\n errorName = \"FAIL \";\n quitscrS(LightRed, errorName);\n break;\n case _dirt:\n errorName = \"wrong output format \";\n quitscrS(LightCyan, errorName);\n result = _pe;\n break;\n case _points:\n errorName = \"points \";\n quitscrS(LightYellow, errorName);\n break;\n case _unexpected_eof:\n errorName = \"unexpected eof \";\n quitscrS(LightCyan, errorName);\n break;\n default:\n if (result >= _partially)\n {\n errorName = format(\"partially correct (%d) \", pctype);\n isPartial = true;\n quitscrS(LightYellow, errorName);\n }\n else\n quit(_fail, \"What is the code ??? \");\n }\n }\n\n if (resultName != \"\")\n {\n resultFile = std::fopen(resultName.c_str(), \"w\");\n if (resultFile == NULL)\n quit(_fail, \"Can not write to the result file\");\n if (appesMode)\n {\n std::fprintf(resultFile, \"\");\n if (isPartial)\n std::fprintf(resultFile, \"\", outcomes[(int)_partially].c_str(), pctype);\n else\n {\n if (result != _points)\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str());\n else\n {\n if (__testlib_points == std::numeric_limits::infinity())\n quit(_fail, \"Expected points, but infinity found\");\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", __testlib_points));\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str(), stringPoints.c_str());\n }\n }\n xmlSafeWrite(resultFile, msg);\n std::fprintf(resultFile, \"\\n\");\n }\n else\n std::fprintf(resultFile, \"%s\", msg);\n if (NULL == resultFile || fclose(resultFile) != 0)\n quit(_fail, \"Can not write to the result file\");\n }\n\n quitscr(LightGray, msg);\n std::fprintf(stderr, \"\\n\");\n\n inf.close();\n ouf.close();\n ans.close();\n if (tout.is_open())\n tout.close();\n\n textColor(LightGray);\n\n if (resultName != \"\")\n std::fprintf(stderr, \"See file to check exit message\\n\");\n\n halt(resultExitCode(result));\n}\n\n#ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n#endif\nNORETURN void InStream::quitf(TResult result, const char* msg, ...)\n{\n FMT_TO_RESULT(msg, msg, message);\n InStream::quit(result, message.c_str());\n}\n\nNORETURN void InStream::quits(TResult result, std::string msg)\n{\n InStream::quit(result, msg.c_str());\n}\n\nvoid InStream::xmlSafeWrite(std::FILE * file, const char* msg)\n{\n size_t lmsg = strlen(msg);\n for (size_t i = 0; i < lmsg; i++)\n {\n if (msg[i] == '&')\n {\n std::fprintf(file, \"%s\", \"&\");\n continue;\n }\n if (msg[i] == '<')\n {\n std::fprintf(file, \"%s\", \"<\");\n continue;\n }\n if (msg[i] == '>')\n {\n std::fprintf(file, \"%s\", \">\");\n continue;\n }\n if (msg[i] == '\"')\n {\n std::fprintf(file, \"%s\", \""\");\n continue;\n }\n if (0 <= msg[i] && msg[i] <= 31)\n {\n std::fprintf(file, \"%c\", '.');\n continue;\n }\n std::fprintf(file, \"%c\", msg[i]);\n }\n}\n\nvoid InStream::quitscrS(WORD color, std::string msg)\n{\n quitscr(color, msg.c_str());\n}\n\nvoid InStream::quitscr(WORD color, const char* msg)\n{\n if (resultName == \"\")\n {\n textColor(color);\n std::fprintf(stderr, \"%s\", msg);\n textColor(LightGray);\n }\n}\n\nvoid InStream::reset(std::FILE* file)\n{\n if (opened && stdfile)\n quit(_fail, \"Can't reset standard handle\");\n\n if (opened)\n close();\n\n if (!stdfile)\n if (NULL == (file = std::fopen(name.c_str(), \"rb\")))\n {\n if (mode == _output)\n quits(_pe, std::string(\"Output file not found: \\\"\") + name + \"\\\"\");\n \n if (mode == _answer)\n quits(_fail, std::string(\"Answer file not found: \\\"\") + name + \"\\\"\");\n }\n\n if (NULL != file)\n {\n opened = true;\n\n __testlib_set_binary(file);\n\n if (stdfile)\n reader = new FileInputStreamReader(file, name);\n else\n reader = new BufferedFileInputStreamReader(file, name);\n }\n else\n {\n opened = false;\n reader = NULL;\n }\n}\n\nvoid InStream::init(std::string fileName, TMode mode)\n{\n opened = false;\n name = fileName;\n stdfile = false;\n this->mode = mode;\n \n std::ifstream stream;\n stream.open(fileName.c_str(), std::ios::in);\n if (stream.is_open())\n {\n std::streampos start = stream.tellg();\n stream.seekg(0, std::ios::end);\n std::streampos end = stream.tellg();\n size_t fileSize = size_t(end - start);\n stream.close();\n \n // You can change maxFileSize.\n // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'.\n if (fileSize > maxFileSize)\n quitf(_pe, \"File size exceeds %d bytes, size is %d\", int(maxFileSize), int(fileSize));\n }\n\n reset();\n}\n\nvoid InStream::init(std::FILE* f, TMode mode)\n{\n opened = false;\n name = \"untitled\";\n this->mode = mode;\n \n if (f == stdin)\n name = \"stdin\", stdfile = true;\n if (f == stdout)\n name = \"stdout\", stdfile = true;\n if (f == stderr)\n name = \"stderr\", stdfile = true;\n\n reset(f);\n}\n\nchar InStream::curChar()\n{\n return char(reader->curChar());\n}\n\nchar InStream::nextChar()\n{\n return char(reader->nextChar());\n}\n\nchar InStream::readChar()\n{\n return nextChar();\n}\n\nchar InStream::readChar(char c)\n{\n lastLine = reader->getLine();\n char found = readChar();\n if (c != found)\n {\n if (!isEoln(found))\n quit(_pe, (\"Unexpected character '\" + std::string(1, found) + \"', but '\" + std::string(1, c) + \"' expected\").c_str());\n else\n quit(_pe, (\"Unexpected character \" + (\"#\" + vtos(int(found))) + \", but '\" + std::string(1, c) + \"' expected\").c_str());\n }\n return found;\n}\n\nchar InStream::readSpace()\n{\n return readChar(' ');\n}\n\nvoid InStream::unreadChar(char c)\n{\n reader->unreadChar(c);\n}\n\nvoid InStream::skipChar()\n{\n reader->skipChar();\n}\n\nvoid InStream::skipBlanks()\n{\n while (isBlanks(reader->curChar()))\n reader->skipChar();\n}\n\nstd::string InStream::readWord()\n{\n readWordTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nvoid InStream::readWordTo(std::string& result)\n{\n if (!strict)\n skipBlanks();\n\n lastLine = reader->getLine();\n int cur = reader->nextChar();\n\n if (cur == EOFC)\n quit(_unexpected_eof, \"Unexpected end of file - token expected\");\n\n if (isBlanks(cur))\n quit(_pe, \"Unexpected white-space - token expected\");\n\n result.clear();\n\n while (!(isBlanks(cur) || cur == EOFC))\n {\n result += char(cur);\n \n // You can change maxTokenLength.\n // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'.\n if (result.length() > maxTokenLength)\n quitf(_pe, \"Length of token exceeds %d, token is '%s...'\", int(maxTokenLength), __testlib_part(result).c_str());\n\n cur = reader->nextChar();\n }\n\n reader->unreadChar(cur);\n\n if (result.length() == 0)\n quit(_unexpected_eof, \"Unexpected end of file or white-space - token expected\");\n}\n\nstd::string InStream::readToken()\n{\n return readWord();\n}\n\nvoid InStream::readTokenTo(std::string& result)\n{\n readWordTo(result);\n}\n\nstatic std::string __testlib_part(const std::string& s)\n{\n if (s.length() <= 64)\n return s;\n else\n return s.substr(0, 30) + \"...\" + s.substr(s.length() - 31, 31);\n}\n\n#define __testlib_readMany(readMany, readOne, typeName, space) \\\n if (size < 0) \\\n quit(_fail, #readMany \": size should be non-negative.\"); \\\n if (size > 100000000) \\\n quit(_fail, #readMany \": size should be at most 100000000.\"); \\\n \\\n std::vector result(size); \\\n readManyIteration = indexBase; \\\n \\\n for (int i = 0; i < size; i++) \\\n { \\\n result[i] = readOne; \\\n readManyIteration++; \\\n if (strict && space && i + 1 < size) \\\n readSpace(); \\\n } \\\n \\\n readManyIteration = NO_INDEX; \\\n return result; \\\n\nstd::string InStream::readWord(const pattern& p, const std::string& variableName)\n{\n readWordTo(_tmpReadToken);\n if (!p.matches(_tmpReadToken))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Token element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token element \" + variableName + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n return _tmpReadToken;\n}\n\nstd::vector InStream::readWords(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readWord(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(pattern(ptrn), variableName);\n}\n\nstd::vector InStream::readWords(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const pattern& p, const std::string& variableName)\n{\n return readWord(p, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(ptrn, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true);\n}\n\nvoid InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readWordTo(result);\n if (!p.matches(result))\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n}\n\nvoid InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, pattern(ptrn), variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n return readWordTo(result, p, variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, ptrn, variableName);\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(long long integer, const char* s)\n{\n if (integer == LLONG_MIN)\n return strcmp(s, \"-9223372036854775808\") == 0;\n\n if (integer == 0LL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n if (integer < 0 && s[0] != '-')\n return false;\n\n if (integer < 0)\n s++, length--, integer = -integer;\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(unsigned long long integer, const char* s)\n{\n if (integer == ULLONG_MAX)\n return strcmp(s, \"18446744073709551615\") == 0;\n\n if (integer == 0ULL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\nstatic inline double stringToDouble(InStream& in, const char* buffer)\n{\n double retval;\n\n size_t length = strlen(buffer);\n\n int minusCount = 0;\n int plusCount = 0;\n int decimalPointCount = 0;\n int digitCount = 0;\n int eCount = 0;\n\n for (size_t i = 0; i < length; i++)\n {\n if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.'\n || buffer[i] == 'e' || buffer[i] == 'E'\n || buffer[i] == '-' || buffer[i] == '+')\n {\n if ('0' <= buffer[i] && buffer[i] <= '9')\n digitCount++;\n if (buffer[i] == 'e' || buffer[i] == 'E')\n eCount++;\n if (buffer[i] == '-')\n minusCount++;\n if (buffer[i] == '+')\n plusCount++;\n if (buffer[i] == '.')\n decimalPointCount++;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n // If for sure is not a number in standard notation or in e-notation.\n if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)\n{\n if (minAfterPointDigitCount < 0)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be non-negative.\");\n \n if (minAfterPointDigitCount > maxAfterPointDigitCount)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.\");\n\n double retval;\n\n size_t length = strlen(buffer);\n\n if (length == 0 || length > 1000)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int pointPos = -1; \n for (size_t i = 1; i + 1 < length; i++)\n {\n if (buffer[i] == '.')\n {\n if (pointPos > -1)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n pointPos = int(i);\n }\n if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n if (buffer[length - 1] < '0' || buffer[length - 1] > '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);\n if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)\n in.quit(_pe, (\"Expected strict double with number of digits after point in range [\"\n + vtos(minAfterPointDigitCount)\n + \",\"\n + vtos(maxAfterPointDigitCount)\n + \"], but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str()\n );\n\n int firstDigitPos = -1;\n for (size_t i = 0; i < length; i++)\n if (buffer[i] >= '0' && buffer[i] <= '9')\n {\n firstDigitPos = int(i);\n break;\n }\n\n if (firstDigitPos > 1 || firstDigitPos == -1) \n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)\n && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline long long stringToLongLong(InStream& in, const char* buffer)\n{\n if (strcmp(buffer, \"-9223372036854775808\") == 0)\n return LLONG_MIN;\n\n bool minus = false;\n size_t length = strlen(buffer);\n \n if (length > 1 && buffer[0] == '-')\n minus = true;\n\n if (length > 20)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n long long retval = 0LL;\n\n int zeroes = 0;\n int processingZeroes = true;\n \n for (int i = (minus ? 1 : 0); i < int(length); i++)\n {\n if (buffer[i] == '0' && processingZeroes)\n zeroes++;\n else\n processingZeroes = false;\n\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (retval < 0)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n \n if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n retval = (minus ? -retval : +retval);\n\n if (length < 19)\n return retval;\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline unsigned long long stringToUnsignedLongLong(InStream& in, const char* buffer)\n{\n size_t length = strlen(buffer);\n\n if (length > 20)\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n if (length > 1 && buffer[0] == '0')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n unsigned long long retval = 0LL;\n for (int i = 0; i < int(length); i++)\n {\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (length < 19)\n return retval;\n\n if (length == 20 && strcmp(buffer, \"18446744073709551615\") == 1)\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nint InStream::readInteger()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int32 expected\");\n\n readWordTo(_tmpReadToken);\n \n long long value = stringToLongLong(*this, _tmpReadToken.c_str());\n if (value < INT_MIN || value > INT_MAX)\n quit(_pe, (\"Expected int32, but \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" found\").c_str());\n \n return int(value);\n}\n\nlong long InStream::readLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToLongLong(*this, _tmpReadToken.c_str());\n}\n\nunsigned long long InStream::readUnsignedLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToUnsignedLongLong(*this, _tmpReadToken.c_str());\n}\n\nlong long InStream::readLong(long long minv, long long maxv, const std::string& variableName)\n{\n long long result = readLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readLongs(int size, long long minv, long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true)\n}\n\nunsigned long long InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n unsigned long long result = readUnsignedLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true)\n}\n\nunsigned long long InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n return readUnsignedLong(minv, maxv, variableName);\n}\n\nint InStream::readInt()\n{\n return readInteger();\n}\n\nint InStream::readInt(int minv, int maxv, const std::string& variableName)\n{\n int result = readInt();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nint InStream::readInteger(int minv, int maxv, const std::string& variableName)\n{\n return readInt(minv, maxv, variableName);\n}\n\nstd::vector InStream::readInts(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true)\n}\n\nstd::vector InStream::readIntegers(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true)\n}\n\ndouble InStream::readReal()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - double expected\");\n\n return stringToDouble(*this, readWord().c_str());\n}\n\ndouble InStream::readDouble()\n{\n return readReal();\n}\n\ndouble InStream::readReal(double minv, double maxv, const std::string& variableName)\n{\n double result = readReal();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readReals(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readDouble(double minv, double maxv, const std::string& variableName)\n{\n return readReal(minv, maxv, variableName);\n} \n\nstd::vector InStream::readDoubles(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - strict double expected\");\n\n double result = stringToStrictDouble(*this, readWord().c_str(),\n minAfterPointDigitCount, maxAfterPointDigitCount);\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictReals, readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\ndouble InStream::readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n return readStrictReal(minv, maxv,\n minAfterPointDigitCount, maxAfterPointDigitCount,\n variableName);\n}\n\nstd::vector InStream::readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictDoubles, readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\nbool InStream::eof()\n{\n if (!strict && NULL == reader)\n return true;\n\n return reader->eof();\n}\n\nbool InStream::seekEof()\n{\n if (!strict && NULL == reader)\n return true;\n skipBlanks();\n return eof();\n}\n\nbool InStream::eoln()\n{\n if (!strict && NULL == reader)\n return true;\n\n int c = reader->nextChar();\n\n if (!strict)\n {\n if (c == EOFC)\n return true;\n\n if (c == CR)\n {\n c = reader->nextChar();\n\n if (c != LF)\n {\n reader->unreadChar(c);\n reader->unreadChar(CR);\n return false;\n }\n else\n return true;\n }\n \n if (c == LF)\n return true;\n\n reader->unreadChar(c);\n return false;\n }\n else\n {\n bool returnCr = false;\n\n#if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS)\n if (c != CR)\n {\n reader->unreadChar(c);\n return false;\n }\n else\n {\n if (!returnCr)\n returnCr = true;\n c = reader->nextChar();\n }\n#endif \n if (c != LF)\n {\n reader->unreadChar(c);\n if (returnCr)\n reader->unreadChar(CR);\n return false;\n }\n\n return true;\n }\n}\n\nvoid InStream::readEoln()\n{\n lastLine = reader->getLine();\n if (!eoln())\n quit(_pe, \"Expected EOLN\");\n}\n\nvoid InStream::readEof()\n{\n lastLine = reader->getLine();\n if (!eof())\n quit(_pe, \"Expected EOF\");\n\n if (TestlibFinalizeGuard::alive && this == &inf)\n testlibFinalizeGuard.readEofCount++;\n}\n\nbool InStream::seekEoln()\n{\n if (!strict && NULL == reader)\n return true;\n \n int cur;\n do\n {\n cur = reader->nextChar();\n } \n while (cur == SPACE || cur == TAB);\n\n reader->unreadChar(cur);\n return eoln();\n}\n\nvoid InStream::nextLine()\n{\n readLine();\n}\n\nvoid InStream::readStringTo(std::string& result)\n{\n if (NULL == reader)\n quit(_pe, \"Expected line\");\n\n result.clear();\n\n for (;;)\n {\n int cur = reader->curChar();\n\n if (cur == LF || cur == EOFC)\n break;\n\n if (cur == CR)\n {\n cur = reader->nextChar();\n if (reader->curChar() == LF)\n {\n reader->unreadChar(cur);\n break;\n }\n }\n\n lastLine = reader->getLine();\n result += char(reader->nextChar());\n }\n\n if (strict)\n readEoln();\n else\n eoln();\n}\n\nstd::string InStream::readString()\n{\n readStringTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, int indexBase)\n{\n __testlib_readMany(readStrings, readString(), std::string, false)\n}\n\nvoid InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result);\n if (!p.matches(result))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Line \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Line element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n}\n\nvoid InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, pattern(ptrn), variableName);\n}\n\nstd::string InStream::readString(const pattern& p, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, p, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readString(const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, ptrn, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result)\n{\n readStringTo(result);\n}\n\nstd::string InStream::readLine()\n{\n return readString();\n}\n\nstd::vector InStream::readLines(int size, int indexBase)\n{\n __testlib_readMany(readLines, readString(), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result, p, variableName);\n}\n\nvoid InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, ptrn, variableName);\n}\n\nstd::string InStream::readLine(const pattern& p, const std::string& variableName)\n{\n return readString(p, variableName);\n}\n\nstd::vector InStream::readLines(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readLine(const std::string& ptrn, const std::string& variableName)\n{\n return readString(ptrn, variableName);\n}\n\nstd::vector InStream::readLines(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid InStream::ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n this->__testlib_ensure(cond, message);\n }\n}\n\nvoid InStream::__testlib_ensure(bool cond, std::string message)\n{\n if (!cond)\n this->quit(_wa, message.c_str()); \n}\n\nvoid InStream::close()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n \n opened = false;\n}\n\nNORETURN void quit(TResult result, const std::string& msg)\n{\n ouf.quit(result, msg.c_str());\n}\n\nNORETURN void quit(TResult result, const char* msg)\n{\n ouf.quit(result, msg);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...);\n\nNORETURN void __testlib_quitp(double points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %lf, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", points));\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void __testlib_quitp(int points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %d, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = format(\"%d\", points);\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void quitp(float points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(double points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\nNORETURN void quitp(long double points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(int points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\ntemplate\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitp(F points, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quitp(points, message);\n}\n\ntemplate\nNORETURN void quitp(F points)\n{\n __testlib_quitp(points, std::string(\"\"));\n}\n\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid quitif(bool condition, TResult result, const char* format, ...)\n{\n if (condition)\n {\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n }\n}\n\nNORETURN void __testlib_help()\n{\n InStream::textColor(InStream::LightCyan);\n std::fprintf(stderr, \"TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ \", VERSION);\n std::fprintf(stderr, \"by Mike Mirzayanov, copyright(c) 2005-2018\\n\");\n std::fprintf(stderr, \"Checker name: \\\"%s\\\"\\n\", checkerName.c_str());\n InStream::textColor(InStream::LightGray);\n\n std::fprintf(stderr, \"\\n\");\n std::fprintf(stderr, \"Latest features: \\n\");\n for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)\n {\n std::fprintf(stderr, \"*) %s\\n\", latestFeatures[i]);\n }\n std::fprintf(stderr, \"\\n\");\n\n std::fprintf(stderr, \"Program must be run with the following arguments: \\n\");\n std::fprintf(stderr, \" [ [<-appes>]]\\n\\n\");\n\n std::exit(FAIL_EXIT_CODE);\n}\n\nstatic void __testlib_ensuresPreconditions()\n{\n // testlib assumes: sizeof(int) = 4.\n __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);\n\n // testlib assumes: INT_MAX == 2147483647.\n __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);\n\n // testlib assumes: sizeof(long long) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);\n\n // testlib assumes: sizeof(double) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);\n\n // testlib assumes: no -ffast-math.\n if (!__testlib_isNaN(+__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n if (!__testlib_isNaN(-__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n}\n\nvoid registerGen(int argc, char* argv[], int randomGeneratorVersion)\n{\n if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)\n quitf(_fail, \"Random generator version is expected to be 0 or 1.\");\n random_t::version = randomGeneratorVersion;\n\n __testlib_ensuresPreconditions();\n\n testlibMode = _generator;\n __testlib_set_binary(stdin);\n rnd.setSeed(argc, argv);\n}\n\n#ifdef USE_RND_AS_BEFORE_087\nvoid registerGen(int argc, char* argv[])\n{\n registerGen(argc, argv, 0);\n}\n#else\n#ifdef __GNUC__\n#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4))\n __attribute__ ((deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\")))\n#else\n __attribute__ ((deprecated))\n#endif\n#endif\n#ifdef _MSC_VER\n __declspec(deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\"))\n#endif\nvoid registerGen(int argc, char* argv[])\n{\n std::fprintf(stderr, \"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\\n\\n\");\n registerGen(argc, argv, 0);\n}\n#endif\n\nvoid registerInteraction(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _interactor;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n \n if (argc < 3 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [ [<-appes>]]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc <= 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n#ifndef EJUDGE\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n#endif\n\n inf.init(argv[1], _input);\n\n tout.open(argv[2], std::ios_base::out);\n if (tout.fail() || !tout.is_open())\n quit(_fail, std::string(\"Can not write to the test-output-file '\") + argv[2] + std::string(\"'\"));\n\n ouf.init(stdin, _output);\n \n if (argc >= 4)\n ans.init(argv[3], _answer);\n else\n ans.name = \"unopened answer stream\";\n}\n\nvoid registerValidation()\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _validator;\n __testlib_set_binary(stdin);\n\n inf.init(stdin, _input);\n inf.strict = true;\n}\n\nvoid registerValidation(int argc, char* argv[])\n{\n registerValidation();\n\n for (int i = 1; i < argc; i++)\n {\n if (!strcmp(\"--testset\", argv[i]))\n {\n if (i + 1 < argc && strlen(argv[i + 1]) > 0)\n validator.setTestset(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--group\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setGroup(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--testOverviewLogFileName\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setTestOverviewLogFileName(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n } \n}\n\nvoid addFeature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.addFeature(feature); \n}\n\nvoid feature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.feature(feature); \n}\n\nvoid registerTestlibCmd(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _checker;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n\n if (argc < 4 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [<-appes>]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc == 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n\n inf.init(argv[1], _input);\n ans.init(argv[2], _answer);\n ouf.init(argv[3], _output);\n}\n\nvoid registerTestlib(int argc, ...)\n{\n if (argc < 3 || argc > 5)\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n\n char** argv = new char*[argc + 1];\n \n va_list ap;\n va_start(ap, argc);\n argv[0] = NULL;\n for (int i = 0; i < argc; i++)\n {\n argv[i + 1] = va_arg(ap, char*);\n }\n va_end(ap);\n\n registerTestlibCmd(argc + 1, argv);\n delete[] argv;\n}\n\nstatic inline void __testlib_ensure(bool cond, const std::string& msg)\n{\n if (!cond)\n quit(_fail, msg.c_str());\n}\n\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\nstatic inline void __testlib_ensure(bool cond, const char* msg)\n{\n if (!cond)\n quit(_fail, msg);\n}\n\n#define ensure(cond) __testlib_ensure(cond, \"Condition failed: \\\"\" #cond \"\\\"\")\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\ninline void ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n __testlib_ensure(cond, message);\n }\n}\n\nNORETURN static void __testlib_fail(const std::string& message)\n{\n quitf(_fail, \"%s\", message.c_str());\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid setName(const char* format, ...)\n{\n FMT_TO_RESULT(format, format, name);\n checkerName = name;\n}\n\n/* \n * Do not use random_shuffle, because it will produce different result\n * for different C++ compilers.\n *\n * This implementation uses testlib random_t to produce random numbers, so\n * it is stable.\n */ \ntemplate\nvoid shuffle(_RandomAccessIter __first, _RandomAccessIter __last)\n{\n if (__first == __last) return;\n for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)\n std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));\n}\n\n\ntemplate\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use random_shuffle(), use shuffle() instead\")))\n#endif\nvoid random_shuffle(_RandomAccessIter , _RandomAccessIter )\n{\n quitf(_fail, \"Don't use random_shuffle(), use shuffle() instead\");\n}\n\n#ifdef __GLIBC__\n# define RAND_THROW_STATEMENT throw()\n#else\n# define RAND_THROW_STATEMENT\n#endif\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use rand(), use rnd.next() instead\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nint rand() RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use rand(), use rnd.next() instead\");\n \n /* This line never runs. */\n //throw \"Don't use rand(), use rnd.next() instead\";\n}\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1).\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nvoid srand(unsigned int seed) RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1) [ignored seed=%d].\", seed);\n}\n\nvoid startTest(int test)\n{\n const std::string testFileName = vtos(test);\n if (NULL == freopen(testFileName.c_str(), \"wt\", stdout))\n __testlib_fail(\"Unable to write file '\" + testFileName + \"'\");\n}\n\ninline std::string upperCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('a' <= s[i] && s[i] <= 'z')\n s[i] = char(s[i] - 'a' + 'A');\n return s;\n}\n\ninline std::string lowerCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('A' <= s[i] && s[i] <= 'Z')\n s[i] = char(s[i] - 'A' + 'a');\n return s;\n}\n\ninline std::string compress(const std::string& s)\n{\n return __testlib_part(s);\n}\n\ninline std::string englishEnding(int x)\n{\n x %= 100;\n if (x / 10 == 1)\n return \"th\";\n if (x % 10 == 1)\n return \"st\";\n if (x % 10 == 2)\n return \"nd\";\n if (x % 10 == 3)\n return \"rd\";\n return \"th\";\n}\n\ninline std::string trim(const std::string& s)\n{\n if (s.empty())\n return s;\n\n int left = 0;\n while (left < int(s.length()) && isBlanks(s[left]))\n left++;\n if (left >= int(s.length()))\n return \"\";\n\n int right = int(s.length()) - 1;\n while (right >= 0 && isBlanks(s[right]))\n right--;\n if (right < 0)\n return \"\";\n\n return s.substr(left, right - left + 1);\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator)\n{\n std::stringstream ss;\n bool repeated = false;\n for (_ForwardIterator i = first; i != last; i++)\n {\n if (repeated)\n ss << separator;\n else\n repeated = true;\n ss << *i;\n }\n return ss.str();\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last)\n{\n return join(first, last, ' ');\n}\n\ntemplate \nstd::string join(const _Collection& collection, _Separator separator)\n{\n return join(collection.begin(), collection.end(), separator);\n}\n\ntemplate \nstd::string join(const _Collection& collection)\n{\n return join(collection, ' ');\n}\n\n/**\n * Splits string s by character separator returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separator returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n if (!item.empty())\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n \n if (!item.empty())\n result.push_back(item);\n\n return result;\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char* prepend)\n{\n std::string message;\n if (strlen(prepend) != 0)\n message = format(\"%s: expected '%s', but found '%s'\",\n compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());\n else\n message = format(\"expected '%s', but found '%s'\",\n compress(expected).c_str(), compress(found).c_str());\n quit(result, message);\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char* prepend)\n{\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend);\n}\n\ntemplate \n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, T expected, T found, const char* prependFormat = \"\", ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = vtos(expected);\n std::string foundString = vtos(found);\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, std::string expected, std::string found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, expected, found, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, double expected, double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, const char* expected, const char* found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, float expected, float found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, long double expected, long double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\n#endif\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate \nstruct is_iterable\n{\n template \n static char test(typename U::iterator* x);\n \n template \n static long test(U* x);\n \n static const bool value = sizeof(test(0)) == 1;\n};\n\ntemplate\nstruct __testlib_enable_if {};\n \ntemplate\nstruct __testlib_enable_if { typedef T type; };\n\ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n std::cout << t;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n bool first = true;\n for (typename T::const_iterator i = t.begin(); i != t.end(); i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n std::cout << *i;\n }\n}\n\ntemplate<>\ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const std::string& t)\n{\n std::cout << t;\n}\n \ntemplate\nvoid __println_range(A begin, B end)\n{\n bool first = true;\n for (B i = B(begin); i != end; i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n __testlib_print_one(*i);\n }\n std::cout << std::endl;\n}\n\ntemplate\nstruct is_iterator\n{ \n static T makeT();\n typedef void * twoptrs[2];\n static twoptrs & test(...);\n template static typename R::iterator_category * test(R);\n template static void * test(R *);\n static const bool value = sizeof(test(makeT())) == sizeof(void *); \n};\n\ntemplate\nstruct is_iterator::value >::type>\n{\n static const bool value = false; \n};\n\ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __println_range(a, b);\n}\n\ntemplate \nvoid println(const A* a, const A* b)\n{\n __println_range(a, b);\n}\n\ntemplate <>\nvoid println(const char* a, const char* b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const T& x)\n{\n __testlib_print_one(x);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f, const G& g)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << \" \";\n __testlib_print_one(g);\n std::cout << std::endl;\n}\n#endif\n\n\n\nvoid registerChecker(std::string probName, int argc, char* argv[])\n{\n setName(\"checker for problem %s\", probName.c_str());\n registerTestlibCmd(argc, argv);\n}\n\n\n\nconst std::string _grader_OK = \"OK\";\nconst std::string _grader_SV = \"SV\";\nconst std::string _grader_PV = \"PV\";\nconst std::string _grader_WA = \"WA\";\nconst std::string _grader_FAIL = \"FAIL\";\n\n\nvoid InStream::readSecret(\n std::string secret,\n TResult mismatchResult,\n std::string mismatchMessage,\n std::string eofMessage)\n{\n if (seekEof())\n quits(mismatchResult, eofMessage);\n if (readWord() != secret)\n quits(mismatchResult, mismatchMessage);\n eoln();\n}\n\nvoid readBothSecrets(std::string secret)\n{\n ans.readSecret(\n secret,\n _fail,\n \"Secret mismatch in the (correct) answer file\",\n \"Empty (correct) answer file\");\n ouf.readSecret(\n secret,\n _pv,\n \"Possible tampering with the output\",\n \"Early termination of the solution (possibly calling exit)\");\n}\n\n\nvoid InStream::quitByGraderResult(TResult result, std::string defaultMessage)\n{\n std::string msg = \"\";\n if (!eof())\n msg = readLine();\n if (msg.empty())\n quits(result, defaultMessage);\n quits(result, msg);\n}\n\nvoid InStream::readGraderResult()\n{\n std::string result = readWord();\n eoln();\n if (result == _grader_OK)\n return;\n if (result == _grader_SV)\n quitByGraderResult(_sv, \"Security violation detected in grader\");\n if (result == _grader_PV)\n quitByGraderResult(_pv, \"Protocol violation detected in grader\");\n if (result == _grader_WA)\n quitByGraderResult(_wa, \"Wrong answer detected in grader\");\n if (result == _grader_FAIL)\n quitByGraderResult(_fail, \"Failure in grader\");\n quitf(_fail, \"Unknown grader result\");\n}\n\nvoid readBothGraderResults()\n{\n ans.readGraderResult();\n ouf.readGraderResult();\n}\n\n\nNORETURN void quit(TResult result)\n{\n ouf.quit(result, \"\");\n}\n\n/// Used in validators: skips the rest of input, assuming it to be correct\nNORETURN void skip_ok()\n{\n if (testlibMode != _validator)\n quitf(_fail, \"skip_ok() only works in validators\");\n testlibFinalizeGuard.quitCount++;\n halt(0);\n}\n\n/// 1 -> 1st, 2 -> 2nd, 3 -> 3rd, 4 -> 4th, ...\nstd::string englishTh(int x)\n{\n char c[100];\n snprintf(c, sizeof(c), \"%d%s\", x, englishEnding(x).c_str());\n return c;\n}\n\n/// Compares the tokens of two lines\nvoid compareTokens(int lineNo, std::string a, std::string b, char separator=' ')\n{\n std::vector toka = tokenize(a, separator);\n std::vector tokb = tokenize(b, separator);\n if (toka == tokb)\n return;\n std::string dif = format(\"%s lines differ - \", englishTh(lineNo).c_str());\n if (toka.size() != tokb.size())\n quitf(_wa, \"%sexpected: %d tokens, found %d tokens\", dif.c_str(), int(toka.size()), int(tokb.size()));\n for (int i=0; i M, std::vector C)\n\n* $M$: an array of length $S$ describing the message that Aisha wants to send to Basma.\n* $C$: an array of length $31$ indicating the indices of bits controlled by Cleopatra.\n* This procedure may be called at most 2100 times in each test case.\n\nThis procedure should call the following procedure to send a packet:\n\nstd::vector send\\_packet(std::vector A)\n\n* $A$: an original packet (an array of length $31$) representing the bits sent by Aisha.\n* This procedure returns a tainted packet $B$ representing the bits that will be received by Basma.\n* This procedure can be called at most $100$ times in each invocation of send\\_message.\n\nThe second procedure you should implement is:\n\nstd::vector receive\\_message(std::vector\n#include \n\nusing namespace std;\n\n\n/******************************** Begin testlib-related material ********************************/\n\ninline FILE* openFile(const char* name, const char* mode) {\n\tFILE* file = fopen(name, mode);\n\tif (!file)\n\t\tquitf(_fail, \"Could not open file '%s' with mode '%s'.\", name, mode);\n\tcloseOnHalt(file);\n\treturn file;\n}\n\n\nvector mgr2sol, sol2mgr;\nFILE* log_file = nullptr;\n\nvoid nullifyFile(int idx) {\n\tmgr2sol[idx] = sol2mgr[idx] = nullptr;\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid log_printf(const char* fmt, ...) {\n\tif (log_file) {\n\t\tFMT_TO_RESULT(fmt, fmt, message);\n\t\tfprintf(log_file, \"%s\", message.c_str());\n\t\tfflush(log_file);\n\t}\n}\n\nvoid registerManager(std::string probName, int num_processes, int argc, char* argv[]) {\n\tsetName(\"manager for problem %s\", probName.c_str());\n\t__testlib_ensuresPreconditions();\n\ttestlibMode = _checker;\n\trandom_t::version = 1; // Random generator version\n\t__testlib_set_binary(stdin);\n\touf.mode = _output;\n\n\t{//Keep alive on broken pipes\n\t\t//signal(SIGPIPE, SIG_IGN);\n\t\tstruct sigaction sa;\n\t\tsa.sa_handler = SIG_IGN;\n\t\tsigaction(SIGPIPE, &sa, NULL);\n\t}\n\n\tint required_args = 1 + 2 * num_processes;\n\tif (argc < required_args || required_args+1 < argc) {\n\t\tstring usage = format(\"'%s'\", argv[0]);\n\t\tfor (int i = 0; i < num_processes; i++)\n\t\t\tusage += format(\" sol%d-to-mgr mgr-to-sol%d\", i, i);\n\t\tusage += \" [mgr_log] < input-file\";\n\t\tquitf(_fail,\n\t\t\t\"Manager for problem %s:\\n\"\n\t\t\t\"Invalid number of arguments: %d\\n\"\n\t\t\t\"Usage: %s\",\n\t\t\tprobName.c_str(), argc-1, usage.c_str());\n\t}\n\n\tinf.init(stdin, _input);\n\tcloseOnHalt(stdout);\n\tcloseOnHalt(stderr);\n\n\tmgr2sol.resize(num_processes);\n\tsol2mgr.resize(num_processes);\n\tfor (int i = 0; i < num_processes; i++) {\n\t\tmgr2sol[i] = openFile(argv[1 + 2*i + 1], \"a\");\n\t\tsol2mgr[i] = openFile(argv[1 + 2*i + 0], \"r\");\n\t}\n\n\tif (argc > required_args) {\n\t\tlog_file = openFile(argv[required_args], \"w\");\n\t} else {\n\t\tlog_file = nullptr;\n\t}\n}\n/********************************* End testlib-related material *********************************/\n\n\n// utils\n\n#define rep(i, n) for(int i = 0, i##__n = (int)(n); i < i##__n; ++i)\n\ntemplate int sz(const C& c) { return std::size(c); }\n\n\n// grader/manager protocol\n\nconst int secret_g2m = 0x647FB390;\nconst int secret_m2g = 0xB107D5C0;\nconst int code_mask = 0x0000000F;\n\nconst int M2G_CODE__OK = 0;\nconst int M2G_CODE__DIE = 1;\n\nconst int G2M_CODE__OK = 0;\nconst int G2M_CODE__OK_END_OF_PACKETS = 1;\nconst int G2M_CODE__PACKET_SIZE_INCORRECT = 2;\nconst int G2M_CODE__RETURN_MESSAGE_TOO_LARGE = 3;\nconst int G2M_CODE__PV_CALL_EXIT = 13;\nconst int G2M_CODE__PV_TAMPER_M2G = 14;\nconst int G2M_CODE__SILENT = 15;\n\n\nint fifo_idx = 0;\nbool mode_end_of_packets;\n\nvoid out_flush() {\n\tfflush(mgr2sol[fifo_idx]);\n}\n\nvoid write_int(int x) {\n\tFILE* fout = mgr2sol[fifo_idx];\n\tif (1 != fwrite(&x, sizeof(x), 1, fout)) {\n\t\tnullifyFile(fifo_idx);\n\t\tlog_printf(\"Could not write int to mgr2sol[%d]\\n\", fifo_idx);\n\t}\n}\n\nvoid write_int_array(const int* arr, int len) {\n\tFILE* fout = mgr2sol[fifo_idx];\n\tif (int ret = fwrite(arr, sizeof(int), len, fout); len != ret) {\n\t\tnullifyFile(fifo_idx);\n\t\tlog_printf(\"Could not write int array of size %d to mgr2sol[%d], fwrite returned %d\\n\", len, fifo_idx, ret);\n\t}\n}\n\nvoid write_int_vector(const vector& v) {\n\twrite_int_array(v.data(), sz(v));\n}\n\n\nvoid write_secret(int m2g_code = M2G_CODE__OK) {\n\twrite_int(secret_m2g | m2g_code);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void die(TResult result, const char* format, ...) {\n\tFMT_TO_RESULT(format, format, message);\n\tlog_printf(\"Dying with message '%s'\\n\", message.c_str());\n\trep(i, sz(mgr2sol))\n\t\tif(mgr2sol[i] != nullptr) {\n\t\t\tfifo_idx = i;\n\t\t\tlog_printf(\"Sending secret with code DIE to mgr2sol[%d]\\n\", fifo_idx);\n\t\t\twrite_secret(M2G_CODE__DIE);\n\t\t\tout_flush();\n\t\t}\n\tlog_printf(\"Quitting with result code %d\\n\", int(result));\n\tquit(result, message);\n}\n\nNORETURN void die_invalid_argument(const string &msg) {\n\tRESULT_MESSAGE_WRONG += \": Invalid argument\";\n\tdie(_wa, \"%s\", msg.c_str());\n}\n\nNORETURN void die_too_many_calls(const string &msg) {\n\tRESULT_MESSAGE_WRONG += \": Too many calls\";\n\tdie(_wa, \"%s\", msg.c_str());\n}\n\nint read_int() {\n\tFILE* fin = sol2mgr[fifo_idx];\n\tint x;\n\tif (1 != fread(&x, sizeof(x), 1, fin)) {\n\t\tnullifyFile(fifo_idx);\n\t\tdie(_fail, \"Could not read int from sol2mgr[%d]\", fifo_idx);\n\t}\n\treturn x;\n}\n\nvoid read_int_array(int* arr, int len) {\n\tFILE* fin = sol2mgr[fifo_idx];\n\tif (int ret = fread(arr, sizeof(int), len, fin); len != ret) {\n\t\tnullifyFile(fifo_idx);\n\t\tdie(_fail, \"Could not read int array of size %d from sol2mgr[%d], fread returned %d\", len, fifo_idx, ret);\n\t}\n}\n\n\nvoid read_secret() {\n\tint secret = read_int();\n\tif((secret & ~code_mask) != secret_g2m)\n\t\tdie(_pv, \"Possible tampering with sol2mgr[%d]\", fifo_idx);\n\tint g2m_code = secret & code_mask;\n\tmode_end_of_packets = false;\n\tswitch (g2m_code) {\n\t\tcase G2M_CODE__OK:\n\t\t\treturn;\n\t\tcase G2M_CODE__OK_END_OF_PACKETS:\n\t\t\tmode_end_of_packets = true;\n\t\t\treturn;\n\t\tcase G2M_CODE__SILENT:\n\t\t\tdie(_fail, \"Unexpected g2m_code SILENT from sol2mgr[%d]\", fifo_idx);\n\t\tcase G2M_CODE__PV_TAMPER_M2G:\n\t\t\tdie(_pv, \"Possible tampering with mgr2sol[%d]\", fifo_idx);\n\t\tcase G2M_CODE__PV_CALL_EXIT:\n\t\t\tdie(_pv, \"Solution[%d] called exit()\", fifo_idx);\n\t\tcase G2M_CODE__PACKET_SIZE_INCORRECT:\n\t\t\tdie_invalid_argument(\"Packet size is incorrect\");\n\t\tcase G2M_CODE__RETURN_MESSAGE_TOO_LARGE:\n\t\t\tdie(_wa, \"Returned message's length is too large.\");\n\t\tdefault:\n\t\t\tdie(_fail, \"Unknown g2m_code %d from sol2mgr[%d]\", g2m_code, fifo_idx);\n\t}\n}\n\n\nconst int PACKET_SIZE = 31;\nconst int CALLS_CNT_LIMIT = 100;\n\n//mt19937 rng(15061994);\n//auto rnd1 = bind(uniform_int_distribution(0, (1 << 1) - 1), rng);\n//auto rnd4 = bind(uniform_int_distribution(0, (1 << 4) - 1), rng);\n//auto rnd31 = bind(uniform_int_distribution(0, (1U << 31) - 1), rng);\nint used_days, max_used_days = 0;\n\nint compressed_len(int len) { return (len+31) / 32; }\n\nstring vi2binStr(const vector& arr, int len) {\n\tstring str(len, '*');\n\trep(i, len) str[i] = (arr[i / 32] >> (i & 31) & 1) + '0';\n\treturn str;\n}\n\nenum Strategy {\n\tBEGIN,\n\tkExampleStrategy,\n\tkRandom,\n\tkJustOnes,\n\tkJustZeroes,\n\tkMimicAllButOneRound0,\n\tkMimicAllButOneRound1,\n\tkMimicAllButOneRound2,\n\tkMimicAllButOneRound3,\n\tkMimicAllButOneRound4,\n\tkInvertAllButOneRound0,\n\tkInvertAllButOneRound1,\n\tkInvertAllButOneRound2,\n\tkInvertAllButOneRound3,\n\tkInvertAllButOneRound4,\n\tkMinimizeDiffOfZeroesAndOnes,\n\tkEchoPreviousResponses,\n\tkEchoPreviousResponsesShuffled,\n\tkSame,\n\tkFlip,\n\tkMimicClosestOnLeft,\n\tkMimicClosestOnRight,\n\tEND\n};\n\nstruct BaseTestCase {\n\tconst int S;\n\tconst vector M_f;\n\tconst int C_f;\n};\n\nstruct EncoderTestCase {\n\tconst BaseTestCase *base;\n\tStrategy strategy;\n};\n\nstruct DecoderTestCase {\n\tconst BaseTestCase *base;\n\tvector R_f;\n};\n\n\nvector ReadBaseTestCases() {\n\tint T = inf.readInt();\n\tvector base_tests;\n\tfor(int _ = 0; _ < T; _++) {\n\t\tint S = inf.readInt();\n\t\tvector M_f(compressed_len(S), 0);\n\t\tfor(int i = 0; i < S; i++) {\n\t\t\tint bit = inf.readInt(0, 1);\n\t\t\tM_f[i / 32] |= bit << (i & 31);\n\t\t}\n\n\t\tint C_f = 0;\n\t\tfor(int i = 0; i < PACKET_SIZE; i++) {\n\t\t\tint ally = inf.readInt(0, PACKET_SIZE-1);\n\t\t\tC_f |= ally << i;\n\t\t}\n\n\t\tbase_tests.push_back(BaseTestCase{\n\t\t\t\t.S = S,\n\t\t\t\t.M_f = M_f,\n\t\t\t\t.C_f = C_f});\n\t}\n\tfclose(stdin);\n\treturn base_tests;\n}\n\nvector GenerateEncoderTests(const vector &base_tests) {\n\tvector encoder_tests;\n\tif(base_tests.size() <= 3) { // This is the example test\n\t\tfor(const auto &base_test : base_tests)\n\t\t\tencoder_tests.push_back(EncoderTestCase{\n\t\t\t\t\t.base = &base_test,\n\t\t\t\t\t.strategy = Strategy::kExampleStrategy});\n\t}\n\telse {\n\t\tfor(const auto &base_test : base_tests)\n\t\t\tfor(int strategy = Strategy::BEGIN + 1; strategy < Strategy::END; strategy++)\n\t\t\t\tencoder_tests.push_back(EncoderTestCase{\n\t\t\t\t\t\t.base = &base_test,\n\t\t\t\t\t\t.strategy = static_cast(strategy)});\n\t}\n\n\tshuffle(encoder_tests.begin(), encoder_tests.end());\n\treturn encoder_tests;\n}\n\nvoid setbit(int &x, int i, int b) { b == 1 ? x |= (1 << i) : x &= ~(1 << i); }\n\nint ApplyStrategy(const Strategy strategy, const int C_f, int used_days,\n\t\tconst vector& previous_answers, const vector& who_to_mimic,\n\t\tconst vector& non_mimic_index, int x) {\n\tif(strategy == Strategy::kExampleStrategy) {\n\t\tint bit = 0;\n\t\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\t\tif(C_f >> i & 1) {\n\t\t\t\tsetbit(x, i, bit);\n\t\t\t\tbit ^= 1;\n\t\t\t}\n\t\treturn x;\n\t}\n\n\tif(strategy == Strategy::kSame)\n\t\treturn x;\n\tif(strategy == Strategy::kFlip)\n\t\treturn x ^ C_f;\n\tif(strategy == Strategy::kMimicClosestOnLeft) {\n\t\tint st = __builtin_ctz(~C_f);\n\t\tint pbit = (x >> st) & 1;\n\t\tfor(int dis = 1; dis < PACKET_SIZE; dis++) {\n\t\t\tint i = (st + dis) % PACKET_SIZE;\n\t\t\tif(C_f >> i & 1)\n\t\t\t\tsetbit(x, i, pbit);\n\t\t\tpbit = (x >> i) & 1;\n\t\t}\n\t\treturn x;\n\t}\n\tif(strategy == Strategy::kMimicClosestOnRight) {\n\t\tint st = __builtin_ctz(~C_f);\n\t\tint pbit = (x >> st) & 1;\n\t\tfor(int dis = 1; dis < PACKET_SIZE; dis++) {\n\t\t\tint i = (st - dis + PACKET_SIZE) % PACKET_SIZE;\n\t\t\tif(C_f >> i & 1)\n\t\t\t\tsetbit(x, i, pbit);\n\t\t\tpbit = (x >> i) & 1;\n\t\t}\n\t\treturn x;\n\t}\n\n\tif(strategy == Strategy::kRandom)\n\t\treturn x ^ (rnd.next(0U, (1U << 31) - 1) & C_f);\n\tif(strategy == Strategy::kJustOnes)\n\t\treturn x | C_f;\n\tif(strategy == Strategy::kJustZeroes)\n\t\treturn x & ~C_f;\n\n\tvector their_choices;\n\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\tif(!(C_f >> i & 1))\n\t\t\ttheir_choices.push_back(x >> i & 1);\n\n\tif(kMimicAllButOneRound0 <= strategy and strategy <= kInvertAllButOneRound4) {\n\t\tint id = strategy - kMimicAllButOneRound0;\n\t\tif(kInvertAllButOneRound0 <= strategy)\n\t\t\tid = strategy - kInvertAllButOneRound0;\n\t\tif(used_days == non_mimic_index[id]) {\n\t\t\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\t\t\tif(C_f >> i & 1) {\n\t\t\t\t\tif(kMimicAllButOneRound0 <= strategy and strategy <= kMimicAllButOneRound4)\n\t\t\t\t\t\tsetbit(x, i, x >> who_to_mimic[i] & 1);\n\t\t\t\t\telse\n\t\t\t\t\t\tsetbit(x, i, (x >> who_to_mimic[i] & 1) ^ 1);\n\t\t\t\t}\n\t\t\treturn x;\n\t\t}\n\t\telse\n\t\t\treturn x ^ (rnd.next(0U, (1U << 31) - 1) & C_f);\n\t}\n\n\tif(strategy == Strategy::kMinimizeDiffOfZeroesAndOnes) {\n\t\tint zeroes_count = 0, ones_count = 0;\n\t\tfor(int previous_answer: previous_answers) {\n\t\t\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\t\t\tif((previous_answer >> i & 1) == 0)\n\t\t\t\t\tzeroes_count++;\n\t\t\t\telse\n\t\t\t\t\tones_count++;\n\t\t}\n\t\tfor(int i = 0; i < PACKET_SIZE; i++) {\n\t\t\tif(!(C_f >> i & 1)) {\n\t\t\t\tif((x >> i & 1) == 0)\n\t\t\t\t\tzeroes_count++;\n\t\t\t\telse\n\t\t\t\t\tones_count++;\n\t\t\t}\n\t\t}\n\t\tvector my_choices;\n\t\tfor(int i = 0; i < (PACKET_SIZE - 1) / 2; i++) {\n\t\t\tint choice = rnd.next(0, 1);\n\t\t\tif(zeroes_count > ones_count)\n\t\t\t\tchoice = 1;\n\t\t\tif(zeroes_count < ones_count)\n\t\t\t\tchoice = 0;\n\t\t\tif(choice == 0)\n\t\t\t\tzeroes_count++;\n\t\t\tif(choice == 1)\n\t\t\t\tones_count++;\n\t\t\tmy_choices.push_back(choice);\n\t\t}\n\t\tshuffle(my_choices.begin(), my_choices.end());\n\t\tint ix = 0;\n\t\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\t\tif(C_f >> i & 1)\n\t\t\t\tsetbit(x, i, my_choices[ix++]);\n\t\treturn x;\n\t}\n\n\tif(strategy == Strategy::kEchoPreviousResponses or\n\t\t\tstrategy == Strategy::kEchoPreviousResponsesShuffled) {\n\t\tif(used_days == 1) {\n\t\t\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\t\t\tif(C_f >> i & 1)\n\t\t\t\t\tsetbit(x, i, rnd.next(0, 1));\n\t\t}\n\t\telse {\n\t\t\tint previous_response = previous_answers.back();\n\t\t\tvector my_response;\n\t\t\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\t\t\tif(!(C_f >> i & 1))\n\t\t\t\t\tmy_response.push_back(previous_response >> i & 1);\n\t\t\tif(strategy == Strategy::kEchoPreviousResponsesShuffled)\n\t\t\t\tshuffle(my_response.begin(), my_response.end());\n\t\t\tint ix = 0;\n\t\t\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\t\t\tif(C_f >> i & 1)\n\t\t\t\t\tsetbit(x, i, my_response[ix++]);\n\t\t}\n\t\treturn x;\n\t}\n\n\tdie(_fail, \"Unknown strategy!\");\n}\n\nvector CalculateMimicyMap(int C_f) {\n\tvector their_indices;\n\tfor(int i = 0; i < PACKET_SIZE; i++) {\n\t\tif(!(C_f >> i & 1))\n\t\t\ttheir_indices.push_back(i);\n\t}\n//\tshuffle(their_indices.begin(), their_indices.end(), rng);\n\ttheir_indices.erase(their_indices.begin() + rnd.next(16));\n\t\n\tvector who_to_mimic(PACKET_SIZE, -1);\n\tint ix = 0;\n\tfor(int i = 0; i < PACKET_SIZE; i++)\n\t\tif(C_f >> i & 1)\n\t\t\twho_to_mimic[i] = their_indices[ix++];\n\treturn who_to_mimic;\n}\n\nvector RunEncoder(vector &encoder_tests) {\n\tint test_cases = encoder_tests.size();\n\n\tvector decoder_tests;\n\n\tfor(int _ = 0; _ < test_cases; _++) {\n\t\tconst EncoderTestCase &test = encoder_tests[_];\n\n\t\twrite_secret();\n\t\twrite_int(test.base->S);\n\t\twrite_int_vector(test.base->M_f);\n\t\twrite_int(test.base->C_f);\n\t\tout_flush();\n\n\t\tauto who_to_mimic = CalculateMimicyMap(test.base->C_f);\n\t\tvector non_mimic_index(5);\n\t\tnon_mimic_index[1] = rnd.next(0, 7);\n\t\tnon_mimic_index[0] = rnd.next(8, 19);\n\t\tnon_mimic_index[2] = rnd.next(20, 44);\n\t\tnon_mimic_index[3] = rnd.next(45, 66);\n\t\tnon_mimic_index[4] = rnd.next(67, 100);\n\n\t\tused_days = 0;\n\t\tvector R_f;\n\t\twhile(true) {\n\t\t\tread_secret();\n\t\t\tif(mode_end_of_packets == true) break;\n\n\t\t\tint A_f = read_int();\n\n\t\t\tif(++used_days > CALLS_CNT_LIMIT)\n\t\t\t\tdie_too_many_calls(\"Used too many days\");\n\n\t\t\tint B_f = ApplyStrategy(test.strategy, test.base->C_f, used_days, R_f, who_to_mimic, non_mimic_index, A_f);\n\n\t\t\tensuref(((B_f ^ A_f) | test.base->C_f) == test.base->C_f, \"ApplyStrategy should not edit uncontrolled bits\");\n\t\t\t\n\t\t\tR_f.push_back(B_f);\n\n\t\t\twrite_secret();\n\t\t\twrite_int(B_f);\n\t\t\tout_flush();\n\t\t}\n\t\tdecoder_tests.push_back(DecoderTestCase{\n\t\t\t\t.base = test.base,\n\t\t\t\t.R_f = R_f,\n\t\t\t\t});\n\t\tmax_used_days = max(max_used_days, used_days);\n\t}\n\n\twrite_secret();\n\twrite_int(-1);\n\tout_flush();\n\n\treturn decoder_tests;\n}\n\nvoid RunDecoder(const vector &decoder_tests) {\n\tint test_cases = decoder_tests.size();\n\tfor(int _ = 0; _ < test_cases; _++) {\n\t\tconst DecoderTestCase &test = decoder_tests[_];\n\n\t\twrite_secret();\n\t\twrite_int(sz(test.R_f));\n\t\twrite_int_vector(test.R_f);\n\t\tout_flush();\n\n\t\tread_secret();\n\t\tint L = read_int();\n\t\tvector D_f(compressed_len(L), 0);\n\t\tread_int_array(D_f.data(), sz(D_f));\n\n\t\tif(L != test.base->S || D_f != test.base->M_f) {\n\t\t\tlog_printf(\n\t\t\t\t\t\"WA:\\n\"\n\t\t\t\t\t\"original message:\\n\"\n\t\t\t\t\t\"'%s'\\n\"\n\t\t\t\t\t\"decoded message:\\n\"\n\t\t\t\t\t\"'%s'\\n\",\n\t\t\t\t\tvi2binStr(test.base->M_f, test.base->S).c_str(),\n\t\t\t\t\tvi2binStr(D_f, L).c_str());\n\t \tdie(_wa, \"decoded message is incorrect\");\n\t\t}\n\t}\n\n\twrite_secret();\n\twrite_int(-1);\n\tout_flush();\n}\n\nint main(int argc, char **argv) {\n\tregisterManager(\"message\", 2, argc, argv);\n\n\tfifo_idx = 0; // Mode: Encoder\n\tvector base_tests = ReadBaseTestCases();\n\tvector encoder_tests = GenerateEncoderTests(base_tests);\n\tvector decoder_tests = RunEncoder(encoder_tests);\n\tnullifyFile(fifo_idx);\n\n\tshuffle(decoder_tests.begin(), decoder_tests.end());\n\n\tfifo_idx = 1; // Mode: Decoder\n\tRunDecoder(decoder_tests);\n\tnullifyFile(fifo_idx);\n\n\t// scoring\n\tconst int days_threshold = 66;\n\tif(max_used_days <= days_threshold)\n\t\tquitf(_ok, \"Used %d days\", max_used_days);\n\telse if(max_used_days <= CALLS_CNT_LIMIT)\n\t\tquitp(pow(0.95, max_used_days - days_threshold), \"Used %d days\", max_used_days);\n\n\tdie(_fail, \"Reached an unreachable code!!!\");\n\n\treturn 0;\n}\n", "stub.cpp": "#include \"message.h\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\nnamespace {\n\n/******************************** Begin testlib-related material ********************************/\n#ifdef _MSC_VER\n# define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n# define NORETURN __attribute__ ((noreturn))\n#else\n# define NORETURN\n#endif\n/********************************* End testlib-related material *********************************/\n\n\n// utils\n\n#define rep(i, n) for(int i = 0, i##__n = (int)(n); i < i##__n; ++i)\n\ntemplate int sz(const C& c) { return std::size(c); }\n\n// grader/manager protocol\n\nconst int secret_g2m = 0x647FB390;\nconst int secret_m2g = 0xB107D5C0;\nconst int code_mask = 0x0000000F;\n\nconst int M2G_CODE__OK = 0;\n\nconst int G2M_CODE__OK = 0;\nconst int G2M_CODE__OK_END_OF_PACKETS = 1;\nconst int G2M_CODE__PACKET_SIZE_INCORRECT = 2;\nconst int G2M_CODE__RETURN_MESSAGE_TOO_LARGE = 3;\nconst int G2M_CODE__PV_CALL_EXIT = 13;\nconst int G2M_CODE__PV_TAMPER_M2G = 14;\nconst int G2M_CODE__SILENT = 15;\n\n\nbool exit_allowed = false;\n\nNORETURN void authorized_exit(int exit_code) {\n exit_allowed = true;\n exit(exit_code);\n}\n\n\nFILE* fin = stdin;\nFILE* fout = stdout;\n\nvoid out_flush() {\n\tfflush(fout);\n}\n\nvoid write_int(int x) {\n\tif (1 != fwrite(&x, sizeof(x), 1, fout)) {\n\t\tfprintf(stderr, \"Could not write int to fout\\n\");\n\t\tauthorized_exit(3);\n\t}\n}\n\nvoid write_int_array(const int* arr, int len) {\n\tif (int ret = fwrite(arr, sizeof(int), len, fout); len != ret) {\n\t\tfprintf(stderr, \"Could not write int array of size %d to fout, fwrite returned %d\\n\", len, ret);\n\t\tauthorized_exit(3);\n\t}\n}\n\n\nvoid write_secret(int g2m_code = G2M_CODE__OK) {\n\twrite_int(secret_g2m | g2m_code);\n}\n\nNORETURN void die(int g2m_code) {\n\tif(g2m_code == G2M_CODE__OK) {\n\t\tfprintf(stderr, \"Shall not die with code OK\\n\");\n\t\tauthorized_exit(5);\n\t}\n\tfprintf(stderr, \"Dying with code %d\\n\", g2m_code);\n\tif(g2m_code != G2M_CODE__SILENT)\n\t\twrite_secret(g2m_code);\n\tfclose(fin);\n\tfclose(fout);\n\tauthorized_exit(0);\n}\n\n\nint read_int() {\n\tint x;\n\tif (1 != fread(&x, sizeof(x), 1, fin)) {\n\t\tfprintf(stderr, \"Could not read int from fin\\n\");\n\t\tauthorized_exit(3);\n\t}\n\treturn x;\n}\n\nvoid read_int_array(int* arr, int len) {\n\tif (int ret = fread(arr, sizeof(int), len, fin); len != ret) {\n\t\tfprintf(stderr, \"Could not read int array of size %d from fin, fread returned %d\\n\", len, ret);\n\t\tauthorized_exit(3);\n\t}\n}\n\n\nvoid read_secret() {\n\tint secret = read_int();\n\tif((secret & ~code_mask) != secret_m2g)\n\t\tdie(G2M_CODE__PV_TAMPER_M2G);\n\tint m2g_code = secret & code_mask;\n\tif(m2g_code != M2G_CODE__OK)\n\t\tdie(G2M_CODE__SILENT);\n}\n\nvoid check_exit_protocol() {\n if (!exit_allowed)\n die(G2M_CODE__PV_CALL_EXIT);\n}\n\n\n// problem utils\n\nint vb2int(const vector &v) {\n\tint r = 0;\n\trep(i, sz(v)) r |= ((v[i] ? 1 : 0) << i);\n\treturn r;\n}\n\nvector int2vb(int x, int len) {\n\tvector v(len);\n\trep(i, sz(v)) v[i] = (x >> i & 1) ? true : false;\n\treturn v;\n}\n\nvoid arr2vb(int* arr, int len, vector &r) {\n\tr.resize(len);\n\trep(i, len) r[i] = (arr[i / 32] >> (i & 31) & 1) ? true : false;\n}\n\nint compressed_len(int len) { return (len+31) / 32; }\n\nvoid vb2arr(vector v, int* arr, int len) {\n\tlen = sz(v);\n\trep(i, compressed_len(len)) arr[i] = 0;\n\trep(i, len) arr[i / 32] |= (v[i] ? 1 : 0) << (i & 31);\n}\n\n\n// grader logic\n\nconst int PACKET_SIZE = 31;\nconst int MAX_MESSAGE_SIZE = 1024;\nconst int MESSAGE_SIZE_LIMIT = 2 * MAX_MESSAGE_SIZE;\n\nNORETURN void run_encoder() {\n\tfor(int S; read_secret(), (S = read_int()) != -1; ) {\n\t\tint M_f[(MAX_MESSAGE_SIZE + 32 - 1) / 32];\n\t\tread_int_array(M_f, compressed_len(S));\n\t\tint C_f = read_int();\n\n\t\tvector M;\n\t\tarr2vb(M_f, S, M);\n\t\tvector C = int2vb(C_f, PACKET_SIZE);\n\n\t\tsend_message(M, C);\n\n\t\twrite_secret(G2M_CODE__OK_END_OF_PACKETS);\n\t\tout_flush();\n\t}\n\tdie(G2M_CODE__SILENT);\n}\n\nNORETURN void run_decoder() {\n\tfor(int K; read_secret(), (K = read_int()) != -1; ) {\n\t\tvector R_f(K, 0);\n\t\tread_int_array(R_f.data(), K);\n\n\t\tvector> R(K);\n\t\trep(i, K) R[i] = int2vb(R_f[i], PACKET_SIZE);\n\t\tvector D = receive_message(R);\n\t\tint L = sz(D);\n\n\t\tif(L < 0 || L > MESSAGE_SIZE_LIMIT) die(G2M_CODE__RETURN_MESSAGE_TOO_LARGE);\n\n\t\tint D_f[(MESSAGE_SIZE_LIMIT + 32 - 1) / 32];\n\t\tvb2arr(D, D_f, L);\n\n\t\twrite_secret();\n\t\twrite_int(L);\n\t\twrite_int_array(D_f, compressed_len(L));\n\t\tout_flush();\n\t}\n\tdie(G2M_CODE__SILENT);\n}\n\n\n} // namespace\n\n\nvector send_packet(vector A) {\n\tif(sz(A) != PACKET_SIZE) die(G2M_CODE__PACKET_SIZE_INCORRECT);\n\n\tint A_f = vb2int(A);\n\n\twrite_secret();\n\twrite_int(A_f);\n\tout_flush();\n\n\tread_secret();\n\tint B_f = read_int();\n\treturn int2vb(B_f, PACKET_SIZE);\n}\n\nint main(int argc, char **argv) {\n\tsignal(SIGPIPE, SIG_IGN);\n\tatexit(check_exit_protocol);\n\tat_quick_exit(check_exit_protocol);\n\n\tif(argc < 2) {\n\t\tfprintf(stderr, \"invalid args\\n\");\n\t\tauthorized_exit(1);\n\t}\n\n\tstring grader_id = argv[1];\n\tif (grader_id == \"0\")\n\t\trun_encoder();\n\n\tif (grader_id == \"1\")\n\t\trun_decoder();\n\n\tfprintf(stderr, \"invalid grader id: '%s'\\n\", grader_id.c_str());\n\tauthorized_exit(1);\n}\n", "message.h": "#include \n\nvoid send_message(std::vector M, std::vector C);\n\nstd::vector send_packet(std::vector A);\n\nstd::vector receive_message(std::vector> R);\n", "testlib.h": "/* \n * It is strictly recommended to include \"testlib.h\" before any other include \n * in your code. In this case testlib overrides compiler specific \"random()\".\n *\n * If you can't compile your code and compiler outputs something about \n * ambiguous call of \"random_shuffle\", \"rand\" or \"srand\" it means that \n * you shouldn't use them. Use \"shuffle\", and \"rnd.next()\" instead of them\n * because these calls produce stable result for any C++ compiler. Read \n * sample generator sources for clarification.\n *\n * Please read the documentation for class \"random_t\" and use \"rnd\" instance in\n * generators. Probably, these sample calls will be usefull for you:\n * rnd.next(); rnd.next(100); rnd.next(1, 2); \n * rnd.next(3.14); rnd.next(\"[a-z]{1,100}\").\n *\n * Also read about wnext() to generate off-center random distribution.\n *\n * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker.\n */\n\n#ifndef _TESTLIB_H_\n#define _TESTLIB_H_\n\n/*\n * Copyright (c) 2005-2018\n */\n\n#define VERSION \"0.9.21\"\n\n/* \n * Mike Mirzayanov\n *\n * This material is provided \"as is\", with absolutely no warranty expressed\n * or implied. Any use is at your own risk.\n *\n * Permission to use or copy this software for any purpose is hereby granted \n * without fee, provided the above notices are retained on all copies.\n * Permission to modify the code and to distribute modified code is granted,\n * provided the above notices are retained, and a notice that the code was\n * modified is included with the above copyright notice.\n *\n */\n\n/*\n * Kian Mirjalali:\n *\n * Modified to be compatible with CMS & requirements for preparing IOI tasks\n *\n * * defined FOR_LINUX in order to force linux-based line endings in validators.\n *\n * * Changed the ordering of checker arguments\n * from \n * to \n *\n * * Added \"Security Violation\" & \"Protocol Violation\" as new result types.\n *\n * * Changed checker quit behaviors to make it compliant with CMS.\n *\n * * The checker exit codes should always be 0 in CMS.\n *\n * * For partial scoring, forced quitp() functions to accept only scores in the range [0,1].\n * If the partial score is less than 1e-5, it becomes 1e-5, because 0 grades are considered wrong in CMS.\n * Grades in range [1e-5, 0.0001) are printed exactly (to prevent rounding to zero).\n * Grades in [0.0001, 1] are printed with 4 digits after decimal point.\n *\n * * Added the following utility types/variables/functions/methods:\n * type HaltListener (as a function with no parameters or return values)\n * vector __haltListeners\n * void registerHaltListener(HaltListener haltListener)\n * void callHaltListeners() (which is called in quit)\n * void closeOnHalt(FILE* file)\n * void closeOnHalt(F& f) (template using f.close())\n * void InStream::readSecret(string secret, TResult mismatchResult, string mismatchMessage, string eofMessage)\n * void InStream::readGraderResult()\n * +supporting conversion of graderResult to CMS result\n * void quitp(double), quitp(int)\n * void registerChecker(string probName, argc, argv)\n * void readBothSecrets(string secret)\n * void readBothGraderResults()\n * void quit(TResult)\n * bool compareTokens(string a, string b, char separator=' ')\n * void compareRemainingLines(int lineNo=1)\n * void skip_ok()\n *\n */\n\n/* NOTE: This file contains testlib library for C++.\n *\n * Check, using testlib running format:\n * check.exe [ [-appes]],\n * If result file is specified it will contain results.\n *\n * Validator, using testlib running format: \n * validator.exe < input.txt,\n * It will return non-zero exit code and writes message to standard output.\n *\n * Generator, using testlib running format: \n * gen.exe [parameter-1] [parameter-2] [... paramerter-n]\n * You can write generated test(s) into standard output or into the file(s).\n *\n * Interactor, using testlib running format: \n * interactor.exe [ [ [-appes]]],\n * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],\n * can be judged by checker later), reads program output from ouf (mapped to stdin),\n * writes output to program via stdout (use cout, printf, etc).\n */\n\nconst char* latestFeatures[] = {\n \"Fixed stringstream repeated usage issue\",\n \"Fixed compilation in g++ (for std=c++03)\",\n \"Batch of println functions (support collections, iterator ranges)\",\n \"Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation\",\n \"Allow any whitespace in readInts-like functions for non-validators\",\n \"Ignore 4+ command line arguments ifdef EJUDGE\",\n \"Speed up of vtos\",\n \"Show line number in validators in case of incorrect format\",\n \"Truncate huge checker/validator/interactor message\",\n \"Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type\",\n \"Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type\",\n \"Fixed compilation in VS 2015+\",\n \"Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines\",\n \"Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals\",\n \"Introduced split/tokenize functions to separate string by given char\",\n \"Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters\",\n \"Supported --testOverviewLogFileName for validator: bounds hits + features\",\n \"Fixed UB (sequence points) in random_t\",\n \"POINTS_EXIT_CODE returned back to 7 (instead of 0)\",\n \"Removed disable buffers for interactive problems, because it works unexpectedly in wine\",\n \"InStream over string: constructor of InStream from base InStream to inherit policies and std::string\",\n \"Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \\\"[n=%d,m=%d]\\\", n, m)\",\n \"Fixed incorrect interval parsing in patterns\",\n \"Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)\",\n \"Introduced disableFinalizeGuard() to switch off finalization checkings\",\n \"Use join() functions to format a range of items as a single string (separated by spaces or other separators)\",\n \"Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors\",\n \"Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7\",\n \"Fixed bug with nan in stringToDouble\", \n \"Fixed issue around overloads for size_t on x64\", \n \"Added attribute 'points' to the XML output in case of result=_points\", \n \"Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14\", \n \"Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading\", \n \"Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()\", \n \"Manual buffer in InStreams, some IO speed improvements\", \n \"Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true\", \n \"Introduced guard against missed quitf() in checker or readEof() in validators\", \n \"Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers\", \n \"Supported registerInteraction(argc, argv)\", \n \"Print checker message to the stderr instead of stdout\", \n \"Supported TResult _points to output calculated score, use quitp(...) functions\", \n \"Fixed to be compilable on Mac\", \n \"PC_BASE_EXIT_CODE=50 in case of defined TESTSYS\",\n \"Fixed issues 19-21, added __attribute__ format printf\", \n \"Some bug fixes\", \n \"ouf.readInt(1, 100) and similar calls return WA\", \n \"Modified random_t to avoid integer overflow\", \n \"Truncated checker output [patch by Stepan Gatilov]\", \n \"Renamed class random -> class random_t\", \n \"Supported name parameter for read-and-validation methods, like readInt(1, 2, \\\"n\\\")\", \n \"Fixed bug in readDouble()\", \n \"Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()\", \n \"Supported \\\"partially correct\\\", example: quitf(_pc(13), \\\"result=%d\\\", result)\", \n \"Added shuffle(begin, end), use it instead of random_shuffle(begin, end)\", \n \"Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode\", \n \"Package extended with samples of generators and validators\", \n \"Written the documentation for classes and public methods in testlib.h\",\n \"Implemented random routine to support generators, use registerGen() to switch it on\",\n \"Implemented strict mode to validate tests, use registerValidation() to switch it on\",\n \"Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output\",\n \"Added InStream::readLong() and removed InStream::readLongint()\",\n \"Now no footer added to each report by default (use directive FOOTER to switch on)\",\n \"Now every checker has a name, use setName(const char* format, ...) to set it\",\n \"Now it is compatible with TTS (by Kittens Computing)\",\n \"Added \\'ensure(condition, message = \\\"\\\")\\' feature, it works like assert()\",\n \"Fixed compatibility with MS C++ 7.1\",\n \"Added footer with exit code information\",\n \"Added compatibility with EJUDGE (compile with EJUDGE directive)\",\n \"Added compatibility with Contester (compile with CONTESTER directive)\"\n };\n\n#define FOR_LINUX\n\n#ifdef _MSC_VER\n#define _CRT_SECURE_NO_DEPRECATE\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_NO_VA_START_VALIDATION\n#endif\n\n/* Overrides random() for Borland C++. */\n#define random __random_deprecated\n#include \n#include \n#include \n#include \n#undef random\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ || __CYGWIN__ )\n# if !defined(_MSC_VER) || _MSC_VER>1400\n# define NOMINMAX 1\n# include \n# else\n# define WORD unsigned short\n# include \n# endif\n# include \n# define ON_WINDOWS\n# if defined(_MSC_VER) && _MSC_VER>1400\n# pragma warning( disable : 4127 )\n# pragma warning( disable : 4146 )\n# pragma warning( disable : 4458 )\n# endif\n#else\n# define WORD unsigned short\n# include \n#endif\n\n#if defined(FOR_WINDOWS) && defined(FOR_LINUX)\n#error Only one target system is allowed\n#endif\n\n#ifndef LLONG_MIN\n#define LLONG_MIN (-9223372036854775807LL - 1)\n#endif\n\n#ifndef ULLONG_MAX\n#define ULLONG_MAX (18446744073709551615)\n#endif\n\n#define LF ((char)10)\n#define CR ((char)13)\n#define TAB ((char)9)\n#define SPACE ((char)' ')\n#define EOFC (255)\n\n#ifndef OK_EXIT_CODE\n# ifdef CONTESTER\n# define OK_EXIT_CODE 0xAC\n# else\n# define OK_EXIT_CODE 0\n# endif\n#endif\n\n#ifndef WA_EXIT_CODE\n# ifdef EJUDGE\n# define WA_EXIT_CODE 5\n# elif defined(CONTESTER)\n# define WA_EXIT_CODE 0xAB\n# else\n# define WA_EXIT_CODE 1\n# endif\n#endif\n\n#ifndef PE_EXIT_CODE\n# ifdef EJUDGE\n# define PE_EXIT_CODE 4\n# elif defined(CONTESTER)\n# define PE_EXIT_CODE 0xAA\n# else\n# define PE_EXIT_CODE 2\n# endif\n#endif\n\n#ifndef FAIL_EXIT_CODE\n# ifdef EJUDGE\n# define FAIL_EXIT_CODE 6\n# elif defined(CONTESTER)\n# define FAIL_EXIT_CODE 0xA3\n# else\n# define FAIL_EXIT_CODE 3\n# endif\n#endif\n\n#ifndef DIRT_EXIT_CODE\n# ifdef EJUDGE\n# define DIRT_EXIT_CODE 6\n# else\n# define DIRT_EXIT_CODE 4\n# endif\n#endif\n\n#ifndef POINTS_EXIT_CODE\n# define POINTS_EXIT_CODE 7\n#endif\n\n#ifndef UNEXPECTED_EOF_EXIT_CODE\n# define UNEXPECTED_EOF_EXIT_CODE 8\n#endif\n\n#ifndef SV_EXIT_CODE\n# define SV_EXIT_CODE 20\n#endif\n\n#ifndef PV_EXIT_CODE\n# define PV_EXIT_CODE 21\n#endif\n\n#ifndef PC_BASE_EXIT_CODE\n# ifdef TESTSYS\n# define PC_BASE_EXIT_CODE 50\n# else\n# define PC_BASE_EXIT_CODE 0\n# endif\n#endif\n\n#ifdef __GNUC__\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))\n#else\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]\n#endif\n\n#ifdef ON_WINDOWS\n#define I64 \"%I64d\"\n#define U64 \"%I64u\"\n#else\n#define I64 \"%lld\"\n#define U64 \"%llu\"\n#endif\n\n#ifdef _MSC_VER\n# define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n# define NORETURN __attribute__ ((noreturn))\n#else\n# define NORETURN\n#endif\n\n/**************** HaltListener material ****************/\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntypedef std::function HaltListener;\n#else\ntypedef void (*HaltListener)();\n#endif\n\nstd::vector __haltListeners;\n\ninline void registerHaltListener(HaltListener haltListener) {\n __haltListeners.push_back(haltListener);\n}\n\ninline void callHaltListeners() {\n // Removing and calling haltListeners in reverse order.\n while (!__haltListeners.empty()) {\n HaltListener haltListener = __haltListeners.back();\n __haltListeners.pop_back();\n haltListener();\n }\n}\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ninline void closeOnHalt(FILE* file) {\n registerHaltListener([file] { fclose(file); });\n}\ntemplate\ninline void closeOnHalt(F& f) {\n registerHaltListener([&f] { f.close(); });\n}\n#endif\n/*******************************************************/\n\nstatic char __testlib_format_buffer[16777216];\nstatic int __testlib_format_buffer_usage_count = 0;\n\n#define FMT_TO_RESULT(fmt, cstr, result) std::string result; \\\n if (__testlib_format_buffer_usage_count != 0) \\\n __testlib_fail(\"FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0\"); \\\n __testlib_format_buffer_usage_count++; \\\n va_list ap; \\\n va_start(ap, fmt); \\\n vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \\\n va_end(ap); \\\n __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \\\n result = std::string(__testlib_format_buffer); \\\n __testlib_format_buffer_usage_count--; \\\n\nconst long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;\n\nNORETURN static void __testlib_fail(const std::string& message);\n\ntemplate\nstatic inline T __testlib_abs(const T& x)\n{\n return x > 0 ? x : -x;\n}\n\ntemplate\nstatic inline T __testlib_min(const T& a, const T& b)\n{\n return a < b ? a : b;\n}\n\ntemplate\nstatic inline T __testlib_max(const T& a, const T& b)\n{\n return a > b ? a : b;\n}\n\nstatic bool __testlib_prelimIsNaN(double r)\n{\n volatile double ra = r;\n#ifndef __BORLANDC__\n return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);\n#else\n return std::_isnan(ra);\n#endif\n}\n\nstatic std::string removeDoubleTrailingZeroes(std::string value)\n{\n while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)\n value = value.substr(0, value.length() - 1);\n return value + '0';\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nstd::string format(const char* fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt, result);\n return result;\n}\n\nstd::string format(const std::string fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt.c_str(), result);\n return result;\n}\n\nstatic std::string __testlib_part(const std::string& s);\n\nstatic bool __testlib_isNaN(double r)\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n volatile double ra = r;\n long long llr1, llr2;\n std::memcpy((void*)&llr1, (void*)&ra, sizeof(double)); \n ra = -ra;\n std::memcpy((void*)&llr2, (void*)&ra, sizeof(double)); \n long long llnan = 0xFFF8000000000000LL;\n return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;\n}\n\nstatic double __testlib_nan()\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n#ifndef NAN\n long long llnan = 0xFFF8000000000000LL;\n double nan;\n std::memcpy(&nan, &llnan, sizeof(double));\n return nan;\n#else\n return NAN;\n#endif\n}\n\nstatic bool __testlib_isInfinite(double r)\n{\n volatile double ra = r;\n return (ra > 1E300 || ra < -1E300);\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)\n{\n if (__testlib_isNaN(expected))\n {\n return __testlib_isNaN(result);\n }\n else \n if (__testlib_isInfinite(expected))\n {\n if (expected > 0)\n {\n return result > 0 && __testlib_isInfinite(result);\n }\n else\n {\n return result < 0 && __testlib_isInfinite(result);\n }\n }\n else \n if (__testlib_isNaN(result) || __testlib_isInfinite(result))\n {\n return false;\n }\n else \n if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)\n {\n return true;\n }\n else\n {\n double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n return result + 1E-15 >= minv && result <= maxv + 1E-15;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline double doubleDelta(double expected, double result)\n{\n double absolute = __testlib_abs(result - expected);\n \n if (__testlib_abs(expected) > 1E-9)\n {\n double relative = __testlib_abs(absolute / expected);\n return __testlib_min(absolute, relative);\n }\n else\n return absolute;\n}\n\n#if !defined(_MSC_VER) || _MSC_VER<1900\n#ifndef _fileno\n#define _fileno(_stream) ((_stream)->_file)\n#endif\n#endif\n\n#ifndef O_BINARY\nstatic void __testlib_set_binary(\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\n std::FILE* file\n)\n#else\nstatic void __testlib_set_binary(std::FILE* file)\n#endif\n{\n#ifdef O_BINARY\n if (NULL != file)\n {\n#ifndef __BORLANDC__\n _setmode(_fileno(file), O_BINARY);\n#else\n setmode(fileno(file), O_BINARY);\n#endif\n }\n#endif\n}\n\n/*\n * Very simple regex-like pattern.\n * It used for two purposes: validation and generation.\n * \n * For example, pattern(\"[a-z]{1,5}\").next(rnd) will return\n * random string from lowercase latin letters with length \n * from 1 to 5. It is easier to call rnd.next(\"[a-z]{1,5}\") \n * for the same effect. \n * \n * Another samples:\n * \"mike|john\" will generate (match) \"mike\" or \"john\";\n * \"-?[1-9][0-9]{0,3}\" will generate (match) non-zero integers from -9999 to 9999;\n * \"id-([ac]|b{2})\" will generate (match) \"id-a\", \"id-bb\", \"id-c\";\n * \"[^0-9]*\" will match sequences (empty or non-empty) without digits, you can't \n * use it for generations.\n *\n * You can't use pattern for generation if it contains meta-symbol '*'. Also it\n * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].\n *\n * For matching very simple greedy algorithm is used. For example, pattern\n * \"[0-9]?1\" will not match \"1\", because of greedy nature of matching.\n * Alternations (meta-symbols \"|\") are processed with brute-force algorithm, so \n * do not use many alternations in one expression.\n *\n * If you want to use one expression many times it is better to compile it into\n * a single pattern like \"pattern p(\"[a-z]+\")\". Later you can use \n * \"p.matches(std::string s)\" or \"p.next(random_t& rd)\" to check matching or generate\n * new string by pattern.\n * \n * Simpler way to read token and check it for pattern matching is \"inf.readToken(\"[a-z]+\")\".\n */\nclass random_t;\n\nclass pattern\n{\npublic:\n /* Create pattern instance by string. */\n pattern(std::string s);\n /* Generate new string by pattern and given random_t. */\n std::string next(random_t& rnd) const;\n /* Checks if given string match the pattern. */\n bool matches(const std::string& s) const;\n /* Returns source string of the pattern. */\n std::string src() const;\nprivate:\n bool matches(const std::string& s, size_t pos) const;\n\n std::string s;\n std::vector children;\n std::vector chars;\n int from;\n int to;\n};\n\n/* \n * Use random_t instances to generate random values. It is preffered\n * way to use randoms instead of rand() function or self-written \n * randoms.\n *\n * Testlib defines global variable \"rnd\" of random_t class.\n * Use registerGen(argc, argv, 1) to setup random_t seed be command\n * line (to use latest random generator version).\n *\n * Random generates uniformly distributed values if another strategy is\n * not specified explicitly.\n */\nclass random_t\n{\nprivate:\n unsigned long long seed;\n static const unsigned long long multiplier;\n static const unsigned long long addend;\n static const unsigned long long mask;\n static const int lim;\n\n long long nextBits(int bits) \n {\n if (bits <= 48)\n {\n seed = (seed * multiplier + addend) & mask;\n return (long long)(seed >> (48 - bits));\n }\n else\n {\n if (bits > 63)\n __testlib_fail(\"random_t::nextBits(int bits): n must be less than 64\");\n\n int lowerBitCount = (random_t::version == 0 ? 31 : 32);\n \n long long left = (nextBits(31) << 32);\n long long right = nextBits(lowerBitCount);\n \n return left ^ right;\n }\n }\n\npublic:\n static int version;\n\n /* New random_t with fixed seed. */\n random_t()\n : seed(3905348978240129619LL)\n {\n }\n\n /* Sets seed by command line. */\n void setSeed(int argc, char* argv[])\n {\n random_t p;\n\n seed = 3905348978240129619LL;\n for (int i = 1; i < argc; i++)\n {\n std::size_t le = std::strlen(argv[i]);\n for (std::size_t j = 0; j < le; j++)\n seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;\n seed += multiplier / addend;\n }\n\n seed = seed & mask;\n }\n\n /* Sets seed by given value. */ \n void setSeed(long long _seed)\n {\n _seed = (_seed ^ multiplier) & mask;\n seed = _seed;\n }\n\n#ifndef __BORLANDC__\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(const std::string& ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#else\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(std::string ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#endif\n\n /* Random value in range [0, n-1]. */\n int next(int n)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(int n): n must be positive\");\n\n if ((n & -n) == n) // n is a power of 2\n return (int)((n * (long long)nextBits(31)) >> 31);\n\n const long long limit = INT_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(31);\n } while (bits >= limit);\n\n return int(bits % n);\n }\n\n /* Random value in range [0, n-1]. */\n unsigned int next(unsigned int n)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::next(unsigned int n): n must be less INT_MAX\");\n return (unsigned int)next(int(n));\n }\n\n /* Random value in range [0, n-1]. */\n long long next(long long n) \n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(long long n): n must be positive\");\n\n const long long limit = __TESTLIB_LONGLONG_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(63);\n } while (bits >= limit);\n\n return bits % n;\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long long next(unsigned long long n)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long long n): n must be less LONGLONG_MAX\");\n return (unsigned long long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n long next(long n)\n {\n return (long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long next(unsigned long n)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long n): n must be less LONG_MAX\");\n return (unsigned long)next((unsigned long long)(n));\n }\n\n /* Returns random value in range [from,to]. */\n int next(int from, int to)\n {\n return int(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n unsigned int next(unsigned int from, unsigned int to)\n {\n return (unsigned int)(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n long long next(long long from, long long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long long next(unsigned long long from, unsigned long long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n long next(long from, long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long next(unsigned long from, unsigned long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long from, unsigned long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Random double value in range [0, 1). */\n double next() \n {\n long long left = ((long long)(nextBits(26)) << 27);\n long long right = nextBits(27);\n return (double)(left + right) / (double)(1LL << 53);\n }\n\n /* Random double value in range [0, n). */\n double next(double n)\n {\n return n * next();\n }\n\n /* Random double value in range [from, to). */\n double next(double from, double to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(double from, double to): from can't not exceed to\");\n return next(to - from) + from;\n }\n\n /* Returns random element from container. */\n template \n typename Container::value_type any(const Container& c)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Container& c): c.size() must be positive\");\n return *(c.begin() + next(size));\n }\n\n /* Returns random element from iterator range. */\n template \n typename Iter::value_type any(const Iter& begin, const Iter& end)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end): range must have positive length\");\n return *(begin + next(size));\n }\n\n /* Random string value by given pattern (see pattern documentation). */\n#ifdef __GNUC__\n __attribute__ ((format (printf, 2, 3)))\n#endif\n std::string next(const char* format, ...)\n {\n FMT_TO_RESULT(format, format, ptrn);\n return next(ptrn);\n }\n\n /* \n * Weighted next. If type == 0 than it is usual \"next()\".\n *\n * If type = 1, than it returns \"max(next(), next())\"\n * (the number of \"max\" functions equals to \"type\").\n *\n * If type < 0, than \"max\" function replaces with \"min\".\n */\n int wnext(int n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(int n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n int result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));\n\n return int(n * p);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n long long wnext(long long n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(long long n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n long long result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(int type)\n {\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return p;\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(double n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(double n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return n * result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return n * p;\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned int wnext(unsigned int n, int type)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::wnext(unsigned int n, int type): n must be less INT_MAX\");\n return (unsigned int)wnext(int(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long long wnext(unsigned long long n, int type)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX\");\n\n return (unsigned long long)wnext((long long)(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n long wnext(long n, int type)\n {\n return (long)wnext((long long)(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long wnext(unsigned long n, int type)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long n, int type): n must be less LONG_MAX\");\n\n return (unsigned long)wnext((unsigned long long)(n), type);\n }\n\n /* Returns weighted random value in range [from, to]. */\n int wnext(int from, int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(int from, int to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n int wnext(unsigned int from, unsigned int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to\");\n return int(wnext(to - from + 1, type) + from);\n }\n \n /* Returns weighted random value in range [from, to]. */\n long long wnext(long long from, long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long long from, long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long long wnext(unsigned long long from, unsigned long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n long wnext(long from, long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long from, long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long wnext(unsigned long from, unsigned long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random double value in range [from, to). */\n double wnext(double from, double to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(double from, double to, int type): from can't not exceed to\");\n return wnext(to - from, type) + from;\n }\n\n /* Returns weighted random element from container. */\n template \n typename Container::value_type wany(const Container& c, int type)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::wany(const Container& c, int type): c.size() must be positive\");\n return *(c.begin() + wnext(size, type));\n }\n\n /* Returns weighted random element from iterator range. */\n template \n typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length\");\n return *(begin + wnext(size, type));\n }\n\n template\n std::vector perm(T size, E first)\n {\n if (size <= 0)\n __testlib_fail(\"random_t::perm(T size, E first = 0): size must be positive\");\n std::vector p(size);\n for (T i = 0; i < size; i++)\n p[i] = first + i;\n if (size > 1)\n for (T i = 1; i < size; i++)\n std::swap(p[i], p[next(i + 1)]);\n return p;\n }\n\n template\n std::vector perm(T size)\n {\n return perm(size, T(0));\n }\n};\n\nconst int random_t::lim = 25;\nconst unsigned long long random_t::multiplier = 0x5DEECE66DLL;\nconst unsigned long long random_t::addend = 0xBLL;\nconst unsigned long long random_t::mask = (1LL << 48) - 1;\nint random_t::version = -1;\n\n/* Pattern implementation */\nbool pattern::matches(const std::string& s) const\n{\n return matches(s, 0);\n}\n\nstatic bool __pattern_isSlash(const std::string& s, size_t pos)\n{\n return s[pos] == '\\\\';\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)\n{\n if (pos >= s.length())\n return false;\n\n int slashes = 0;\n\n int before = int(pos) - 1;\n while (before >= 0 && s[before] == '\\\\')\n before--, slashes++;\n\n return slashes % 2 == 0 && s[pos] == value;\n}\n\nstatic char __pattern_getChar(const std::string& s, size_t& pos)\n{\n if (__pattern_isSlash(s, pos))\n pos += 2;\n else\n pos++;\n\n return s[pos - 1];\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector chars)\n{\n int result = 0;\n\n while (pos < s.length())\n {\n char c = s[pos++];\n if (!std::binary_search(chars.begin(), chars.end(), c))\n break;\n else\n result++;\n }\n\n return result;\n}\n\nstd::string pattern::src() const\n{\n return s;\n}\n\nbool pattern::matches(const std::string& s, size_t pos) const\n{\n std::string result;\n\n if (to > 0)\n {\n int size = __pattern_greedyMatch(s, pos, chars);\n if (size < from)\n return false;\n if (size > to)\n size = to;\n pos += size;\n }\n\n if (children.size() > 0)\n {\n for (size_t child = 0; child < children.size(); child++)\n if (children[child].matches(s, pos))\n return true;\n return false;\n }\n else\n return pos == s.length();\n}\n\nstd::string pattern::next(random_t& rnd) const\n{\n std::string result;\n result.reserve(20);\n\n if (to == INT_MAX)\n __testlib_fail(\"pattern::next(random_t& rnd): can't process character '*' for generation\");\n\n if (to > 0)\n {\n int count = rnd.next(to - from + 1) + from;\n for (int i = 0; i < count; i++)\n result += chars[rnd.next(int(chars.size()))];\n }\n\n if (children.size() > 0)\n {\n int child = rnd.next(int(children.size()));\n result += children[child].next(rnd);\n }\n\n return result;\n}\n\nstatic void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)\n{\n if (pos >= s.length())\n {\n from = to = 1;\n return;\n }\n \n if (__pattern_isCommandChar(s, pos, '{'))\n {\n std::vector parts;\n std::string part;\n\n pos++;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))\n {\n if (__pattern_isCommandChar(s, pos, ','))\n parts.push_back(part), part = \"\", pos++;\n else\n part += __pattern_getChar(s, pos);\n }\n\n if (part != \"\")\n parts.push_back(part);\n\n if (!__pattern_isCommandChar(s, pos, '}'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (parts.size() < 1 || parts.size() > 2)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector numbers;\n\n for (size_t i = 0; i < parts.size(); i++)\n {\n if (parts[i].length() == 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n int number;\n if (std::sscanf(parts[i].c_str(), \"%d\", &number) != 1)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n numbers.push_back(number);\n }\n\n if (numbers.size() == 1)\n from = to = numbers[0];\n else\n from = numbers[0], to = numbers[1];\n\n if (from > to)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n }\n else\n {\n if (__pattern_isCommandChar(s, pos, '?'))\n {\n from = 0, to = 1, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '*'))\n {\n from = 0, to = INT_MAX, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '+'))\n {\n from = 1, to = INT_MAX, pos++;\n return;\n }\n \n from = to = 1;\n }\n}\n\nstatic std::vector __pattern_scanCharSet(const std::string& s, size_t& pos)\n{\n if (pos >= s.length())\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector result;\n\n if (__pattern_isCommandChar(s, pos, '['))\n {\n pos++;\n bool negative = __pattern_isCommandChar(s, pos, '^');\n\n char prev = 0;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))\n {\n if (__pattern_isCommandChar(s, pos, '-') && prev != 0)\n {\n pos++;\n\n if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']'))\n {\n result.push_back(prev);\n prev = '-';\n continue;\n }\n\n char next = __pattern_getChar(s, pos);\n if (prev > next)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n for (char c = prev; c != next; c++)\n result.push_back(c);\n result.push_back(next);\n\n prev = 0;\n }\n else\n {\n if (prev != 0)\n result.push_back(prev);\n prev = __pattern_getChar(s, pos);\n }\n }\n\n if (prev != 0)\n result.push_back(prev);\n\n if (!__pattern_isCommandChar(s, pos, ']'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (negative)\n {\n std::sort(result.begin(), result.end());\n std::vector actuals;\n for (int code = 0; code < 255; code++)\n {\n char c = char(code);\n if (!std::binary_search(result.begin(), result.end(), c))\n actuals.push_back(c);\n }\n result = actuals;\n }\n\n std::sort(result.begin(), result.end());\n }\n else\n result.push_back(__pattern_getChar(s, pos));\n\n return result;\n}\n\npattern::pattern(std::string s): s(s), from(0), to(0)\n{\n std::string t;\n for (size_t i = 0; i < s.length(); i++)\n if (!__pattern_isCommandChar(s, i, ' '))\n t += s[i];\n s = t;\n\n int opened = 0;\n int firstClose = -1;\n std::vector seps;\n\n for (size_t i = 0; i < s.length(); i++)\n {\n if (__pattern_isCommandChar(s, i, '('))\n {\n opened++;\n continue;\n }\n\n if (__pattern_isCommandChar(s, i, ')'))\n {\n opened--;\n if (opened == 0 && firstClose == -1)\n firstClose = int(i);\n continue;\n }\n \n if (opened < 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (__pattern_isCommandChar(s, i, '|') && opened == 0)\n seps.push_back(int(i));\n }\n\n if (opened != 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (seps.size() == 0 && firstClose + 1 == (int)s.length() \n && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))\n {\n children.push_back(pattern(s.substr(1, s.length() - 2)));\n }\n else\n {\n if (seps.size() > 0)\n {\n seps.push_back(int(s.length()));\n int last = 0;\n\n for (size_t i = 0; i < seps.size(); i++)\n {\n children.push_back(pattern(s.substr(last, seps[i] - last)));\n last = seps[i] + 1;\n }\n }\n else\n {\n size_t pos = 0;\n chars = __pattern_scanCharSet(s, pos);\n __pattern_scanCounts(s, pos, from, to);\n if (pos < s.length())\n children.push_back(pattern(s.substr(pos)));\n }\n }\n}\n/* End of pattern implementation */\n\ntemplate \ninline bool isEof(C c)\n{\n return c == EOFC;\n}\n\ntemplate \ninline bool isEoln(C c)\n{\n return (c == LF || c == CR);\n}\n\ntemplate\ninline bool isBlanks(C c)\n{\n return (c == LF || c == CR || c == SPACE || c == TAB);\n}\n\nenum TMode\n{\n _input, _output, _answer\n};\n\n/* Outcomes 6-15 are reserved for future use. */\nenum TResult\n{\n _ok = 0,\n _wa = 1,\n _pe = 2,\n _fail = 3,\n _dirt = 4,\n _points = 5,\n _unexpected_eof = 8,\n _sv = 10,\n _pv = 11,\n _partially = 16\n};\n\nenum TTestlibMode\n{\n _unknown, _checker, _validator, _generator, _interactor\n};\n\n#define _pc(exitCode) (TResult(_partially + (exitCode)))\n\n/* Outcomes 6-15 are reserved for future use. */\nconst std::string outcomes[] = {\n \"accepted\",\n \"wrong-answer\",\n \"presentation-error\",\n \"fail\",\n \"fail\",\n#ifndef PCMS2\n \"points\",\n#else\n \"relative-scoring\",\n#endif\n \"reserved\",\n \"reserved\",\n \"unexpected-eof\",\n \"reserved\",\n \"security-violation\",\n \"protocol-violation\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"partially-correct\"\n};\n\nclass InputStreamReader\n{\npublic:\n virtual int curChar() = 0; \n virtual int nextChar() = 0; \n virtual void skipChar() = 0;\n virtual void unreadChar(int c) = 0;\n virtual std::string getName() = 0;\n virtual bool eof() = 0;\n virtual void close() = 0;\n virtual int getLine() = 0;\n virtual ~InputStreamReader() = 0;\n};\n\nInputStreamReader::~InputStreamReader()\n{\n // No operations.\n}\n\nclass StringInputStreamReader: public InputStreamReader\n{\nprivate:\n std::string s;\n size_t pos;\n\npublic:\n StringInputStreamReader(const std::string& content): s(content), pos(0)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (pos >= s.length())\n return EOFC;\n else\n return s[pos];\n }\n\n int nextChar()\n {\n if (pos >= s.length())\n {\n pos++;\n return EOFC;\n }\n else\n return s[pos++];\n }\n\n void skipChar()\n {\n pos++;\n }\n\n void unreadChar(int c)\n { \n if (pos == 0)\n __testlib_fail(\"FileFileInputStreamReader::unreadChar(int): pos == 0.\");\n pos--;\n if (pos < s.length())\n s[pos] = char(c);\n }\n\n std::string getName()\n {\n return __testlib_part(s);\n }\n\n int getLine()\n {\n return -1;\n }\n\n bool eof()\n {\n return pos >= s.length();\n }\n\n void close()\n {\n // No operations.\n }\n};\n\nclass FileInputStreamReader: public InputStreamReader\n{\nprivate:\n std::FILE* file;\n std::string name;\n int line;\n std::vector undoChars;\n\n inline int postprocessGetc(int getcResult)\n {\n if (getcResult != EOF)\n return getcResult;\n else\n return EOFC;\n }\n\n int getc(FILE* file)\n {\n int c;\n if (undoChars.empty())\n c = ::getc(file);\n else\n {\n c = undoChars.back();\n undoChars.pop_back();\n }\n\n if (c == LF)\n line++;\n return c;\n }\n\n int ungetc(int c/*, FILE* file*/)\n {\n if (c == LF)\n line--;\n undoChars.push_back(c);\n return c;\n }\n\npublic:\n FileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (feof(file))\n return EOFC;\n else\n {\n int c = getc(file);\n ungetc(c/*, file*/);\n return postprocessGetc(c);\n }\n }\n\n int nextChar()\n {\n if (feof(file))\n return EOFC;\n else\n return postprocessGetc(getc(file));\n }\n\n void skipChar()\n {\n getc(file);\n }\n\n void unreadChar(int c)\n { \n ungetc(c/*, file*/);\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n\n bool eof()\n {\n if (NULL == file || feof(file))\n return true;\n else\n {\n int c = nextChar();\n if (c == EOFC || (c == EOF && feof(file)))\n return true;\n unreadChar(c);\n return false;\n }\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nclass BufferedFileInputStreamReader: public InputStreamReader\n{\nprivate:\n static const size_t BUFFER_SIZE;\n static const size_t MAX_UNREAD_COUNT; \n \n std::FILE* file;\n char* buffer;\n bool* isEof;\n int bufferPos;\n size_t bufferSize;\n\n std::string name;\n int line;\n\n bool refill()\n {\n if (NULL == file)\n __testlib_fail(\"BufferedFileInputStreamReader: file == NULL (\" + getName() + \")\");\n\n if (bufferPos >= int(bufferSize))\n {\n size_t readSize = fread(\n buffer + MAX_UNREAD_COUNT,\n 1,\n BUFFER_SIZE - MAX_UNREAD_COUNT,\n file\n );\n\n if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT\n && ferror(file))\n __testlib_fail(\"BufferedFileInputStreamReader: unable to read (\" + getName() + \")\");\n\n bufferSize = MAX_UNREAD_COUNT + readSize;\n bufferPos = int(MAX_UNREAD_COUNT);\n std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);\n\n return readSize > 0;\n }\n else\n return true;\n }\n\n char increment()\n {\n char c;\n if ((c = buffer[bufferPos++]) == LF)\n line++;\n return c;\n }\n\npublic:\n BufferedFileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n buffer = new char[BUFFER_SIZE];\n isEof = new bool[BUFFER_SIZE];\n bufferSize = MAX_UNREAD_COUNT;\n bufferPos = int(MAX_UNREAD_COUNT);\n }\n\n ~BufferedFileInputStreamReader()\n {\n if (NULL != buffer)\n {\n delete[] buffer;\n buffer = NULL;\n }\n if (NULL != isEof)\n {\n delete[] isEof;\n isEof = NULL;\n }\n }\n\n int curChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : buffer[bufferPos];\n }\n\n int nextChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : increment();\n }\n\n void skipChar()\n {\n increment();\n }\n\n void unreadChar(int c)\n { \n bufferPos--;\n if (bufferPos < 0)\n __testlib_fail(\"BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0\");\n isEof[bufferPos] = (c == EOFC);\n buffer[bufferPos] = char(c);\n if (c == LF)\n line--;\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n \n bool eof()\n {\n return !refill() || EOFC == curChar();\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nconst size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;\nconst size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2; \n\n/*\n * Streams to be used for reading data in checkers or validators.\n * Each read*() method moves pointer to the next character after the\n * read value.\n */\nstruct InStream\n{\n /* Do not use them. */\n InStream();\n ~InStream();\n\n /* Wrap std::string with InStream. */\n InStream(const InStream& baseStream, std::string content);\n\n InputStreamReader* reader;\n int lastLine;\n\n std::string name;\n TMode mode;\n bool opened;\n bool stdfile;\n bool strict;\n\n int wordReserveSize;\n std::string _tmpReadToken;\n\n int readManyIteration;\n size_t maxFileSize;\n size_t maxTokenLength;\n size_t maxMessageLength;\n\n void init(std::string fileName, TMode mode);\n void init(std::FILE* f, TMode mode);\n\n /* Moves stream pointer to the first non-white-space character or EOF. */ \n void skipBlanks();\n \n /* Returns current character in the stream. Doesn't remove it from stream. */\n char curChar();\n /* Moves stream pointer one character forward. */\n void skipChar();\n /* Returns current character and moves pointer one character forward. */\n char nextChar();\n \n /* Returns current character and moves pointer one character forward. */\n char readChar();\n /* As \"readChar()\" but ensures that the result is equal to given parameter. */\n char readChar(char c);\n /* As \"readChar()\" but ensures that the result is equal to the space (code=32). */\n char readSpace();\n /* Puts back the character into the stream. */\n void unreadChar(char c);\n\n /* Reopens stream, you should not use it. */\n void reset(std::FILE* file = NULL);\n /* Checks that current position is EOF. If not it doesn't move stream pointer. */\n bool eof();\n /* Moves pointer to the first non-white-space character and calls \"eof()\". */\n bool seekEof();\n\n /* \n * Checks that current position contains EOLN. \n * If not it doesn't move stream pointer. \n * In strict mode expects \"#13#10\" for windows or \"#10\" for other platforms.\n */\n bool eoln();\n /* Moves pointer to the first non-space and non-tab character and calls \"eoln()\". */\n bool seekEoln();\n\n /* Moves stream pointer to the first character of the next line (if exists). */\n void nextLine();\n\n /* \n * Reads new token. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n std::string readWord();\n /* The same as \"readWord()\", it is preffered to use \"readToken()\". */\n std::string readToken();\n /* The same as \"readWord()\", but ensures that token matches to given pattern. */\n std::string readWord(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readWord(const pattern& p, const std::string& variableName = \"\");\n std::vector readWords(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readWords(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n /* The same as \"readToken()\", but ensures that token matches to given pattern. */\n std::string readToken(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readToken(const pattern& p, const std::string& variableName = \"\");\n std::vector readTokens(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readTokens(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n\n void readWordTo(std::string& result);\n void readWordTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n void readTokenTo(std::string& result);\n void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads new long long value. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n long long readLong();\n unsigned long long readUnsignedLong();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInteger();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInt();\n\n /* As \"readLong()\" but ensures that value in the range [minv,maxv]. */\n long long readLong(long long minv, long long maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of long longs. */\n std::vector readLongs(int size, long long minv, long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n unsigned long long readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* As \"readInteger()\" but ensures that value in the range [minv,maxv]. */\n int readInteger(int minv, int maxv, const std::string& variableName = \"\");\n /* As \"readInt()\" but ensures that value in the range [minv,maxv]. */\n int readInt(int minv, int maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of integers. */\n std::vector readIntegers(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* Reads space-separated sequence of integers. */\n std::vector readInts(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readReal();\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readDouble();\n \n /* As \"readReal()\" but ensures that value in the range [minv,maxv]. */\n double readReal(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readReals(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* As \"readDouble()\" but ensures that value in the range [minv,maxv]. */\n double readDouble(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readDoubles(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n \n /* \n * As \"readReal()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * As \"readDouble()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n \n /* As readLine(). */\n std::string readString();\n /* Read many lines. */\n std::vector readStrings(int size, int indexBase = 1);\n /* See readLine(). */\n void readStringTo(std::string& result);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readStrings(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readStrings(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads line from the current position to EOLN or EOF. Moves stream pointer to \n * the first character of the new line (if possible). \n */\n std::string readLine();\n /* Read many lines. */\n std::vector readLines(int size, int indexBase = 1);\n /* See readLine(). */\n void readLineTo(std::string& result);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readLines(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readLines(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* Reads EOLN or fails. Use it in validators. Calls \"eoln()\" method internally. */\n void readEoln();\n /* Reads EOF or fails. Use it in validators. Calls \"eof()\" method internally. */\n void readEof();\n\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quit(TResult result, const char* msg);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quitf(TResult result, const char* msg, ...);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quits(TResult result, std::string msg);\n\n /* \n * Checks condition and aborts a program if codition is false.\n * Returns _wa for ouf and _fail on any other streams.\n */\n #ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n #endif\n void ensuref(bool cond, const char* format, ...);\n void __testlib_ensure(bool cond, std::string message);\n\n void close();\n\n const static int NO_INDEX = INT_MAX;\n\n const static WORD LightGray = 0x07; \n const static WORD LightRed = 0x0c; \n const static WORD LightCyan = 0x0b; \n const static WORD LightGreen = 0x0a; \n const static WORD LightYellow = 0x0e; \n const static WORD LightMagenta = 0x0d; \n\n static void textColor(WORD color);\n static void quitscr(WORD color, const char* msg);\n static void quitscrS(WORD color, std::string msg);\n void xmlSafeWrite(std::FILE * file, const char* msg);\n\n void readSecret(\n std::string secret,\n TResult mismatchResult = _pv,\n std::string mismatchMessage = \"Secret mismatch\",\n std::string eofMessage = \"Unexpected end of file - secret expected\");\n void readGraderResult();\n\nprivate:\n InStream(const InStream&);\n InStream& operator =(const InStream&);\n void quitByGraderResult(TResult result, std::string defaultMessage);\n};\n\nInStream inf;\nInStream ouf;\nInStream ans;\nbool appesMode;\nstd::string resultName;\nstd::string checkerName = \"untitled checker\";\nrandom_t rnd;\nTTestlibMode testlibMode = _unknown;\ndouble __testlib_points = std::numeric_limits::infinity();\n\nstruct ValidatorBoundsHit\n{\n static const double EPS;\n bool minHit;\n bool maxHit;\n\n ValidatorBoundsHit(bool minHit = false, bool maxHit = false): minHit(minHit), maxHit(maxHit)\n {\n };\n\n ValidatorBoundsHit merge(const ValidatorBoundsHit& validatorBoundsHit)\n {\n return ValidatorBoundsHit(\n __testlib_max(minHit, validatorBoundsHit.minHit),\n __testlib_max(maxHit, validatorBoundsHit.maxHit)\n );\n }\n};\n\nconst double ValidatorBoundsHit::EPS = 1E-12;\n\nclass Validator\n{\nprivate:\n std::string _testset;\n std::string _group;\n std::string _testOverviewLogFileName;\n std::map _boundsHitByVariableName;\n std::set _features;\n std::set _hitFeatures;\n\n bool isVariableNameBoundsAnalyzable(const std::string& variableName)\n {\n for (size_t i = 0; i < variableName.length(); i++)\n if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')\n return false;\n return true;\n }\n\n bool isFeatureNameAnalyzable(const std::string& featureName)\n {\n for (size_t i = 0; i < featureName.length(); i++)\n if (featureName[i] < ' ')\n return false;\n return true;\n }\npublic:\n Validator(): _testset(\"tests\"), _group()\n {\n }\n\n std::string testset() const\n {\n return _testset;\n }\n \n std::string group() const\n {\n return _group;\n }\n\n std::string testOverviewLogFileName() const\n {\n return _testOverviewLogFileName;\n }\n \n void setTestset(const char* const testset)\n {\n _testset = testset;\n }\n\n void setGroup(const char* const group)\n {\n _group = group;\n }\n\n void setTestOverviewLogFileName(const char* const testOverviewLogFileName)\n {\n _testOverviewLogFileName = testOverviewLogFileName;\n }\n\n void addBoundsHit(const std::string& variableName, ValidatorBoundsHit boundsHit)\n {\n if (isVariableNameBoundsAnalyzable(variableName))\n {\n _boundsHitByVariableName[variableName]\n = boundsHit.merge(_boundsHitByVariableName[variableName]);\n }\n }\n\n std::string getBoundsHitLog()\n {\n std::string result;\n for (std::map::iterator i = _boundsHitByVariableName.begin();\n i != _boundsHitByVariableName.end();\n i++)\n {\n result += \"\\\"\" + i->first + \"\\\":\";\n if (i->second.minHit)\n result += \" min-value-hit\";\n if (i->second.maxHit)\n result += \" max-value-hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n std::string getFeaturesLog()\n {\n std::string result;\n for (std::set::iterator i = _features.begin();\n i != _features.end();\n i++)\n {\n result += \"feature \\\"\" + *i + \"\\\":\";\n if (_hitFeatures.count(*i))\n result += \" hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n void writeTestOverviewLog()\n {\n if (!_testOverviewLogFileName.empty())\n {\n std::string fileName(_testOverviewLogFileName);\n _testOverviewLogFileName = \"\";\n FILE* testOverviewLogFile = fopen(fileName.c_str(), \"w\");\n if (NULL == testOverviewLogFile)\n __testlib_fail(\"Validator::writeTestOverviewLog: can't test overview log to (\" + fileName + \")\");\n fprintf(testOverviewLogFile, \"%s%s\", getBoundsHitLog().c_str(), getFeaturesLog().c_str());\n if (fclose(testOverviewLogFile))\n __testlib_fail(\"Validator::writeTestOverviewLog: can't close test overview log file (\" + fileName + \")\");\n }\n }\n\n void addFeature(const std::string& feature)\n {\n if (_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" registered twice.\");\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n _features.insert(feature);\n }\n\n void feature(const std::string& feature)\n {\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n if (!_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" didn't registered via addFeature(feature).\");\n\n _hitFeatures.insert(feature);\n }\n} validator;\n\nstruct TestlibFinalizeGuard\n{\n static bool alive;\n int quitCount, readEofCount;\n\n TestlibFinalizeGuard() : quitCount(0), readEofCount(0)\n {\n // No operations.\n }\n\n ~TestlibFinalizeGuard()\n {\n bool _alive = alive;\n alive = false;\n\n if (_alive)\n {\n if (testlibMode == _checker && quitCount == 0)\n __testlib_fail(\"Checker must end with quit or quitf call.\");\n\n if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)\n __testlib_fail(\"Validator must end with readEof call.\");\n }\n\n validator.writeTestOverviewLog();\n }\n};\n\nbool TestlibFinalizeGuard::alive = true;\nTestlibFinalizeGuard testlibFinalizeGuard;\n\n/*\n * Call it to disable checks on finalization.\n */\nvoid disableFinalizeGuard()\n{\n TestlibFinalizeGuard::alive = false;\n}\n\n/* Interactor streams.\n */\nstd::fstream tout;\n\n/* implementation\n */\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate\nstatic std::string vtos(const T& t, std::true_type)\n{ \n if (t == 0)\n return \"0\";\n else\n {\n T n(t);\n bool negative = n < 0;\n std::string s;\n while (n != 0) {\n T digit = n % 10;\n if (digit < 0)\n digit = -digit;\n s += char('0' + digit);\n n /= 10;\n }\n std::reverse(s.begin(), s.end());\n return negative ? \"-\" + s : s;\n }\n}\n\ntemplate\nstatic std::string vtos(const T& t, std::false_type)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n\ntemplate \nstatic std::string vtos(const T& t)\n{\n return vtos(t, std::is_integral());\n}\n#else\ntemplate\nstatic std::string vtos(const T& t)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n#endif\n\ntemplate \nstatic std::string toString(const T& t)\n{\n return vtos(t);\n}\n\nInStream::InStream()\n{\n reader = NULL;\n lastLine = -1;\n name = \"\";\n mode = _input;\n strict = false;\n stdfile = false;\n wordReserveSize = 4;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::InStream(const InStream& baseStream, std::string content)\n{\n reader = new StringInputStreamReader(content);\n lastLine = -1;\n opened = true;\n strict = baseStream.strict;\n mode = baseStream.mode;\n name = \"based on \" + baseStream.name;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::~InStream()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\nint resultExitCode(TResult r)\n{\n if (testlibMode == _checker)\n return 0;//CMS Checkers should always finish with zero exit code.\n if (r == _ok)\n return OK_EXIT_CODE;\n if (r == _wa)\n return WA_EXIT_CODE;\n if (r == _pe)\n return PE_EXIT_CODE;\n if (r == _fail)\n return FAIL_EXIT_CODE;\n if (r == _dirt)\n return DIRT_EXIT_CODE;\n if (r == _points)\n return POINTS_EXIT_CODE;\n if (r == _unexpected_eof)\n#ifdef ENABLE_UNEXPECTED_EOF\n return UNEXPECTED_EOF_EXIT_CODE;\n#else\n return PE_EXIT_CODE;\n#endif\n if (r == _sv)\n return SV_EXIT_CODE;\n if (r == _pv)\n return PV_EXIT_CODE;\n if (r >= _partially)\n return PC_BASE_EXIT_CODE + (r - _partially);\n return FAIL_EXIT_CODE;\n}\n\nvoid InStream::textColor(\n#if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)) && defined(__GNUC__)\n __attribute__((unused)) \n#endif\n WORD color\n)\n{\n#if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)\n HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(handle, color);\n#endif\n#if !defined(ON_WINDOWS) && defined(__GNUC__)\n if (isatty(2))\n {\n switch (color)\n {\n case LightRed:\n fprintf(stderr, \"\\033[1;31m\");\n break;\n case LightCyan:\n fprintf(stderr, \"\\033[1;36m\");\n break;\n case LightGreen:\n fprintf(stderr, \"\\033[1;32m\");\n break;\n case LightYellow:\n fprintf(stderr, \"\\033[1;33m\");\n break;\n case LightMagenta:\n fprintf(stderr, \"\\033[1;35m\");\n break;\n case LightGray:\n default:\n fprintf(stderr, \"\\033[0m\");\n }\n }\n#endif\n}\n\nNORETURN void halt(int exitCode)\n{\n callHaltListeners();\n#ifdef FOOTER\n InStream::textColor(InStream::LightGray);\n std::fprintf(stderr, \"Checker: \\\"%s\\\"\\n\", checkerName.c_str());\n std::fprintf(stderr, \"Exit code: %d\\n\", exitCode);\n InStream::textColor(InStream::LightGray);\n#endif\n std::exit(exitCode);\n}\n\nstatic bool __testlib_shouldCheckDirt(TResult result)\n{\n return result == _ok || result == _points || result >= _partially;\n}\n\n\nstd::string RESULT_MESSAGE_CORRECT = \"Output is correct\";\nstd::string RESULT_MESSAGE_PARTIALLY_CORRECT = \"Output is partially correct\";\nstd::string RESULT_MESSAGE_WRONG = \"Output isn't correct\";\nstd::string RESULT_MESSAGE_SECURITY_VIOLATION = \"Security Violation\";\nstd::string RESULT_MESSAGE_PROTOCOL_VIOLATION = \"Protocol Violation\";\nstd::string RESULT_MESSAGE_FAIL = \"Judge Failure; Contact staff!\";\n\nNORETURN void InStream::quit(TResult result, const char* msg)\n{\n if (TestlibFinalizeGuard::alive)\n testlibFinalizeGuard.quitCount++;\n\n // You can change maxMessageLength.\n // Example: 'inf.maxMessageLength = 1024 * 1024;'.\n if (strlen(msg) > maxMessageLength)\n {\n std::string message(msg);\n std::string warn = \"message length exceeds \" + vtos(maxMessageLength)\n + \", the message is truncated: \";\n msg = (warn + message.substr(0, maxMessageLength - warn.length())).c_str();\n }\n\n#ifndef ENABLE_UNEXPECTED_EOF\n if (result == _unexpected_eof)\n result = _pe;\n#endif\n\n if (mode != _output && result != _fail)\n {\n if (mode == _input && testlibMode == _validator && lastLine != -1)\n quits(_fail, std::string(msg) + \" (\" + name + \", line \" + vtos(lastLine) + \")\");\n else\n quits(_fail, std::string(msg) + \" (\" + name + \")\");\n }\n\n std::FILE * resultFile;\n std::string errorName;\n \n if (__testlib_shouldCheckDirt(result))\n {\n if (testlibMode != _interactor && !ouf.seekEof())\n quit(_dirt, \"Extra information in the output file\");\n }\n\n int pctype = result - _partially;\n bool isPartial = false;\n\n if (testlibMode == _checker) {\n WORD color;\n std::string pointsStr = \"0\";\n switch (result)\n {\n case _ok:\n pointsStr = format(\"%d\", 1);\n color = LightGreen;\n errorName = RESULT_MESSAGE_CORRECT;\n break;\n case _wa:\n case _pe:\n case _dirt:\n case _unexpected_eof:\n color = LightRed;\n errorName = RESULT_MESSAGE_WRONG;\n break;\n case _fail:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_FAIL;\n break;\n case _sv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_SECURITY_VIOLATION;\n break;\n case _pv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_PROTOCOL_VIOLATION;\n break;\n case _points:\n if (__testlib_points < 1e-5)\n pointsStr = \"0.00001\"; // Prevent zero scores in CMS as zero is considered wrong\n else if (__testlib_points < 0.0001)\n pointsStr = format(\"%lf\", __testlib_points); // Prevent rounding the numbers below 0.0001\n else\n pointsStr = format(\"%.4lf\", __testlib_points);\n color = LightYellow;\n errorName = RESULT_MESSAGE_PARTIALLY_CORRECT;\n break;\n default:\n if (result >= _partially)\n quit(_fail, \"testlib partially mode not supported\");\n else\n quit(_fail, \"What is the code ??? \");\n } \n std::fprintf(stdout, \"%s\\n\", pointsStr.c_str());\n quitscrS(color, errorName);\n std::fprintf(stderr, \"\\n\");\n } else {\n switch (result)\n {\n case _ok:\n errorName = \"ok \";\n quitscrS(LightGreen, errorName);\n break;\n case _wa:\n errorName = \"wrong answer \";\n quitscrS(LightRed, errorName);\n break;\n case _pe:\n errorName = \"wrong output format \";\n quitscrS(LightRed, errorName);\n break;\n case _fail:\n errorName = \"FAIL \";\n quitscrS(LightRed, errorName);\n break;\n case _dirt:\n errorName = \"wrong output format \";\n quitscrS(LightCyan, errorName);\n result = _pe;\n break;\n case _points:\n errorName = \"points \";\n quitscrS(LightYellow, errorName);\n break;\n case _unexpected_eof:\n errorName = \"unexpected eof \";\n quitscrS(LightCyan, errorName);\n break;\n default:\n if (result >= _partially)\n {\n errorName = format(\"partially correct (%d) \", pctype);\n isPartial = true;\n quitscrS(LightYellow, errorName);\n }\n else\n quit(_fail, \"What is the code ??? \");\n }\n }\n\n if (resultName != \"\")\n {\n resultFile = std::fopen(resultName.c_str(), \"w\");\n if (resultFile == NULL)\n quit(_fail, \"Can not write to the result file\");\n if (appesMode)\n {\n std::fprintf(resultFile, \"\");\n if (isPartial)\n std::fprintf(resultFile, \"\", outcomes[(int)_partially].c_str(), pctype);\n else\n {\n if (result != _points)\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str());\n else\n {\n if (__testlib_points == std::numeric_limits::infinity())\n quit(_fail, \"Expected points, but infinity found\");\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", __testlib_points));\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str(), stringPoints.c_str());\n }\n }\n xmlSafeWrite(resultFile, msg);\n std::fprintf(resultFile, \"\\n\");\n }\n else\n std::fprintf(resultFile, \"%s\", msg);\n if (NULL == resultFile || fclose(resultFile) != 0)\n quit(_fail, \"Can not write to the result file\");\n }\n\n quitscr(LightGray, msg);\n std::fprintf(stderr, \"\\n\");\n\n inf.close();\n ouf.close();\n ans.close();\n if (tout.is_open())\n tout.close();\n\n textColor(LightGray);\n\n if (resultName != \"\")\n std::fprintf(stderr, \"See file to check exit message\\n\");\n\n halt(resultExitCode(result));\n}\n\n#ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n#endif\nNORETURN void InStream::quitf(TResult result, const char* msg, ...)\n{\n FMT_TO_RESULT(msg, msg, message);\n InStream::quit(result, message.c_str());\n}\n\nNORETURN void InStream::quits(TResult result, std::string msg)\n{\n InStream::quit(result, msg.c_str());\n}\n\nvoid InStream::xmlSafeWrite(std::FILE * file, const char* msg)\n{\n size_t lmsg = strlen(msg);\n for (size_t i = 0; i < lmsg; i++)\n {\n if (msg[i] == '&')\n {\n std::fprintf(file, \"%s\", \"&\");\n continue;\n }\n if (msg[i] == '<')\n {\n std::fprintf(file, \"%s\", \"<\");\n continue;\n }\n if (msg[i] == '>')\n {\n std::fprintf(file, \"%s\", \">\");\n continue;\n }\n if (msg[i] == '\"')\n {\n std::fprintf(file, \"%s\", \""\");\n continue;\n }\n if (0 <= msg[i] && msg[i] <= 31)\n {\n std::fprintf(file, \"%c\", '.');\n continue;\n }\n std::fprintf(file, \"%c\", msg[i]);\n }\n}\n\nvoid InStream::quitscrS(WORD color, std::string msg)\n{\n quitscr(color, msg.c_str());\n}\n\nvoid InStream::quitscr(WORD color, const char* msg)\n{\n if (resultName == \"\")\n {\n textColor(color);\n std::fprintf(stderr, \"%s\", msg);\n textColor(LightGray);\n }\n}\n\nvoid InStream::reset(std::FILE* file)\n{\n if (opened && stdfile)\n quit(_fail, \"Can't reset standard handle\");\n\n if (opened)\n close();\n\n if (!stdfile)\n if (NULL == (file = std::fopen(name.c_str(), \"rb\")))\n {\n if (mode == _output)\n quits(_pe, std::string(\"Output file not found: \\\"\") + name + \"\\\"\");\n \n if (mode == _answer)\n quits(_fail, std::string(\"Answer file not found: \\\"\") + name + \"\\\"\");\n }\n\n if (NULL != file)\n {\n opened = true;\n\n __testlib_set_binary(file);\n\n if (stdfile)\n reader = new FileInputStreamReader(file, name);\n else\n reader = new BufferedFileInputStreamReader(file, name);\n }\n else\n {\n opened = false;\n reader = NULL;\n }\n}\n\nvoid InStream::init(std::string fileName, TMode mode)\n{\n opened = false;\n name = fileName;\n stdfile = false;\n this->mode = mode;\n \n std::ifstream stream;\n stream.open(fileName.c_str(), std::ios::in);\n if (stream.is_open())\n {\n std::streampos start = stream.tellg();\n stream.seekg(0, std::ios::end);\n std::streampos end = stream.tellg();\n size_t fileSize = size_t(end - start);\n stream.close();\n \n // You can change maxFileSize.\n // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'.\n if (fileSize > maxFileSize)\n quitf(_pe, \"File size exceeds %d bytes, size is %d\", int(maxFileSize), int(fileSize));\n }\n\n reset();\n}\n\nvoid InStream::init(std::FILE* f, TMode mode)\n{\n opened = false;\n name = \"untitled\";\n this->mode = mode;\n \n if (f == stdin)\n name = \"stdin\", stdfile = true;\n if (f == stdout)\n name = \"stdout\", stdfile = true;\n if (f == stderr)\n name = \"stderr\", stdfile = true;\n\n reset(f);\n}\n\nchar InStream::curChar()\n{\n return char(reader->curChar());\n}\n\nchar InStream::nextChar()\n{\n return char(reader->nextChar());\n}\n\nchar InStream::readChar()\n{\n return nextChar();\n}\n\nchar InStream::readChar(char c)\n{\n lastLine = reader->getLine();\n char found = readChar();\n if (c != found)\n {\n if (!isEoln(found))\n quit(_pe, (\"Unexpected character '\" + std::string(1, found) + \"', but '\" + std::string(1, c) + \"' expected\").c_str());\n else\n quit(_pe, (\"Unexpected character \" + (\"#\" + vtos(int(found))) + \", but '\" + std::string(1, c) + \"' expected\").c_str());\n }\n return found;\n}\n\nchar InStream::readSpace()\n{\n return readChar(' ');\n}\n\nvoid InStream::unreadChar(char c)\n{\n reader->unreadChar(c);\n}\n\nvoid InStream::skipChar()\n{\n reader->skipChar();\n}\n\nvoid InStream::skipBlanks()\n{\n while (isBlanks(reader->curChar()))\n reader->skipChar();\n}\n\nstd::string InStream::readWord()\n{\n readWordTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nvoid InStream::readWordTo(std::string& result)\n{\n if (!strict)\n skipBlanks();\n\n lastLine = reader->getLine();\n int cur = reader->nextChar();\n\n if (cur == EOFC)\n quit(_unexpected_eof, \"Unexpected end of file - token expected\");\n\n if (isBlanks(cur))\n quit(_pe, \"Unexpected white-space - token expected\");\n\n result.clear();\n\n while (!(isBlanks(cur) || cur == EOFC))\n {\n result += char(cur);\n \n // You can change maxTokenLength.\n // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'.\n if (result.length() > maxTokenLength)\n quitf(_pe, \"Length of token exceeds %d, token is '%s...'\", int(maxTokenLength), __testlib_part(result).c_str());\n\n cur = reader->nextChar();\n }\n\n reader->unreadChar(cur);\n\n if (result.length() == 0)\n quit(_unexpected_eof, \"Unexpected end of file or white-space - token expected\");\n}\n\nstd::string InStream::readToken()\n{\n return readWord();\n}\n\nvoid InStream::readTokenTo(std::string& result)\n{\n readWordTo(result);\n}\n\nstatic std::string __testlib_part(const std::string& s)\n{\n if (s.length() <= 64)\n return s;\n else\n return s.substr(0, 30) + \"...\" + s.substr(s.length() - 31, 31);\n}\n\n#define __testlib_readMany(readMany, readOne, typeName, space) \\\n if (size < 0) \\\n quit(_fail, #readMany \": size should be non-negative.\"); \\\n if (size > 100000000) \\\n quit(_fail, #readMany \": size should be at most 100000000.\"); \\\n \\\n std::vector result(size); \\\n readManyIteration = indexBase; \\\n \\\n for (int i = 0; i < size; i++) \\\n { \\\n result[i] = readOne; \\\n readManyIteration++; \\\n if (strict && space && i + 1 < size) \\\n readSpace(); \\\n } \\\n \\\n readManyIteration = NO_INDEX; \\\n return result; \\\n\nstd::string InStream::readWord(const pattern& p, const std::string& variableName)\n{\n readWordTo(_tmpReadToken);\n if (!p.matches(_tmpReadToken))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Token element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token element \" + variableName + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n return _tmpReadToken;\n}\n\nstd::vector InStream::readWords(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readWord(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(pattern(ptrn), variableName);\n}\n\nstd::vector InStream::readWords(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const pattern& p, const std::string& variableName)\n{\n return readWord(p, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(ptrn, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true);\n}\n\nvoid InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readWordTo(result);\n if (!p.matches(result))\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n}\n\nvoid InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, pattern(ptrn), variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n return readWordTo(result, p, variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, ptrn, variableName);\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(long long integer, const char* s)\n{\n if (integer == LLONG_MIN)\n return strcmp(s, \"-9223372036854775808\") == 0;\n\n if (integer == 0LL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n if (integer < 0 && s[0] != '-')\n return false;\n\n if (integer < 0)\n s++, length--, integer = -integer;\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(unsigned long long integer, const char* s)\n{\n if (integer == ULLONG_MAX)\n return strcmp(s, \"18446744073709551615\") == 0;\n\n if (integer == 0ULL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\nstatic inline double stringToDouble(InStream& in, const char* buffer)\n{\n double retval;\n\n size_t length = strlen(buffer);\n\n int minusCount = 0;\n int plusCount = 0;\n int decimalPointCount = 0;\n int digitCount = 0;\n int eCount = 0;\n\n for (size_t i = 0; i < length; i++)\n {\n if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.'\n || buffer[i] == 'e' || buffer[i] == 'E'\n || buffer[i] == '-' || buffer[i] == '+')\n {\n if ('0' <= buffer[i] && buffer[i] <= '9')\n digitCount++;\n if (buffer[i] == 'e' || buffer[i] == 'E')\n eCount++;\n if (buffer[i] == '-')\n minusCount++;\n if (buffer[i] == '+')\n plusCount++;\n if (buffer[i] == '.')\n decimalPointCount++;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n // If for sure is not a number in standard notation or in e-notation.\n if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)\n{\n if (minAfterPointDigitCount < 0)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be non-negative.\");\n \n if (minAfterPointDigitCount > maxAfterPointDigitCount)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.\");\n\n double retval;\n\n size_t length = strlen(buffer);\n\n if (length == 0 || length > 1000)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int pointPos = -1; \n for (size_t i = 1; i + 1 < length; i++)\n {\n if (buffer[i] == '.')\n {\n if (pointPos > -1)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n pointPos = int(i);\n }\n if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n if (buffer[length - 1] < '0' || buffer[length - 1] > '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);\n if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)\n in.quit(_pe, (\"Expected strict double with number of digits after point in range [\"\n + vtos(minAfterPointDigitCount)\n + \",\"\n + vtos(maxAfterPointDigitCount)\n + \"], but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str()\n );\n\n int firstDigitPos = -1;\n for (size_t i = 0; i < length; i++)\n if (buffer[i] >= '0' && buffer[i] <= '9')\n {\n firstDigitPos = int(i);\n break;\n }\n\n if (firstDigitPos > 1 || firstDigitPos == -1) \n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)\n && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline long long stringToLongLong(InStream& in, const char* buffer)\n{\n if (strcmp(buffer, \"-9223372036854775808\") == 0)\n return LLONG_MIN;\n\n bool minus = false;\n size_t length = strlen(buffer);\n \n if (length > 1 && buffer[0] == '-')\n minus = true;\n\n if (length > 20)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n long long retval = 0LL;\n\n int zeroes = 0;\n int processingZeroes = true;\n \n for (int i = (minus ? 1 : 0); i < int(length); i++)\n {\n if (buffer[i] == '0' && processingZeroes)\n zeroes++;\n else\n processingZeroes = false;\n\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (retval < 0)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n \n if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n retval = (minus ? -retval : +retval);\n\n if (length < 19)\n return retval;\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline unsigned long long stringToUnsignedLongLong(InStream& in, const char* buffer)\n{\n size_t length = strlen(buffer);\n\n if (length > 20)\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n if (length > 1 && buffer[0] == '0')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n unsigned long long retval = 0LL;\n for (int i = 0; i < int(length); i++)\n {\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (length < 19)\n return retval;\n\n if (length == 20 && strcmp(buffer, \"18446744073709551615\") == 1)\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nint InStream::readInteger()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int32 expected\");\n\n readWordTo(_tmpReadToken);\n \n long long value = stringToLongLong(*this, _tmpReadToken.c_str());\n if (value < INT_MIN || value > INT_MAX)\n quit(_pe, (\"Expected int32, but \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" found\").c_str());\n \n return int(value);\n}\n\nlong long InStream::readLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToLongLong(*this, _tmpReadToken.c_str());\n}\n\nunsigned long long InStream::readUnsignedLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToUnsignedLongLong(*this, _tmpReadToken.c_str());\n}\n\nlong long InStream::readLong(long long minv, long long maxv, const std::string& variableName)\n{\n long long result = readLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readLongs(int size, long long minv, long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true)\n}\n\nunsigned long long InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n unsigned long long result = readUnsignedLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true)\n}\n\nunsigned long long InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n return readUnsignedLong(minv, maxv, variableName);\n}\n\nint InStream::readInt()\n{\n return readInteger();\n}\n\nint InStream::readInt(int minv, int maxv, const std::string& variableName)\n{\n int result = readInt();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nint InStream::readInteger(int minv, int maxv, const std::string& variableName)\n{\n return readInt(minv, maxv, variableName);\n}\n\nstd::vector InStream::readInts(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true)\n}\n\nstd::vector InStream::readIntegers(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true)\n}\n\ndouble InStream::readReal()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - double expected\");\n\n return stringToDouble(*this, readWord().c_str());\n}\n\ndouble InStream::readDouble()\n{\n return readReal();\n}\n\ndouble InStream::readReal(double minv, double maxv, const std::string& variableName)\n{\n double result = readReal();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readReals(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readDouble(double minv, double maxv, const std::string& variableName)\n{\n return readReal(minv, maxv, variableName);\n} \n\nstd::vector InStream::readDoubles(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - strict double expected\");\n\n double result = stringToStrictDouble(*this, readWord().c_str(),\n minAfterPointDigitCount, maxAfterPointDigitCount);\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictReals, readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\ndouble InStream::readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n return readStrictReal(minv, maxv,\n minAfterPointDigitCount, maxAfterPointDigitCount,\n variableName);\n}\n\nstd::vector InStream::readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictDoubles, readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\nbool InStream::eof()\n{\n if (!strict && NULL == reader)\n return true;\n\n return reader->eof();\n}\n\nbool InStream::seekEof()\n{\n if (!strict && NULL == reader)\n return true;\n skipBlanks();\n return eof();\n}\n\nbool InStream::eoln()\n{\n if (!strict && NULL == reader)\n return true;\n\n int c = reader->nextChar();\n\n if (!strict)\n {\n if (c == EOFC)\n return true;\n\n if (c == CR)\n {\n c = reader->nextChar();\n\n if (c != LF)\n {\n reader->unreadChar(c);\n reader->unreadChar(CR);\n return false;\n }\n else\n return true;\n }\n \n if (c == LF)\n return true;\n\n reader->unreadChar(c);\n return false;\n }\n else\n {\n bool returnCr = false;\n\n#if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS)\n if (c != CR)\n {\n reader->unreadChar(c);\n return false;\n }\n else\n {\n if (!returnCr)\n returnCr = true;\n c = reader->nextChar();\n }\n#endif \n if (c != LF)\n {\n reader->unreadChar(c);\n if (returnCr)\n reader->unreadChar(CR);\n return false;\n }\n\n return true;\n }\n}\n\nvoid InStream::readEoln()\n{\n lastLine = reader->getLine();\n if (!eoln())\n quit(_pe, \"Expected EOLN\");\n}\n\nvoid InStream::readEof()\n{\n lastLine = reader->getLine();\n if (!eof())\n quit(_pe, \"Expected EOF\");\n\n if (TestlibFinalizeGuard::alive && this == &inf)\n testlibFinalizeGuard.readEofCount++;\n}\n\nbool InStream::seekEoln()\n{\n if (!strict && NULL == reader)\n return true;\n \n int cur;\n do\n {\n cur = reader->nextChar();\n } \n while (cur == SPACE || cur == TAB);\n\n reader->unreadChar(cur);\n return eoln();\n}\n\nvoid InStream::nextLine()\n{\n readLine();\n}\n\nvoid InStream::readStringTo(std::string& result)\n{\n if (NULL == reader)\n quit(_pe, \"Expected line\");\n\n result.clear();\n\n for (;;)\n {\n int cur = reader->curChar();\n\n if (cur == LF || cur == EOFC)\n break;\n\n if (cur == CR)\n {\n cur = reader->nextChar();\n if (reader->curChar() == LF)\n {\n reader->unreadChar(cur);\n break;\n }\n }\n\n lastLine = reader->getLine();\n result += char(reader->nextChar());\n }\n\n if (strict)\n readEoln();\n else\n eoln();\n}\n\nstd::string InStream::readString()\n{\n readStringTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, int indexBase)\n{\n __testlib_readMany(readStrings, readString(), std::string, false)\n}\n\nvoid InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result);\n if (!p.matches(result))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Line \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Line element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n}\n\nvoid InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, pattern(ptrn), variableName);\n}\n\nstd::string InStream::readString(const pattern& p, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, p, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readString(const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, ptrn, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result)\n{\n readStringTo(result);\n}\n\nstd::string InStream::readLine()\n{\n return readString();\n}\n\nstd::vector InStream::readLines(int size, int indexBase)\n{\n __testlib_readMany(readLines, readString(), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result, p, variableName);\n}\n\nvoid InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, ptrn, variableName);\n}\n\nstd::string InStream::readLine(const pattern& p, const std::string& variableName)\n{\n return readString(p, variableName);\n}\n\nstd::vector InStream::readLines(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readLine(const std::string& ptrn, const std::string& variableName)\n{\n return readString(ptrn, variableName);\n}\n\nstd::vector InStream::readLines(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid InStream::ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n this->__testlib_ensure(cond, message);\n }\n}\n\nvoid InStream::__testlib_ensure(bool cond, std::string message)\n{\n if (!cond)\n this->quit(_wa, message.c_str()); \n}\n\nvoid InStream::close()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n \n opened = false;\n}\n\nNORETURN void quit(TResult result, const std::string& msg)\n{\n ouf.quit(result, msg.c_str());\n}\n\nNORETURN void quit(TResult result, const char* msg)\n{\n ouf.quit(result, msg);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...);\n\nNORETURN void __testlib_quitp(double points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %lf, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", points));\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void __testlib_quitp(int points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %d, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = format(\"%d\", points);\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void quitp(float points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(double points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\nNORETURN void quitp(long double points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(int points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\ntemplate\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitp(F points, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quitp(points, message);\n}\n\ntemplate\nNORETURN void quitp(F points)\n{\n __testlib_quitp(points, std::string(\"\"));\n}\n\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid quitif(bool condition, TResult result, const char* format, ...)\n{\n if (condition)\n {\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n }\n}\n\nNORETURN void __testlib_help()\n{\n InStream::textColor(InStream::LightCyan);\n std::fprintf(stderr, \"TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ \", VERSION);\n std::fprintf(stderr, \"by Mike Mirzayanov, copyright(c) 2005-2018\\n\");\n std::fprintf(stderr, \"Checker name: \\\"%s\\\"\\n\", checkerName.c_str());\n InStream::textColor(InStream::LightGray);\n\n std::fprintf(stderr, \"\\n\");\n std::fprintf(stderr, \"Latest features: \\n\");\n for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)\n {\n std::fprintf(stderr, \"*) %s\\n\", latestFeatures[i]);\n }\n std::fprintf(stderr, \"\\n\");\n\n std::fprintf(stderr, \"Program must be run with the following arguments: \\n\");\n std::fprintf(stderr, \" [ [<-appes>]]\\n\\n\");\n\n std::exit(FAIL_EXIT_CODE);\n}\n\nstatic void __testlib_ensuresPreconditions()\n{\n // testlib assumes: sizeof(int) = 4.\n __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);\n\n // testlib assumes: INT_MAX == 2147483647.\n __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);\n\n // testlib assumes: sizeof(long long) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);\n\n // testlib assumes: sizeof(double) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);\n\n // testlib assumes: no -ffast-math.\n if (!__testlib_isNaN(+__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n if (!__testlib_isNaN(-__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n}\n\nvoid registerGen(int argc, char* argv[], int randomGeneratorVersion)\n{\n if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)\n quitf(_fail, \"Random generator version is expected to be 0 or 1.\");\n random_t::version = randomGeneratorVersion;\n\n __testlib_ensuresPreconditions();\n\n testlibMode = _generator;\n __testlib_set_binary(stdin);\n rnd.setSeed(argc, argv);\n}\n\n#ifdef USE_RND_AS_BEFORE_087\nvoid registerGen(int argc, char* argv[])\n{\n registerGen(argc, argv, 0);\n}\n#else\n#ifdef __GNUC__\n#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4))\n __attribute__ ((deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\")))\n#else\n __attribute__ ((deprecated))\n#endif\n#endif\n#ifdef _MSC_VER\n __declspec(deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\"))\n#endif\nvoid registerGen(int argc, char* argv[])\n{\n std::fprintf(stderr, \"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\\n\\n\");\n registerGen(argc, argv, 0);\n}\n#endif\n\nvoid registerInteraction(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _interactor;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n \n if (argc < 3 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [ [<-appes>]]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc <= 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n#ifndef EJUDGE\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n#endif\n\n inf.init(argv[1], _input);\n\n tout.open(argv[2], std::ios_base::out);\n if (tout.fail() || !tout.is_open())\n quit(_fail, std::string(\"Can not write to the test-output-file '\") + argv[2] + std::string(\"'\"));\n\n ouf.init(stdin, _output);\n \n if (argc >= 4)\n ans.init(argv[3], _answer);\n else\n ans.name = \"unopened answer stream\";\n}\n\nvoid registerValidation()\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _validator;\n __testlib_set_binary(stdin);\n\n inf.init(stdin, _input);\n inf.strict = true;\n}\n\nvoid registerValidation(int argc, char* argv[])\n{\n registerValidation();\n\n for (int i = 1; i < argc; i++)\n {\n if (!strcmp(\"--testset\", argv[i]))\n {\n if (i + 1 < argc && strlen(argv[i + 1]) > 0)\n validator.setTestset(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--group\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setGroup(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--testOverviewLogFileName\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setTestOverviewLogFileName(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n } \n}\n\nvoid addFeature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.addFeature(feature); \n}\n\nvoid feature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.feature(feature); \n}\n\nvoid registerTestlibCmd(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _checker;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n\n if (argc < 4 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [<-appes>]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc == 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n\n inf.init(argv[1], _input);\n ans.init(argv[2], _answer);\n ouf.init(argv[3], _output);\n}\n\nvoid registerTestlib(int argc, ...)\n{\n if (argc < 3 || argc > 5)\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n\n char** argv = new char*[argc + 1];\n \n va_list ap;\n va_start(ap, argc);\n argv[0] = NULL;\n for (int i = 0; i < argc; i++)\n {\n argv[i + 1] = va_arg(ap, char*);\n }\n va_end(ap);\n\n registerTestlibCmd(argc + 1, argv);\n delete[] argv;\n}\n\nstatic inline void __testlib_ensure(bool cond, const std::string& msg)\n{\n if (!cond)\n quit(_fail, msg.c_str());\n}\n\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\nstatic inline void __testlib_ensure(bool cond, const char* msg)\n{\n if (!cond)\n quit(_fail, msg);\n}\n\n#define ensure(cond) __testlib_ensure(cond, \"Condition failed: \\\"\" #cond \"\\\"\")\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\ninline void ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n __testlib_ensure(cond, message);\n }\n}\n\nNORETURN static void __testlib_fail(const std::string& message)\n{\n quitf(_fail, \"%s\", message.c_str());\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid setName(const char* format, ...)\n{\n FMT_TO_RESULT(format, format, name);\n checkerName = name;\n}\n\n/* \n * Do not use random_shuffle, because it will produce different result\n * for different C++ compilers.\n *\n * This implementation uses testlib random_t to produce random numbers, so\n * it is stable.\n */ \ntemplate\nvoid shuffle(_RandomAccessIter __first, _RandomAccessIter __last)\n{\n if (__first == __last) return;\n for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)\n std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));\n}\n\n\ntemplate\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use random_shuffle(), use shuffle() instead\")))\n#endif\nvoid random_shuffle(_RandomAccessIter , _RandomAccessIter )\n{\n quitf(_fail, \"Don't use random_shuffle(), use shuffle() instead\");\n}\n\n#ifdef __GLIBC__\n# define RAND_THROW_STATEMENT throw()\n#else\n# define RAND_THROW_STATEMENT\n#endif\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use rand(), use rnd.next() instead\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nint rand() RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use rand(), use rnd.next() instead\");\n \n /* This line never runs. */\n //throw \"Don't use rand(), use rnd.next() instead\";\n}\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1).\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nvoid srand(unsigned int seed) RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1) [ignored seed=%d].\", seed);\n}\n\nvoid startTest(int test)\n{\n const std::string testFileName = vtos(test);\n if (NULL == freopen(testFileName.c_str(), \"wt\", stdout))\n __testlib_fail(\"Unable to write file '\" + testFileName + \"'\");\n}\n\ninline std::string upperCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('a' <= s[i] && s[i] <= 'z')\n s[i] = char(s[i] - 'a' + 'A');\n return s;\n}\n\ninline std::string lowerCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('A' <= s[i] && s[i] <= 'Z')\n s[i] = char(s[i] - 'A' + 'a');\n return s;\n}\n\ninline std::string compress(const std::string& s)\n{\n return __testlib_part(s);\n}\n\ninline std::string englishEnding(int x)\n{\n x %= 100;\n if (x / 10 == 1)\n return \"th\";\n if (x % 10 == 1)\n return \"st\";\n if (x % 10 == 2)\n return \"nd\";\n if (x % 10 == 3)\n return \"rd\";\n return \"th\";\n}\n\ninline std::string trim(const std::string& s)\n{\n if (s.empty())\n return s;\n\n int left = 0;\n while (left < int(s.length()) && isBlanks(s[left]))\n left++;\n if (left >= int(s.length()))\n return \"\";\n\n int right = int(s.length()) - 1;\n while (right >= 0 && isBlanks(s[right]))\n right--;\n if (right < 0)\n return \"\";\n\n return s.substr(left, right - left + 1);\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator)\n{\n std::stringstream ss;\n bool repeated = false;\n for (_ForwardIterator i = first; i != last; i++)\n {\n if (repeated)\n ss << separator;\n else\n repeated = true;\n ss << *i;\n }\n return ss.str();\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last)\n{\n return join(first, last, ' ');\n}\n\ntemplate \nstd::string join(const _Collection& collection, _Separator separator)\n{\n return join(collection.begin(), collection.end(), separator);\n}\n\ntemplate \nstd::string join(const _Collection& collection)\n{\n return join(collection, ' ');\n}\n\n/**\n * Splits string s by character separator returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separator returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n if (!item.empty())\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n \n if (!item.empty())\n result.push_back(item);\n\n return result;\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char* prepend)\n{\n std::string message;\n if (strlen(prepend) != 0)\n message = format(\"%s: expected '%s', but found '%s'\",\n compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());\n else\n message = format(\"expected '%s', but found '%s'\",\n compress(expected).c_str(), compress(found).c_str());\n quit(result, message);\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char* prepend)\n{\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend);\n}\n\ntemplate \n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, T expected, T found, const char* prependFormat = \"\", ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = vtos(expected);\n std::string foundString = vtos(found);\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, std::string expected, std::string found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, expected, found, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, double expected, double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, const char* expected, const char* found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, float expected, float found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, long double expected, long double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\n#endif\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate \nstruct is_iterable\n{\n template \n static char test(typename U::iterator* x);\n \n template \n static long test(U* x);\n \n static const bool value = sizeof(test(0)) == 1;\n};\n\ntemplate\nstruct __testlib_enable_if {};\n \ntemplate\nstruct __testlib_enable_if { typedef T type; };\n\ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n std::cout << t;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n bool first = true;\n for (typename T::const_iterator i = t.begin(); i != t.end(); i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n std::cout << *i;\n }\n}\n\ntemplate<>\ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const std::string& t)\n{\n std::cout << t;\n}\n \ntemplate\nvoid __println_range(A begin, B end)\n{\n bool first = true;\n for (B i = B(begin); i != end; i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n __testlib_print_one(*i);\n }\n std::cout << std::endl;\n}\n\ntemplate\nstruct is_iterator\n{ \n static T makeT();\n typedef void * twoptrs[2];\n static twoptrs & test(...);\n template static typename R::iterator_category * test(R);\n template static void * test(R *);\n static const bool value = sizeof(test(makeT())) == sizeof(void *); \n};\n\ntemplate\nstruct is_iterator::value >::type>\n{\n static const bool value = false; \n};\n\ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __println_range(a, b);\n}\n\ntemplate \nvoid println(const A* a, const A* b)\n{\n __println_range(a, b);\n}\n\ntemplate <>\nvoid println(const char* a, const char* b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const T& x)\n{\n __testlib_print_one(x);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f, const G& g)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << \" \";\n __testlib_print_one(g);\n std::cout << std::endl;\n}\n#endif\n\n\n\nvoid registerChecker(std::string probName, int argc, char* argv[])\n{\n setName(\"checker for problem %s\", probName.c_str());\n registerTestlibCmd(argc, argv);\n}\n\n\n\nconst std::string _grader_OK = \"OK\";\nconst std::string _grader_SV = \"SV\";\nconst std::string _grader_PV = \"PV\";\nconst std::string _grader_WA = \"WA\";\nconst std::string _grader_FAIL = \"FAIL\";\n\n\nvoid InStream::readSecret(\n std::string secret,\n TResult mismatchResult,\n std::string mismatchMessage,\n std::string eofMessage)\n{\n if (seekEof())\n quits(mismatchResult, eofMessage);\n if (readWord() != secret)\n quits(mismatchResult, mismatchMessage);\n eoln();\n}\n\nvoid readBothSecrets(std::string secret)\n{\n ans.readSecret(\n secret,\n _fail,\n \"Secret mismatch in the (correct) answer file\",\n \"Empty (correct) answer file\");\n ouf.readSecret(\n secret,\n _pv,\n \"Possible tampering with the output\",\n \"Early termination of the solution (possibly calling exit)\");\n}\n\n\nvoid InStream::quitByGraderResult(TResult result, std::string defaultMessage)\n{\n std::string msg = \"\";\n if (!eof())\n msg = readLine();\n if (msg.empty())\n quits(result, defaultMessage);\n quits(result, msg);\n}\n\nvoid InStream::readGraderResult()\n{\n std::string result = readWord();\n eoln();\n if (result == _grader_OK)\n return;\n if (result == _grader_SV)\n quitByGraderResult(_sv, \"Security violation detected in grader\");\n if (result == _grader_PV)\n quitByGraderResult(_pv, \"Protocol violation detected in grader\");\n if (result == _grader_WA)\n quitByGraderResult(_wa, \"Wrong answer detected in grader\");\n if (result == _grader_FAIL)\n quitByGraderResult(_fail, \"Failure in grader\");\n quitf(_fail, \"Unknown grader result\");\n}\n\nvoid readBothGraderResults()\n{\n ans.readGraderResult();\n ouf.readGraderResult();\n}\n\n\nNORETURN void quit(TResult result)\n{\n ouf.quit(result, \"\");\n}\n\n/// Used in validators: skips the rest of input, assuming it to be correct\nNORETURN void skip_ok()\n{\n if (testlibMode != _validator)\n quitf(_fail, \"skip_ok() only works in validators\");\n testlibFinalizeGuard.quitCount++;\n halt(0);\n}\n\n/// 1 -> 1st, 2 -> 2nd, 3 -> 3rd, 4 -> 4th, ...\nstd::string englishTh(int x)\n{\n char c[100];\n snprintf(c, sizeof(c), \"%d%s\", x, englishEnding(x).c_str());\n return c;\n}\n\n/// Compares the tokens of two lines\nvoid compareTokens(int lineNo, std::string a, std::string b, char separator=' ')\n{\n std::vector toka = tokenize(a, separator);\n std::vector tokb = tokenize(b, separator);\n if (toka == tokb)\n return;\n std::string dif = format(\"%s lines differ - \", englishTh(lineNo).c_str());\n if (toka.size() != tokb.size())\n quitf(_wa, \"%sexpected: %d tokens, found %d tokens\", dif.c_str(), int(toka.size()), int(tokb.size()));\n for (int i=0; i\nusing namespace std;\n\nstatic int queries = 0;\nstatic int query_limit = 100000;\n\nvoid log_metrics() {\n tout << \"queries=\" << queries << endl;\n tout << \"query_limit=\" << query_limit << endl;\n}\n\nvoid finish(TResult verdict, const string& msg) {\n log_metrics();\n quitf(verdict, \"%s\", msg.c_str());\n}\n\nint main(int argc, char* argv[]) {\n registerInteraction(argc, argv);\n atexit(log_metrics);\n\n inf.readLong(); // seed (unused)\n int x = inf.readInt();\n int y = inf.readInt();\n\n log_metrics();\n\n cout << x << \" \" << y << endl;\n cout.flush();\n\n while (x > 1 || y > 1) {\n char dir;\n int pos;\n if (!(cin >> dir >> pos)) {\n finish(_pe, \"Invalid input format\");\n }\n\n queries++;\n if (queries > query_limit) {\n finish(_wa, \"Too many moves\");\n }\n\n if (dir == 'V' || dir == 'v') {\n if (pos <= 0 || pos >= x) {\n finish(_wa, \"Invalid vertical cut\");\n }\n x = max(pos, x - pos);\n } else if (dir == 'H' || dir == 'h') {\n if (pos <= 0 || pos >= y) {\n finish(_wa, \"Invalid horizontal cut\");\n }\n y = max(pos, y - pos);\n } else {\n finish(_pe, \"Invalid direction\");\n }\n\n cout << x << \" \" << y << endl;\n cout.flush();\n }\n\n finish(_ok, \"Correct\");\n return 0;\n}\n", "rec_interactor.cpp": "// IOI05_E (rec) - Rectangle Game Interactor\n// Opponent strategy: always keep the larger piece\n#include \nusing namespace std;\n\nint x, y;\nint moves = 0;\nconst int MAX_MOVES = 100000;\n\nvoid finish(int code, const char* msg) {\n fprintf(stderr, \"%s\\n\", msg);\n // Write to tout.txt for harness\n FILE* tout = fopen(\"tout.txt\", \"w\");\n if (tout) {\n fprintf(tout, \"queries=%d\\n\", moves);\n fprintf(tout, \"query_limit=%d\\n\", MAX_MOVES);\n fclose(tout);\n }\n exit(code);\n}\n\nint main(int argc, char* argv[]) {\n if (argc < 2) {\n finish(2, \"Usage: interactor \");\n }\n\n FILE* fin = fopen(argv[1], \"r\");\n if (!fin) {\n finish(2, \"Cannot open input file\");\n }\n\n long long seed;\n fscanf(fin, \"%lld %d %d\", &seed, &x, &y);\n fclose(fin);\n\n // Send initial dimensions\n printf(\"%d %d\\n\", x, y);\n fflush(stdout);\n\n while (x > 1 || y > 1) {\n char dir;\n int pos;\n if (scanf(\" %c %d\", &dir, &pos) != 2) {\n finish(2, \"PE: Invalid input format\");\n }\n\n moves++;\n if (moves > MAX_MOVES) {\n finish(1, \"WA: Too many moves\");\n }\n\n if (dir == 'V' || dir == 'v') {\n if (pos <= 0 || pos >= x) {\n finish(1, \"WA: Invalid vertical cut position\");\n }\n x = max(pos, x - pos);\n } else if (dir == 'H' || dir == 'h') {\n if (pos <= 0 || pos >= y) {\n finish(1, \"WA: Invalid horizontal cut position\");\n }\n y = max(pos, y - pos);\n } else {\n finish(2, \"PE: Invalid direction\");\n }\n\n printf(\"%d %d\\n\", x, y);\n fflush(stdout);\n }\n\n finish(0, \"OK\");\n return 0;\n}\n"}} {"problem_id": "ioi18_e", "cate": ["graph", "search"], "difficulty": "hard", "cpu_time_limit_ms": 1000, "memory_limit_mb": 512, "description": "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.\n\nA 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.$\n\nYou 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.\n\nHowever, 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.\n\nImplementation details\n\nYou should implement the following procedure:\n\nfind\\_pair(int N, int[] U, int[] V, int A, int B)\n\n* $N$: the number of cities.\n* $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].$\n* $A$: the toll for a highway when the traffic is light.\n* $B$: the toll for a highway when the traffic is heavy.\n* This procedure is called exactly once for each test case.\n* Note that the value of $M$ is the lengths of the arrays, and can be obtained as indicated in the implementation notice.\n\nint64 ask(int[] w)\n\n* The length of $w$ must be $M.$ The array $w$ describes the traffic conditions.\n* 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.$\n + $w[i] = 0$ means the traffic of the highway $i$ is light.\n + $w[i] = 1$ means the traffic of the highway $i$ is heavy.\n* This function returns the smallest total toll for travelling between the cities $S$ and $T,$ under the traffic conditions specified by $w.$\n* This function can be called at most $100$ times (for each test case).\n\nfind\\_pair should call the following procedure to report the answer:\n\nanswer(int s, int t)\n\n* s and t must be the pair $S$ and $T$ (the order does not matter).\n* This procedure must be called exactly once.\n\nIf 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).\n\nConstraints\n\n* $2 \\le N \\le 90\\,000$\n* $1 \\le M \\le 130\\,000$\n* $1 \\le A < B \\le 1\\,000\\,000\\,000$\n* For each $i: 0 \\le i M-1$\n + $0 \\le U[i] \\le N-1$\n + $0 \\le V[i] \\le N-1$\n + $U[i] \\neq V[i]$\n* $(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$\n* You can travel from any city to any other city by using the highways.\n* $0 \\le S \\le N-1$\n* $0 \\le T \\le N-1$\n* $S \\neq T$\n\nIn 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.\n\nSample grader\n\nThe sample grader reads the input in the following format:\n\n| | | | | |\n| --- | --- | --- | --- | --- |\n| line | $1$ | : | $N$ $M$ $A$ $B$ $S$ $T$ | |\n| line | $2+i$ | : | $U[i]$ $V[i]$ | $(0 \\le i \\le M-1)$ |\n\nIf your program is judged as Accepted, the sample grader prints Accepted: q, with $q$ the number of calls to ask.\n\nIf your program is judged as Wrong Answer, it prints Wrong Answer: MSG, where MSG is one of:\n\n* answered not exactly once: The procedure answer was not called exactly once.\n* 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.$\n* more than 100 calls to ask: The function ask is called more than $100$ times.\n* {s, t} is wrong: The procedure answer is called with an incorrect pair $s$ and $t.$\n\nScoring\n\nSubtasks\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points (max) | Additional constraints |\n| $1$ | $5$ | $M=N-1,$ one of $S$ or $T$ is $0,$ $N \\le 100$ |\n| $2$ | $7$ | $M=N-1,$ one of $S$ or $T$ is $0$ |\n| $3$ | $6$ | $M=N-1,$ $U[i] = i,$ $V[i] = i+1$ for all $i: 0\\le i \\le M-1$ |\n| $4$ | $33$ | $M=N-1$ |\n| $5$ | $18$ | $A=1,$ $B=2$ |\n| $6$ | $31$ | No |\n\nAssume 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:\n\n| | | | |\n| --- | --- | --- | --- |\n| Subtask 1 | $P=5$ | | |\n| Subtask 2 | If $X \\le 60,$ | $P=7.$ | Otherwise $P=0.$ |\n| Subtask 3 | If $X \\le 60,$ | $P=6.$ | Otherwise $P=0.$ |\n| Subtask 4 | If $X \\le 60,$ | $P=33.$ | Otherwise $P=0.$ |\n| Subtask 5 | If $X \\le 52,$ | $P=18.$ | Otherwise $P=0.$ |\n| Subtask 6 | If $X \\le 50,$ | $P=31.$ | If $51\\le X\\le 52, P=21.$ |\n| | | | Otherwise $P=0.$ |\n\nNote that your score for each subtask is the minimum of the scores for the test cases in the subtask.\n\nNote\n\nExample\n\nLet $N=4,$ $M=4,$ $U=[0,0,0,1],$ $V=[1,2,3,2],$ $A=1,$ $B=3,$ $S=1,$ and $T=3.$\n\nThe grader calls find\\_pair(4, [0, 0, 0, 1], [1, 2, 3, 2], 1, 3).\n\n![](https://ioi.contest.codeforces.com/espresso/451ff65ba01e76034a1e4c53b7ae83741e667ce9.png)\n\nIn 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:\n\n| | |\n| --- | --- |\n| Call | Return |\n| ask([0, 0, 0, 0]) | $2$ |\n| ask([0, 1, 1, 0]) | $4$ |\n| ask([1, 0, 1, 0]) | $5$ |\n| ask([1, 1, 1, 1]) | $6$ |\n\nFor 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.$\n\nFor a correct answer, the procedure find\\_pair should call answer(1, 3) or answer(3, 1).\n\nThe file sample-01-in.txt in the zipped attachment package corresponds to this example. Other sample inputs are also available in the package.", "interactor_files": {"grader.cpp": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"highway.h\"\n\nnamespace {\n\nconstexpr int MAX_NUM_CALLS = 100;\nconstexpr long long INF = 1LL << 61;\n\nint N, M, A, B, S, T;\nstd::vector U, V;\nstd::vector>> graph;\n\nbool answered, wrong_pair;\nint num_calls;\n\nint read_int() {\n int x;\n if (scanf(\"%d\", &x) != 1) {\n fprintf(stderr, \"Error while reading input\\n\");\n exit(1);\n }\n return x;\n}\n\nvoid wrong_answer(const char *MSG) {\n printf(\"Wrong Answer: %s\\n\", MSG);\n exit(0);\n}\n\n} // namespace\n\nlong long ask(const std::vector &w) {\n if (++num_calls > MAX_NUM_CALLS) {\n wrong_answer(\"more than 100 calls to ask\");\n }\n if (w.size() != (size_t)M) {\n wrong_answer(\"w is invalid\");\n }\n for (size_t i = 0; i < w.size(); ++i) {\n if (!(w[i] == 0 || w[i] == 1)) {\n wrong_answer(\"w is invalid\");\n }\n }\n\n std::vector visited(N, false);\n std::vector current_dist(N, INF);\n std::queue qa, qb;\n qa.push(S);\n current_dist[S] = 0;\n while (!qa.empty() || !qb.empty()) {\n int v;\n if (qb.empty() ||\n (!qa.empty() && current_dist[qa.front()] <= current_dist[qb.front()])) {\n v = qa.front();\n qa.pop();\n } else {\n v = qb.front();\n qb.pop();\n }\n if (visited[v]) {\n continue;\n }\n visited[v] = true;\n long long d = current_dist[v];\n if (v == T) {\n return d;\n }\n for (auto e : graph[v]) {\n int vv = e.first;\n int ei = e.second;\n if (!visited[vv]) {\n if (w[ei] == 0) {\n if (current_dist[vv] > d + A) {\n current_dist[vv] = d + A;\n qa.push(vv);\n }\n } else {\n if (current_dist[vv] > d + B) {\n current_dist[vv] = d + B;\n qb.push(vv);\n }\n }\n }\n }\n }\n return -1;\n}\n\nvoid answer(int s, int t) {\n if (answered) {\n wrong_answer(\"answered not exactly once\");\n }\n\n if (!((s == S && t == T) || (s == T && t == S))) {\n wrong_pair = true;\n }\n\n answered = true;\n}\n\nint main() {\n N = read_int();\n M = read_int();\n A = read_int();\n B = read_int();\n S = read_int();\n T = read_int();\n U.resize(M);\n V.resize(M);\n graph.assign(N, std::vector>());\n for (int i = 0; i < M; ++i) {\n U[i] = read_int();\n V[i] = read_int();\n graph[U[i]].push_back({V[i], i});\n graph[V[i]].push_back({U[i], i});\n }\n\n answered = false;\n wrong_pair = false;\n num_calls = 0;\n find_pair(N, U, V, A, B);\n if (!answered) {\n wrong_answer(\"answered not exactly once\");\n }\n if (wrong_pair) {\n wrong_answer(\"{s, t} is wrong\");\n }\n printf(\"Accepted: %d\\n\", num_calls);\n return 0;\n}\n", "highway.cpp": "#include \"highway.h\"\n\nvoid find_pair(int N, std::vector U, std::vector V, int A, int B) {\n int M = U.size();\n for (int j = 0; j < 50; ++j) {\n std::vector w(M);\n for (int i = 0; i < M; ++i) {\n w[i] = 0;\n }\n long long toll = ask(w);\n }\n answer(0, N - 1);\n}\n", "highway.h": "#include \n\nvoid find_pair(int N, std::vector U, std::vector V, int A, int B);\n\nlong long ask(const std::vector &w);\nvoid answer(int s, int t);\n"}} {"problem_id": "ioi10_d", "cate": ["data structures", "math"], "difficulty": "easy", "cpu_time_limit_ms": 5000, "memory_limit_mb": 256, "description": "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.\n\nEach 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.\n\nYou 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.\n\nThe 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.\n\nYou 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.\n\nNote 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.\n\nFor illustration only, we show the textual representation of excerpts from 56 language-specific editions of Wikipedia.\n\n1. Yshokkie word meestal in Kanada , die noorde van die VSA en in Europa gespeel. Dit is bekend as 'n b\n\n2. وهو المنتج الذي يجعل المنظم ال يكسب ربحا وال يخسر ويحصل على ، Producer Marginal المنتج الحدي دخل يكف\n\n3. \"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\n\n4. Квинт Фулвий Флак (Quintus Fulvius Flaccus; † 205 пр.н.е. ) e политик и генерал на Римската републик\n\n5. ইন্ডিয়ান ইনস্টিটিউি অফ স ়াশ্য়াল ওযযলযফয়ার অয়াি স্টিজযন ম্য়াযনজযম্ন্ট ( ংযেযে আইআইএ ডস্টিউস্টিএম্ )\n\n6. 5. juni ( lipanj ) ( 5.6. ) je 156. dan godine po gregorijanskom kalendaru (157. u prestupnoj godini\n\n7. La Caunette és un municipi francès , situat al departament de l' Erau i a la regió de Llenguadoc-Ros\n\n8. Praha je malé městečko v Texasu , které leží cca 85 km na jihozápad od Austinu . Bylo založeno\n\n9. Graeme Allen Brown (født 9. april 1979 i Darwin , Northern Territory , Australien ) er en australsk\n\n10. Der Plattiger Habach ( 3.214 m ü. A. , nach anderen Angaben nur 3.207 m [1] )\n\n11. Το Νησί Γκρέιτ Μπάρριερ ( Αγγλικά : Great Barrier Island , Μαορί : Motu Aotea ) είναι νησί στα βόρει\n\n12. Sid Bernstein Presents... is a 2010 feature-length documentary film by directors Jason Ressler and E\n\n13. El término latino lex loci celebrationis aplicado al derecho internacional privado quiere decir: \"le\n\n14. Apollo 5 oli kosmoselaev , mis sooritas Apollo programmi teise mehitamata lennu. Lennu käigus testit\n\n15. هزار و سیصد و پنجاهمین سیارک( TAنامگذاری :1934 ، Rosselia به انگلیسی : 1350 (سیارک ۱۳۵۰ کشف شدهاس\n\n16. V. I. Beretti (myös Vikenty Ivanovitš Beretti , alk. Vincent Beretti ; 1781 Milano Italia – 18. elok\n\n17. Le 5 e bataillon de parachutistes vietnamiens (ou 5 e BPVN ou encore 5 e Bawouan ) est une unité par\n\n18. Amina Sarauniyar Zazzau,, wadda ta rayu daga shekarar 1533 zuwa 1610, ɗaya ce daga cikin 'ya'ya biyu\n\nב מתמטיקה , השערת רימן היא השערה שהציע בשנת 1859 ה מתמטיקאי ברנרד רימן , מגדולי .19 המתמטיקאים של אותה ע\n\n20. Sudski proces Doe protiv Boltona je sudski proces iz 1973 . godine kojim je američki Vrhovni sud uki\n\n21. Owen Cunningham Wilson ( 1968 . november 18. , Dallas , Texas , Egyesült Államok ) amerikai színész\n\n22. Հայ Կաթողիկե Եկեղեցին պատկանում է Արևելյան Կաթոլիկ Եկեղեցիներին և այսպիսով ենթարկվում է Հռոմի Պապի ա\n\n23. Dionysios dari Halicarnassus ( Bahasa Yunani : Διονύσιος Ἀλεξάνδρου Ἀλικαρνᾱσσεύς , Dionysios putra\n\n24. Nnamdi \"Zik\" Azikiwe , bu onye isi-ala izizi Nijiria nwere. Ochichi ya bidolu na afo 1954 welu ruo n\n\n25. La Riserva naturale orientata Serre della Pizzuta è un'area protetta del dipartimento Regionale di S\n\n26. 石橋和義 (いしばし かずよし/まさよし、生没年不詳)は、 �詳。 石橋氏 初 代当主。初名氏義。 尾張 三郎を通称とし、官途は、 左近将監 → 三河守 → 左 衛門佐 。 足利直義\n\n27. კორბინ ბლიუ ( ინგლ. Corbin Bleu ; დ. 21 თებერვალი , 1989 , დაბადების ადგილი ბრუკლინი , ნიუ-იორკი , ა\n\n28. Та́рья Ка́арина Ха́лонен (Tarja Kaarina Halonen)); 24 желтоқсан , 1943 , Каллио , Хельсинки , Финлан\n\n29. 딜롱 ( Dilong )은 중국 랴오닝(Liaoning) 지방의 익시안층(Yixian Formation)에서 온전한 4구의 화석으로 발견되었다. 이 공룡은 가장 원시적인 초기의 티\n\n30. Сүймөнкул Чокморов - советтик актёр. Жетинин айынын 9 (ноябрь) 1939-жылы, Фрунзе шаарын жанындагы Чо\n\n31. D' Mirjam vun Abellin war eng Nonn a Mystikerin , och \" Maria vum gekräizegte Jesus \" genannt. Si as\n\n32. Panopea abrupta ( angl. Geoduck ) - jūrinių dvigeldžių moliuskų rūšis, priklausanti Hiatellidae šeim\n\n33. \"Dzimis Latvijā\" ir Liepājas dueta Fomins & Kleins 2004 . gada 23. februārī izdotais otrais albu\n\n34. I Ludwik Lejzer Zamenhof dia dokotera mpijery maso nipetraka any Polonia . Fantantsika izy ankehitri\n\n35. Седумстотини милиони малечки алвеоли во белите дробови , всушност се шупливи чаури - алвеоли прекрие\n\n36. Энэхүү шувуу нь Бутан , Хятад , Гонконг , Энэтхэг , Пакистан , Иран , Япон , Казакстан , Солонгос ,\n\n37. भारतातील महाराष्ट्रराज्याच्या नागपूर पासुन २१६ कि.मी. दू र असलेलेएि गाव. तेवैनगंगा नदीच्या िाठावर\n\n38. De Slotervaart was oorspronkelijk de waterweg die sinds de Middeleeuwen het dorp Sloten verbond met\n\n39. Macierz S (macierz rozpraszania, od ang. scattering matrix ) jest centralnym elementem w mechanice k\n\n40. A Hora do Rush 3 ( Rush Hour 3 , no original) é o terceiro filme da franquia Rush Hour . Dirigido po\n\n41. Coordonate : 51°34′0″N 12°3′0″E / 51.56667 , 12.05 Brachstedt este o comună din landul Saxonia-A\n\n42. Гробницы императоров династии Мин и Цин — памятник Всемирного наследия ЮНЕСКО , состоящий из несколь\n\n43. Kovalentni radijus atoma - ponekad se naziva i valentni radijus. Kovalentni radijus je srednje rasto\n\n44. Koniecpol je mesto v Poľsku v Sliezskom vojvodstve v okrese Powiat częstochowski v rovnomennej gmine\n\n45. Hoxhë Vokrri vije nga Shqipëria ishte një klerik shqiptar i cili luftonte për Çështjën Kombëtare . A\n\n46. Гурдијеље је насеље у општини Тутин у Рашком округу . Према попису из 2002. било је 93 становника (п\n\n47. Underhållsstöd betalas ut av Försäkringskassan (FK) till en förälder som är vårdnadshavare och bor e\n\n48. இந்தியாவின் தேசிய நநடுஞ்சாலைகள் நடுவண் அரசின் தேசிய நநடுஞ்சாலைே்துலையாை் பராமரிக்கப்படுகின் ைன. நபரு\n\n49. Дар он зиндаги .маишат ,фаолияти мехнати,муборизаи ичтимои, русуму омол, хислат ва эхсосоти халк ифо\n\n50. ไฟทอฟธอรา อินเฟสทันส ( อังกฤษ : Phytophthora infestans ) คอืเชือ้ ราโอโอไมซีท หรือ ราน ้า ที ่ เป็นสาเห\n\n51. ABUL FAWARIS BERRANY - 11. asyrda Orta Aziýadaky oguz taýpalarynyň berrany dinastiýasynyň wekili. Ol\n\n52. Egemenlik ya da hâkimiyet , bir toprak parçası ya da mekan üzerindeki kural koyma gücü ve hukuk yara\n\n53. Темне фентезі (від англ. Dark Fantasy - темне, похмуре фентезі ) - піджанр літератури, який включає\n\n54. Paris By Night 84: In Atlanta - Passport to Music & Fashion (Âm nhạc và Thời trang) là chương tr\n\n55. ISO 3166-2:GU ni akoole ninu ISO 3166-2 , apa opagun ISO 3166 ti International Organization for Stan\n\n56. 下卡姆斯克 ( 俄文 : Нижнека́мск ; 韃靼語 : Түбəн Кама/Tübän Kama )是 俄 羅斯 韃靼斯坦共和國 東北部的一個城市,位於 卡馬河 南岸。 2002年 人口22\n\nThe 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:\n\n* The two-letter ISO code for the Wikipedia language edition;\n* 100 numbers between 1 and 65 535, representing the first 100 symbols, in sequence, of the first paragraph of the article;\n\nThe 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.\n\nScoring\n\nSubtask 1 [30 points] Your submission must achieve accuracy of $0.3$ or better on the grading server.\n\nSubtask 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.\n\nYou 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.", "interactor_files": {"grader.cpp": "#include \"grader.h\"\n#include \"lang.h\"\n\n#include \n#include \n#include \n#include \n\n#define N 100\n\nstatic char lang[20], lan[100][20];\nstatic int lnum, i,j,k,n,nl, uni[N], right, tot;\nint language(int L) {\n if (L < 0 || L >= 56) exit(92);\n right += (L == lnum);\n tot++;\n return lnum;\n}\n\nint main(){\n for (n=0; 1 == scanf(\"%s\",lang); n++) {\n for (i=0;i\n#include \n\n#include \"grader.h\"\n#include \"lang.h\"\n\n#define SZ 100\n\nint prev[1100000];\n\nvoid excerpt(int *E) {\n prev[E[0]] = language(prev[E[0]]);\n}\n", "grader.h": "int language(int L);\n", "lang.h": "void excerpt(int *E);\n"}} {"problem_id": "ioi15_f", "cate": ["graph", "search"], "difficulty": "hard", "cpu_time_limit_ms": 2000, "memory_limit_mb": 1024, "description": "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.\n\nAll 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.\n\nIt 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.\n\nThe 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.\n\n![](https://ioi.contest.codeforces.com/espresso/d9ad919321a7cefe2c132ba7f744c8f8e156c096.png)\n\nEvery 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.\n\nFor 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)$.\n\nIn 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.\n\nRemoving 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$.\n\nIn 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.\n\nTask\n\nInitially, 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.\n\nYour task is to determine:\n\n* In all subtasks: the distance $R$.\n* In subtasks $3$ to $6$: whether there is a balanced hub in the network.\n\nYou 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.\n\n* int hubDistance(int N, int sub)\n + $N$: the number of small towns.\n + $sub$: the subtask number (explained in the Scoring section).\n + If $sub$ is 1 or 2, the function can return either $R$ or $-R$.\n + if $sub$ is greater than 2, if there exists a balanced hub then the function must return $R$, otherwise it must return $-R$.\n\nYour 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.\n\nInput\n\nThe sample grader reads the input in the following format:\n\n* line 1: Subtask number and the number of test cases.\n* line 2: $N_1$, the number of small towns in the first test case.\n* 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$.\n* The next test cases follow. They are given in the same format as the first test case.\n\nOutput\n\nFor each test case, the sample grader prints the return value of hubDistance and the number of calls made on separate lines.\n\nScoring\n\nIn each test case:\n\n* $N$ is between $6$ and $110$ inclusive.\n* The distance between any two distinct small towns is between $1$ and $1\\,000\\,000$ inclusive.\n\nThe 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.\n\n| | | | | |\n| --- | --- | --- | --- | --- |\n| Subtask | Points | Number of queries | Find balanced hub | Additional constraints |\n| 1 | 13 | $\\frac{N(N-1)}{2}$ | NO | — |\n| 2 | 12 | $\\lceil \\frac{7N}{2} \\rceil$ | NO | — |\n| 3 | 13 | $\\frac{N(N-1)}{2}$ | YES | — |\n| 4 | 10 | $\\lceil \\frac{7N}{2} \\rceil$ | YES | Each large city is connected to exactly three settlements |\n| 5 | 13 | $5n$ | YES | — |\n| 6 | 39 | $\\lceil \\frac{7N}{2} \\rceil$ | YES | — |\n\nNote that $\\lceil x \\rceil$ denotes the smallest integer which is greater than or equal to $x$.\n\nNote\n\nNote that the subtask number is a part of the input. The sample grader changes its behavior according to the subtask number.\n\nThe input file corresponding to the example above is:\n\n```\n1 1 \n11 \n0 17 18 20 17 12 20 16 23 20 11 \n17 0 23 25 22 17 25 21 28 25 16 \n18 23 0 12 21 16 24 20 27 24 17 \n20 25 12 0 23 18 26 22 29 26 19 \n17 22 21 23 0 9 21 17 26 23 16 \n12 17 16 18 9 0 16 12 21 18 11 \n20 25 24 26 21 16 0 10 29 26 19 \n16 21 20 22 17 12 10 0 25 22 15 \n23 28 27 29 26 21 29 25 0 21 22 \n20 25 24 26 23 18 26 22 21 0 19 \n11 16 17 19 16 11 19 15 22 19 0\n```\n\nThis 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.", "interactor_files": {"grader.cpp": "#include \"towns.h\"\n#include \n#include \n#include \n#include \"graderlib.c\"\n\nint main() {\n FILE *f;\n f = freopen(\"towns.in\",\"r\",stdin);\n assert(f != NULL);\n f = freopen(\"towns.out\",\"w\",stdout);\n assert(f != NULL);\n int ncase, R, N;\n int subtask;\n int ret;\n ret = scanf(\"%d%d\",&subtask,&ncase);\n assert(ret == 2);\n for (int i = 0; i < ncase; i++) {\n ret = scanf(\"%d\",&N);\n\tassert(ret == 1);\n _ini_query(N,subtask);\n R=hubDistance(N,subtask);\n printf(\"%d\\n\",R);\n }\n return 0;\n}\n", "towns.cpp": "#include \"towns.h\"\n\nint hubDistance(int N, int sub) {\n\tint R = getDistance(0,1);\n\treturn R;\n}\n", "graderlib.c": "#include \n#include \n\nstatic int _N;\nstatic int _dist[110][110];\nstatic int _quota, _user_query;\n\nvoid _ini_query(int N, int k) {\n int ret;\n _N = N;\n for (int i = 0; i < _N; i++) \n for (int j = 0; j < _N; j++) {\n\t ret = scanf(\"%d\", &_dist[i][j]);\n assert(ret == 1);\n }\n if (k == 1 || k == 3) _quota = _N * (_N - 1) / 2;\n else if (k == 2 || k == 4 || k == 6) _quota = (7 * _N + 1) / 2;\n else _quota = 5 * _N;\n _user_query = 0;\n}\n\n\nint getDistance(int i, int j) {\n _user_query++;\n if (_user_query > _quota) {\n printf(\"0\\n\");\n exit(0);\n }\n if (i < 0 || i >= _N) return 0;\n if (j < 0 || j >= _N) return 0;\n return _dist[i][j];\n}\n\n", "towns.h": "#ifndef towns_h\n#define towns_h\n\nint getDistance(int i, int j);\nint hubDistance(int N, int sub);\n\n#endif\n"}, "materialization": {"file_patches": [{"path": "interactor/grader.cpp", "replacements": [{"match": " printf(\"%d\\n\",R);\n", "replace": " printf(\"%d\\n\", (subtask == 1 || subtask == 2) ? abs(R) : R);\n"}]}]}} {"problem_id": "ioi22_e", "cate": ["search", "data structures"], "difficulty": "medium", "cpu_time_limit_ms": 2000, "memory_limit_mb": 2048, "description": "There are $N$ insects, indexed from $0$ to $N - 1$, running around Pak Blangkon's house. Each insect has a type, which is an integer between $0$ and $10^9$ inclusive. Multiple insects may have the same type.\n\nSuppose insects are grouped by type. We define the cardinality of the most frequent insect type as the number of insects in a group with the most number of insects. Similarly, the cardinality of the rarest insect type is the number of insects in a group with the least number of insects.\n\nFor example, suppose that there are $11$ insects, whose types are $[5, 7, 9, 11, 11, 5, 0, 11, 9, 100, 9]$. In this case, the cardinality of the most frequent insect type is $3$. The groups with the most number of insects are type $9$ and type $11$, each consisting of $3$ insects. The cardinality of the rarest insect type is $1$. The groups with the least number of insects are type $7$, type $0$, and type $100$, each consisting of $1$ insect.\n\nPak Blangkon does not know the type of any insect. He has a machine with a single button that can provide some information about the types of the insects. Initially, the machine is empty. To use the machine, three types of operations can be performed:\n\n1. Move an insect to inside the machine.\n2. Move an insect to outside the machine.\n3. Press the button on the machine.\n\nEach type of operation can be performed at most $40\\;000$ times.\n\nWhenever the button is pressed, the machine reports the cardinality of the most frequent insect type, considering only insects inside the machine.\n\nYour task is to determine the cardinality of the rarest insect type among all $N$ insects in Pak Blangkon's house by using the machine. Additionally, in some subtasks, your score depends on the maximum number of operations of a given type that are performed (see Subtasks section for details).\n\nImplementation Details\n\nYou should implement the following procedure:\n\n* int min\\_cardinality(int N)\n + $N$: the number of insects.\n + This procedure should return the cardinality of the rarest insect type among all $N$ insects in Pak Blangkon's house.\n + This procedure is called exactly once.The above procedure can make calls to the following procedures:\n* void move\\_inside(int i)\n + $i$: the index of the insect to be moved inside the machine. The value of $i$ must be between $0$ and $N - 1$ inclusive.\n + If this insect is already inside the machine, the call has no effect on the set of insects in the machine. However, it is still counted as a separate call.\n + This procedure can be called at most $40\\;000$ times.\n* void move\\_outside(int i)\n + $i$: the index of the insect to be moved outside the machine. The value of $i$ must be between $0$ and $N - 1$ inclusive.\n + If this insect is already outside the machine, the call has no effect on the set of insects in the machine. However, it is still counted as a separate call.\n + This procedure can be called at most $40\\;000$ times.\n* int press\\_button()\n + This procedure returns the cardinality of the most frequent insect type, considering only insects inside the machine.\n + This procedure can be called at most $40\\;000$ times.\n + The grader is not adaptive. That is, the types of all $N$ insects are fixed before min\\_cardinality is called.\n\nInteraction\n\nLet $T$ be an array of $N$ integers where $T[i]$ is the type of insect $i$.\n\nThe sample grader reads the input in the following format:\n\n* line $1$: $N$ ($2 \\le N \\le 2000$)\n* line $2$: $T[0] \\; T[1] \\; \\ldots \\; T[N - 1]$\n\nIf the sample grader detects a protocol violation, the output of the sample grader is Protocol Violation: , where is one of the following:\n\n* invalid parameter: in a call to move\\_inside or move\\_outside, the value of $i$ is not between $0$ and $N - 1$ inclusive.\n* too many calls: the number of calls to any of move\\_inside, move\\_outside, or press\\_button exceeds $40\\;000$.\n\nOtherwise, the output of the sample grader is in the following format:\n\n* line $1$: the return value of min\\_cardinality\n* line $2$: $q$\n\nScoring\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 1 | 10 | $N \\le 200$ |\n| 2 | 15 | $N \\le 1000$ |\n| 3 | 75 | No additional constraints |\n\nIf in any of the test cases, the calls to the procedures move\\_inside, move\\_outside, or press\\_button do not conform to the constraints described in Implementation Details, or the return value of min\\_cardinality is incorrect, the score of your solution for that subtask will be $0$.\n\nLet $q$ be the maximum of the following three values: the number of calls to move\\_inside, the number of calls to move\\_outside, and the number of calls to press\\_button.\n\nIn subtask 3, you can obtain a partial score. Let $m$ be the maximum value of $\\frac{q}{N}$ across all test cases in this subtask. Your score for this subtask is calculated according to the following table:\n\n| | |\n| --- | --- |\n| Condition | Points |\n| $20 \\textless m$ | $0$ (reported as | quot;Output isn't correct | quot; in CMS) |\n| $6 \\textless m \\le 20$ | $\\frac{225}{m - 2}$ |\n| $3 \\textless m \\le 6$ | $81 - \\frac{2}{3} m^2$ |\n| $m \\le 3$ | $75$ |\n\nNote\n\nConsider a scenario in which there are $6$ insects of types $[5, 8, 9, 5, 9, 9]$ respectively. The procedure min\\_cardinality is called in the following way:\n\nmin\\_cardinality(6)\n\nThe procedure may call move\\_inside, move\\_outside, and press\\_button as follows.\n\n| | | | |\n| --- | --- | --- | --- |\n| Call | Return value | Insects in the machine | Types of insects in the machine |\n| | | $\\{\\}$ | $[]$ |\n| move\\_inside(0) | | $\\{0\\}$ | $[5]$ |\n| press\\_button() | $1$ | $\\{0\\}$ | $[5]$ |\n| move\\_inside(1) | | $\\{0, 1\\}$ | $[5, 8]$ |\n| press\\_button() | $1$ | $\\{0, 1\\}$ | $[5, 8]$ |\n| move\\_inside(3) | | $\\{0, 1, 3\\}$ | $[5, 8, 5]$ |\n| press\\_button() | $2$ | $\\{0, 1, 3\\}$ | $[5, 8, 5]$ |\n| move\\_inside(2) | | $\\{0, 1, 2, 3\\}$ | $[5, 8, 9, 5]$ |\n| move\\_inside(4) | | $\\{0, 1, 2, 3, 4\\}$ | $[5, 8, 9, 5, 9]$ |\n| move\\_inside(5) | | $\\{0, 1, 2, 3, 4, 5\\}$ | $[5, 8, 9, 5, 9, 9]$ |\n| press\\_button() | $3$ | $\\{0, 1, 2, 3, 4, 5\\}$ | $[5, 8, 9, 5, 9, 9]$ |\n| move\\_inside(5) | | $\\{0, 1, 2, 3, 4, 5\\}$ | $[5, 8, 9, 5, 9, 9]$ |\n| press\\_button() | $3$ | $\\{0, 1, 2, 3, 4, 5\\}$ | $[5, 8, 9, 5, 9, 9]$ |\n| move\\_outside(5) | | $\\{0, 1, 2, 3, 4\\}$ | $[5, 8, 9, 5, 9]$ |\n| press\\_button() | $2$ | $\\{0, 1, 2, 3, 4\\}$ | $[5, 8, 9, 5, 9]$ |\n\nAt this point, there is sufficient information to conclude that the cardinality of the rarest insect type is $1$. Therefore, the procedure min\\_cardinality should return $1$.\n\nIn this example, move\\_inside is called $7$ times, move\\_outside is called $1$ time, and press\\_button is called $6$ times.", "interactor_files": {"manager.cpp": "#include \"testlib.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\ninline FILE* openFile(const char* name, const char* mode) {\n FILE* file = fopen(name, mode);\n if (!file) {\n quitf(_fail, \"Could not open file '%s' with mode '%s'\", name, mode);\n }\n return file;\n}\n\ninline double roundToTwoDp(double score) {\n return round(score * 100) / 100;\n}\n\nstatic inline constexpr int kMaxQueries = 40000;\n\n// Insect types are compressed to colors in the range [0, N).\nstatic std::vector color;\nstatic std::vector in_box;\n\nstatic std::vector color_occurrences;\nstatic std::multiset max_occurrences;\n\nstatic std::vector op_counter(3, 0);\n\nint main(int argc, char *argv[]) {\n testlibMode = _checker;\n ouf.mode = _output;\n\n if (argc < 3) {\n quit(_fail, \"Insufficient number of args for manager of 'insects'\");\n }\n\n {\n // Keep alive on broken pipes\n struct sigaction sa;\n sa.sa_handler = SIG_IGN;\n sigaction(SIGPIPE, &sa, NULL);\n }\n\n // Must be in this order\n FILE *fout = openFile(argv[2], \"a\");\n FILE *fin = openFile(argv[1], \"r\");\n\n int N;\n int is_partial;\n assert(2 == scanf(\"%d %d\", &N, &is_partial));\n color.resize(N);\n in_box.assign(N, false);\n\n std::map type_to_color;\n for (int i = 0; i < N; ++i) {\n int Ti;\n assert(1 == scanf(\"%d\", &Ti));\n if (type_to_color.find(Ti) == type_to_color.end()) {\n int new_color = type_to_color.size();\n type_to_color[Ti] = new_color;\n max_occurrences.insert(0);\n }\n color[i] = type_to_color[Ti];\n }\n\n color_occurrences.assign(type_to_color.size(), 0);\n\n fprintf(fout, \"%d\\n\", N);\n fflush(fout);\n\n while (true) {\n {\n std::string in_secret = \"8\";\n char secret[100];\n if (fscanf(fin, \"%5s\", secret) != 1) {\n quit(_sv, \"Could not read secret (possibly, an unexpected termination\"\n \" of the program)\");\n }\n if (std::string(secret) != in_secret) {\n quit(_sv, \"Secret mismatch (possible tampering with the output)\");\n }\n }\n\n int op;\n if (fscanf(fin, \"%d\", &op) != 1) {\n quit(_fail, \"Could not read op.\");\n }\n\n if (op == 0 || op == 1) {\n ++op_counter[op];\n if (op_counter[op] > kMaxQueries) {\n quit(_sv, \"Too many queries.\");\n }\n\n int i;\n if (fscanf(fin, \"%d\", &i) != 1) {\n quit(_fail, \"Could not read query parameters.\");\n }\n if (i < 0 || i >= N) {\n quit(_sv, \"Invalid query parameters.\");\n }\n\n if (op == 0 && !in_box[i]) {\n in_box[i] = true;\n max_occurrences.erase(max_occurrences.find(color_occurrences[color[i]]));\n ++color_occurrences[color[i]];\n max_occurrences.insert(color_occurrences[color[i]]);\n }\n if (op == 1 && in_box[i]) {\n in_box[i] = false;\n max_occurrences.erase(max_occurrences.find(color_occurrences[color[i]]));\n --color_occurrences[color[i]];\n max_occurrences.insert(color_occurrences[color[i]]);\n }\n } else if (op == 2) {\n ++op_counter[2];\n if (op_counter[2] > kMaxQueries) {\n quit(_sv, \"Too many queries.\");\n }\n\n int frequency = *(max_occurrences.rbegin());\n fprintf(fout, \"%d\\n\", frequency);\n fflush(fout);\n } else if (op == 3) {\n int answer;\n if (fscanf(fin, \"%d\", &answer) != 1) {\n quit(_fail, \"Could not read answer.\");\n }\n\n int Q = *std::max_element(op_counter.begin(), op_counter.end());\n\n for (int i = 0; i < N; ++i) {\n if (!in_box[i]) {\n ++color_occurrences[color[i]];\n }\n }\n int correct = N;\n for (int frequency : color_occurrences) {\n correct = std::min(correct, frequency);\n }\n\n if (answer == correct) {\n if (is_partial == 0) {\n quit(_ok);\n } else if (is_partial == 1) {\n if (Q <= 3 * N) {\n quit(_ok);\n } else if (Q <= 6 * N) {\n quitp(roundToTwoDp(81.0 - pow(Q * 1.0 / N, 2.0) * 2.0 / 3.0) / 75.0);\n } else if (Q <= 20 * N) {\n quitp(roundToTwoDp(225.0 / (Q * 1.0 / N - 2.0)) / 75.0);\n } else {\n quit(_wa, \"Too many queries.\");\n }\n } else {\n assert(false);\n }\n } else {\n quit(_wa, \"Wrong answer.\");\n }\n } else {\n quit(_fail, \"Invalid value of op.\");\n }\n }\n}\n", "stub.cpp": "#include \"insects.h\"\n\n#include \n\n#include \n#include \n\nstatic inline constexpr int kMaxQueries = 40000;\n\nstatic std::vector op_counter;\n\nvoid move_inside(int i) {\n {\n std::string out_secret = \"8\";\n printf(\"%s\\n\", out_secret.c_str());\n }\n printf(\"0 %d\\n\", i);\n\n ++op_counter[0];\n if (op_counter[0] > kMaxQueries) {\n fflush(stdout);\n exit(0);\n }\n}\n\nvoid move_outside(int i) {\n {\n std::string out_secret = \"8\";\n printf(\"%s\\n\", out_secret.c_str());\n }\n printf(\"1 %d\\n\", i);\n\n ++op_counter[1];\n if (op_counter[1] > kMaxQueries) {\n fflush(stdout);\n exit(0);\n }\n}\n\nint press_button() {\n {\n std::string out_secret = \"8\";\n printf(\"%s\\n\", out_secret.c_str());\n }\n printf(\"2\\n\");\n fflush(stdout);\n\n int frequency;\n if (scanf(\"%d\", &frequency) != 1) {\n exit(0);\n }\n return frequency;\n}\n\nint main() {\n int N;\n assert(1 == scanf(\"%d\", &N));\n op_counter.resize(2);\n\n int answer = min_cardinality(N);\n {\n std::string out_secret = \"8\";\n printf(\"%s\\n\", out_secret.c_str());\n }\n printf(\"3 %d\\n\", answer);\n fflush(stdout);\n return 0;\n}\n", "insects.h": "void move_inside(int i);\nvoid move_outside(int i);\nint press_button();\nint min_cardinality(int N);\n", "testlib.h": "/* \n * It is strictly recommended to include \"testlib.h\" before any other include \n * in your code. In this case testlib overrides compiler specific \"random()\".\n *\n * If you can't compile your code and compiler outputs something about \n * ambiguous call of \"random_shuffle\", \"rand\" or \"srand\" it means that \n * you shouldn't use them. Use \"shuffle\", and \"rnd.next()\" instead of them\n * because these calls produce stable result for any C++ compiler. Read \n * sample generator sources for clarification.\n *\n * Please read the documentation for class \"random_t\" and use \"rnd\" instance in\n * generators. Probably, these sample calls will be usefull for you:\n * rnd.next(); rnd.next(100); rnd.next(1, 2); \n * rnd.next(3.14); rnd.next(\"[a-z]{1,100}\").\n *\n * Also read about wnext() to generate off-center random distribution.\n *\n * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker.\n */\n\n#ifndef _TESTLIB_H_\n#define _TESTLIB_H_\n\n/*\n * Copyright (c) 2005-2018\n */\n\n#define VERSION \"0.9.21\"\n\n/* \n * Mike Mirzayanov\n *\n * This material is provided \"as is\", with absolutely no warranty expressed\n * or implied. Any use is at your own risk.\n *\n * Permission to use or copy this software for any purpose is hereby granted \n * without fee, provided the above notices are retained on all copies.\n * Permission to modify the code and to distribute modified code is granted,\n * provided the above notices are retained, and a notice that the code was\n * modified is included with the above copyright notice.\n *\n */\n\n/*\n * Kian Mirjalali:\n *\n * Modified to be compatible with CMS & requirements for preparing IOI tasks\n *\n * * defined FOR_LINUX in order to force linux-based line endings in validators.\n *\n * * Changed the ordering of checker arguments\n * from \n * to \n *\n * * Added \"Security Violation\" as a new result type.\n *\n * * Changed checker quit behaviors to make it compliant with CMS.\n *\n * * The checker exit codes should always be 0 in CMS.\n *\n * * For partial scoring, forced quitp() functions to accept only scores in the range [0,1].\n * If the partial score is less than 1e-5, it becomes 1e-5, because 0 grades are considered wrong in CMS.\n * Grades in range [1e-5, 0.001) are printed exactly (to prevent rounding to zero).\n * Grades in [0.001, 1] are printed with 3 digits after decimal point.\n *\n * * Added the following utility functions/methods: \n * void InStream::readSecret(string secret)\n * void InStream::readGraderResult()\n * +supporting conversion of graderResult to CMS result\n * void quitp(double), quitp(int)\n * void registerChecker(string probName, argc, argv)\n * void readBothSecrets(string secret)\n * void readBothGraderResults()\n * void quit(TResult)\n * bool compareTokens(string a, string b, char separator=' ')\n * void compareRemainingLines(int lineNo=1)\n * void skip_ok()\n *\n */\n\n/*\n * Jonathan Irvin Gunawan:\n *\n * Further modified from changes by Kian Mirjalali for APIO 2021 and IOI 2022.\n *\n * * Print 4 digits after the decimal point for partial scoring.\n * This is to ensure that the grade multiplied by 100 still has at least 2\n * digits after the decimal point.\n *\n * * Rename verdict strings to match with CMS default verdict and the rules.\n * * \"Correct\" -> \"Output is correct\"\n * * \"Wrong Answer\" -> \"Output isn't correct\"\n * * \"Partially Correct\" -> \"Output is partially correct\"\n *\n * * Rename \"Security Violation\" to \"Protocol Violation\".\n * This change was recommended by ISC in IOI 2020.\n *\n * * Add an option to skip printing message when calling quit().\n * For some tasks (especially output-only), we might want to skip printing the\n * message to CMS since it might contain any characters that is submitted by\n * the contestant.\n *\n */\n\n\n/* NOTE: This file contains testlib library for C++.\n *\n * Check, using testlib running format:\n * check.exe [ [-appes]],\n * If result file is specified it will contain results.\n *\n * Validator, using testlib running format: \n * validator.exe < input.txt,\n * It will return non-zero exit code and writes message to standard output.\n *\n * Generator, using testlib running format: \n * gen.exe [parameter-1] [parameter-2] [... paramerter-n]\n * You can write generated test(s) into standard output or into the file(s).\n *\n * Interactor, using testlib running format: \n * interactor.exe [ [ [-appes]]],\n * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],\n * can be judged by checker later), reads program output from ouf (mapped to stdin),\n * writes output to program via stdout (use cout, printf, etc).\n */\n\nconst char* latestFeatures[] = {\n \"Fixed stringstream repeated usage issue\",\n \"Fixed compilation in g++ (for std=c++03)\",\n \"Batch of println functions (support collections, iterator ranges)\",\n \"Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation\",\n \"Allow any whitespace in readInts-like functions for non-validators\",\n \"Ignore 4+ command line arguments ifdef EJUDGE\",\n \"Speed up of vtos\",\n \"Show line number in validators in case of incorrect format\",\n \"Truncate huge checker/validator/interactor message\",\n \"Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type\",\n \"Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type\",\n \"Fixed compilation in VS 2015+\",\n \"Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines\",\n \"Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals\",\n \"Introduced split/tokenize functions to separate string by given char\",\n \"Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters\",\n \"Supported --testOverviewLogFileName for validator: bounds hits + features\",\n \"Fixed UB (sequence points) in random_t\",\n \"POINTS_EXIT_CODE returned back to 7 (instead of 0)\",\n \"Removed disable buffers for interactive problems, because it works unexpectedly in wine\",\n \"InStream over string: constructor of InStream from base InStream to inherit policies and std::string\",\n \"Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \\\"[n=%d,m=%d]\\\", n, m)\",\n \"Fixed incorrect interval parsing in patterns\",\n \"Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)\",\n \"Introduced disableFinalizeGuard() to switch off finalization checkings\",\n \"Use join() functions to format a range of items as a single string (separated by spaces or other separators)\",\n \"Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors\",\n \"Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7\",\n \"Fixed bug with nan in stringToDouble\", \n \"Fixed issue around overloads for size_t on x64\", \n \"Added attribute 'points' to the XML output in case of result=_points\", \n \"Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14\", \n \"Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading\", \n \"Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()\", \n \"Manual buffer in InStreams, some IO speed improvements\", \n \"Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true\", \n \"Introduced guard against missed quitf() in checker or readEof() in validators\", \n \"Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers\", \n \"Supported registerInteraction(argc, argv)\", \n \"Print checker message to the stderr instead of stdout\", \n \"Supported TResult _points to output calculated score, use quitp(...) functions\", \n \"Fixed to be compilable on Mac\", \n \"PC_BASE_EXIT_CODE=50 in case of defined TESTSYS\",\n \"Fixed issues 19-21, added __attribute__ format printf\", \n \"Some bug fixes\", \n \"ouf.readInt(1, 100) and similar calls return WA\", \n \"Modified random_t to avoid integer overflow\", \n \"Truncated checker output [patch by Stepan Gatilov]\", \n \"Renamed class random -> class random_t\", \n \"Supported name parameter for read-and-validation methods, like readInt(1, 2, \\\"n\\\")\", \n \"Fixed bug in readDouble()\", \n \"Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()\", \n \"Supported \\\"partially correct\\\", example: quitf(_pc(13), \\\"result=%d\\\", result)\", \n \"Added shuffle(begin, end), use it instead of random_shuffle(begin, end)\", \n \"Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode\", \n \"Package extended with samples of generators and validators\", \n \"Written the documentation for classes and public methods in testlib.h\",\n \"Implemented random routine to support generators, use registerGen() to switch it on\",\n \"Implemented strict mode to validate tests, use registerValidation() to switch it on\",\n \"Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output\",\n \"Added InStream::readLong() and removed InStream::readLongint()\",\n \"Now no footer added to each report by default (use directive FOOTER to switch on)\",\n \"Now every checker has a name, use setName(const char* format, ...) to set it\",\n \"Now it is compatible with TTS (by Kittens Computing)\",\n \"Added \\'ensure(condition, message = \\\"\\\")\\' feature, it works like assert()\",\n \"Fixed compatibility with MS C++ 7.1\",\n \"Added footer with exit code information\",\n \"Added compatibility with EJUDGE (compile with EJUDGE directive)\",\n \"Added compatibility with Contester (compile with CONTESTER directive)\"\n };\n\n#define FOR_LINUX\n\n#ifdef _MSC_VER\n#define _CRT_SECURE_NO_DEPRECATE\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_NO_VA_START_VALIDATION\n#endif\n\n/* Overrides random() for Borland C++. */\n#define random __random_deprecated\n#include \n#include \n#include \n#include \n#undef random\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ || __CYGWIN__ )\n# if !defined(_MSC_VER) || _MSC_VER>1400\n# define NOMINMAX 1\n# include \n# else\n# define WORD unsigned short\n# include \n# endif\n# include \n# define ON_WINDOWS\n# if defined(_MSC_VER) && _MSC_VER>1400\n# pragma warning( disable : 4127 )\n# pragma warning( disable : 4146 )\n# pragma warning( disable : 4458 )\n# endif\n#else\n# define WORD unsigned short\n# include \n#endif\n\n#if defined(FOR_WINDOWS) && defined(FOR_LINUX)\n#error Only one target system is allowed\n#endif\n\n#ifndef LLONG_MIN\n#define LLONG_MIN (-9223372036854775807LL - 1)\n#endif\n\n#ifndef ULLONG_MAX\n#define ULLONG_MAX (18446744073709551615)\n#endif\n\n#define LF ((char)10)\n#define CR ((char)13)\n#define TAB ((char)9)\n#define SPACE ((char)' ')\n#define EOFC (255)\n\n#ifndef OK_EXIT_CODE\n# ifdef CONTESTER\n# define OK_EXIT_CODE 0xAC\n# else\n# define OK_EXIT_CODE 0\n# endif\n#endif\n\n#ifndef WA_EXIT_CODE\n# ifdef EJUDGE\n# define WA_EXIT_CODE 5\n# elif defined(CONTESTER)\n# define WA_EXIT_CODE 0xAB\n# else\n# define WA_EXIT_CODE 1\n# endif\n#endif\n\n#ifndef PE_EXIT_CODE\n# ifdef EJUDGE\n# define PE_EXIT_CODE 4\n# elif defined(CONTESTER)\n# define PE_EXIT_CODE 0xAA\n# else\n# define PE_EXIT_CODE 2\n# endif\n#endif\n\n#ifndef FAIL_EXIT_CODE\n# ifdef EJUDGE\n# define FAIL_EXIT_CODE 6\n# elif defined(CONTESTER)\n# define FAIL_EXIT_CODE 0xA3\n# else\n# define FAIL_EXIT_CODE 3\n# endif\n#endif\n\n#ifndef DIRT_EXIT_CODE\n# ifdef EJUDGE\n# define DIRT_EXIT_CODE 6\n# else\n# define DIRT_EXIT_CODE 4\n# endif\n#endif\n\n#ifndef POINTS_EXIT_CODE\n# define POINTS_EXIT_CODE 7\n#endif\n\n#ifndef UNEXPECTED_EOF_EXIT_CODE\n# define UNEXPECTED_EOF_EXIT_CODE 8\n#endif\n\n#ifndef SV_EXIT_CODE\n# define SV_EXIT_CODE 20\n#endif\n\n#ifndef PC_BASE_EXIT_CODE\n# ifdef TESTSYS\n# define PC_BASE_EXIT_CODE 50\n# else\n# define PC_BASE_EXIT_CODE 0\n# endif\n#endif\n\n#ifdef __GNUC__\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))\n#else\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]\n#endif\n\n#ifdef ON_WINDOWS\n#define I64 \"%I64d\"\n#define U64 \"%I64u\"\n#else\n#define I64 \"%lld\"\n#define U64 \"%llu\"\n#endif\n\n#ifdef _MSC_VER\n# define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n# define NORETURN __attribute__ ((noreturn))\n#else\n# define NORETURN\n#endif\n \nstatic char __testlib_format_buffer[16777216];\nstatic int __testlib_format_buffer_usage_count = 0;\n\n#define FMT_TO_RESULT(fmt, cstr, result) std::string result; \\\n if (__testlib_format_buffer_usage_count != 0) \\\n __testlib_fail(\"FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0\"); \\\n __testlib_format_buffer_usage_count++; \\\n va_list ap; \\\n va_start(ap, fmt); \\\n vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \\\n va_end(ap); \\\n __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \\\n result = std::string(__testlib_format_buffer); \\\n __testlib_format_buffer_usage_count--; \\\n\nconst long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;\n\nNORETURN static void __testlib_fail(const std::string& message);\n\ntemplate\nstatic inline T __testlib_abs(const T& x)\n{\n return x > 0 ? x : -x;\n}\n\ntemplate\nstatic inline T __testlib_min(const T& a, const T& b)\n{\n return a < b ? a : b;\n}\n\ntemplate\nstatic inline T __testlib_max(const T& a, const T& b)\n{\n return a > b ? a : b;\n}\n\nstatic bool __testlib_prelimIsNaN(double r)\n{\n volatile double ra = r;\n#ifndef __BORLANDC__\n return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);\n#else\n return std::_isnan(ra);\n#endif\n}\n\nstatic std::string removeDoubleTrailingZeroes(std::string value)\n{\n while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)\n value = value.substr(0, value.length() - 1);\n return value + '0';\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nstd::string format(const char* fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt, result);\n return result;\n}\n\nstd::string format(const std::string fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt.c_str(), result);\n return result;\n}\n\nstatic std::string __testlib_part(const std::string& s);\n\nstatic bool __testlib_isNaN(double r)\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n volatile double ra = r;\n long long llr1, llr2;\n std::memcpy((void*)&llr1, (void*)&ra, sizeof(double)); \n ra = -ra;\n std::memcpy((void*)&llr2, (void*)&ra, sizeof(double)); \n long long llnan = 0xFFF8000000000000LL;\n return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;\n}\n\nstatic double __testlib_nan()\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n#ifndef NAN\n long long llnan = 0xFFF8000000000000LL;\n double nan;\n std::memcpy(&nan, &llnan, sizeof(double));\n return nan;\n#else\n return NAN;\n#endif\n}\n\nstatic bool __testlib_isInfinite(double r)\n{\n volatile double ra = r;\n return (ra > 1E300 || ra < -1E300);\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)\n{\n if (__testlib_isNaN(expected))\n {\n return __testlib_isNaN(result);\n }\n else \n if (__testlib_isInfinite(expected))\n {\n if (expected > 0)\n {\n return result > 0 && __testlib_isInfinite(result);\n }\n else\n {\n return result < 0 && __testlib_isInfinite(result);\n }\n }\n else \n if (__testlib_isNaN(result) || __testlib_isInfinite(result))\n {\n return false;\n }\n else \n if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)\n {\n return true;\n }\n else\n {\n double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n return result + 1E-15 >= minv && result <= maxv + 1E-15;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline double doubleDelta(double expected, double result)\n{\n double absolute = __testlib_abs(result - expected);\n \n if (__testlib_abs(expected) > 1E-9)\n {\n double relative = __testlib_abs(absolute / expected);\n return __testlib_min(absolute, relative);\n }\n else\n return absolute;\n}\n\n#if !defined(_MSC_VER) || _MSC_VER<1900\n#ifndef _fileno\n#define _fileno(_stream) ((_stream)->_file)\n#endif\n#endif\n\n#ifndef O_BINARY\nstatic void __testlib_set_binary(\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\n std::FILE* file\n)\n#else\nstatic void __testlib_set_binary(std::FILE* file)\n#endif\n{\n#ifdef O_BINARY\n if (NULL != file)\n {\n#ifndef __BORLANDC__\n _setmode(_fileno(file), O_BINARY);\n#else\n setmode(fileno(file), O_BINARY);\n#endif\n }\n#endif\n}\n\n/*\n * Very simple regex-like pattern.\n * It used for two purposes: validation and generation.\n * \n * For example, pattern(\"[a-z]{1,5}\").next(rnd) will return\n * random string from lowercase latin letters with length \n * from 1 to 5. It is easier to call rnd.next(\"[a-z]{1,5}\") \n * for the same effect. \n * \n * Another samples:\n * \"mike|john\" will generate (match) \"mike\" or \"john\";\n * \"-?[1-9][0-9]{0,3}\" will generate (match) non-zero integers from -9999 to 9999;\n * \"id-([ac]|b{2})\" will generate (match) \"id-a\", \"id-bb\", \"id-c\";\n * \"[^0-9]*\" will match sequences (empty or non-empty) without digits, you can't \n * use it for generations.\n *\n * You can't use pattern for generation if it contains meta-symbol '*'. Also it\n * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].\n *\n * For matching very simple greedy algorithm is used. For example, pattern\n * \"[0-9]?1\" will not match \"1\", because of greedy nature of matching.\n * Alternations (meta-symbols \"|\") are processed with brute-force algorithm, so \n * do not use many alternations in one expression.\n *\n * If you want to use one expression many times it is better to compile it into\n * a single pattern like \"pattern p(\"[a-z]+\")\". Later you can use \n * \"p.matches(std::string s)\" or \"p.next(random_t& rd)\" to check matching or generate\n * new string by pattern.\n * \n * Simpler way to read token and check it for pattern matching is \"inf.readToken(\"[a-z]+\")\".\n */\nclass random_t;\n\nclass pattern\n{\npublic:\n /* Create pattern instance by string. */\n pattern(std::string s);\n /* Generate new string by pattern and given random_t. */\n std::string next(random_t& rnd) const;\n /* Checks if given string match the pattern. */\n bool matches(const std::string& s) const;\n /* Returns source string of the pattern. */\n std::string src() const;\nprivate:\n bool matches(const std::string& s, size_t pos) const;\n\n std::string s;\n std::vector children;\n std::vector chars;\n int from;\n int to;\n};\n\n/* \n * Use random_t instances to generate random values. It is preffered\n * way to use randoms instead of rand() function or self-written \n * randoms.\n *\n * Testlib defines global variable \"rnd\" of random_t class.\n * Use registerGen(argc, argv, 1) to setup random_t seed be command\n * line (to use latest random generator version).\n *\n * Random generates uniformly distributed values if another strategy is\n * not specified explicitly.\n */\nclass random_t\n{\nprivate:\n unsigned long long seed;\n static const unsigned long long multiplier;\n static const unsigned long long addend;\n static const unsigned long long mask;\n static const int lim;\n\n long long nextBits(int bits) \n {\n if (bits <= 48)\n {\n seed = (seed * multiplier + addend) & mask;\n return (long long)(seed >> (48 - bits));\n }\n else\n {\n if (bits > 63)\n __testlib_fail(\"random_t::nextBits(int bits): n must be less than 64\");\n\n int lowerBitCount = (random_t::version == 0 ? 31 : 32);\n \n long long left = (nextBits(31) << 32);\n long long right = nextBits(lowerBitCount);\n \n return left ^ right;\n }\n }\n\npublic:\n static int version;\n\n /* New random_t with fixed seed. */\n random_t()\n : seed(3905348978240129619LL)\n {\n }\n\n /* Sets seed by command line. */\n void setSeed(int argc, char* argv[])\n {\n random_t p;\n\n seed = 3905348978240129619LL;\n for (int i = 1; i < argc; i++)\n {\n std::size_t le = std::strlen(argv[i]);\n for (std::size_t j = 0; j < le; j++)\n seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;\n seed += multiplier / addend;\n }\n\n seed = seed & mask;\n }\n\n /* Sets seed by given value. */ \n void setSeed(long long _seed)\n {\n _seed = (_seed ^ multiplier) & mask;\n seed = _seed;\n }\n\n#ifndef __BORLANDC__\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(const std::string& ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#else\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(std::string ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#endif\n\n /* Random value in range [0, n-1]. */\n int next(int n)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(int n): n must be positive\");\n\n if ((n & -n) == n) // n is a power of 2\n return (int)((n * (long long)nextBits(31)) >> 31);\n\n const long long limit = INT_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(31);\n } while (bits >= limit);\n\n return int(bits % n);\n }\n\n /* Random value in range [0, n-1]. */\n unsigned int next(unsigned int n)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::next(unsigned int n): n must be less INT_MAX\");\n return (unsigned int)next(int(n));\n }\n\n /* Random value in range [0, n-1]. */\n long long next(long long n) \n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(long long n): n must be positive\");\n\n const long long limit = __TESTLIB_LONGLONG_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(63);\n } while (bits >= limit);\n\n return bits % n;\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long long next(unsigned long long n)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long long n): n must be less LONGLONG_MAX\");\n return (unsigned long long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n long next(long n)\n {\n return (long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long next(unsigned long n)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long n): n must be less LONG_MAX\");\n return (unsigned long)next((unsigned long long)(n));\n }\n\n /* Returns random value in range [from,to]. */\n int next(int from, int to)\n {\n return int(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n unsigned int next(unsigned int from, unsigned int to)\n {\n return (unsigned int)(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n long long next(long long from, long long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long long next(unsigned long long from, unsigned long long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n long next(long from, long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long next(unsigned long from, unsigned long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long from, unsigned long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Random double value in range [0, 1). */\n double next() \n {\n long long left = ((long long)(nextBits(26)) << 27);\n long long right = nextBits(27);\n return (double)(left + right) / (double)(1LL << 53);\n }\n\n /* Random double value in range [0, n). */\n double next(double n)\n {\n return n * next();\n }\n\n /* Random double value in range [from, to). */\n double next(double from, double to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(double from, double to): from can't not exceed to\");\n return next(to - from) + from;\n }\n\n /* Returns random element from container. */\n template \n typename Container::value_type any(const Container& c)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Container& c): c.size() must be positive\");\n return *(c.begin() + next(size));\n }\n\n /* Returns random element from iterator range. */\n template \n typename Iter::value_type any(const Iter& begin, const Iter& end)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end): range must have positive length\");\n return *(begin + next(size));\n }\n\n /* Random string value by given pattern (see pattern documentation). */\n#ifdef __GNUC__\n __attribute__ ((format (printf, 2, 3)))\n#endif\n std::string next(const char* format, ...)\n {\n FMT_TO_RESULT(format, format, ptrn);\n return next(ptrn);\n }\n\n /* \n * Weighted next. If type == 0 than it is usual \"next()\".\n *\n * If type = 1, than it returns \"max(next(), next())\"\n * (the number of \"max\" functions equals to \"type\").\n *\n * If type < 0, than \"max\" function replaces with \"min\".\n */\n int wnext(int n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(int n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n int result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));\n\n return int(n * p);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n long long wnext(long long n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(long long n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n long long result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(int type)\n {\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return p;\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(double n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(double n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return n * result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return n * p;\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned int wnext(unsigned int n, int type)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::wnext(unsigned int n, int type): n must be less INT_MAX\");\n return (unsigned int)wnext(int(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long long wnext(unsigned long long n, int type)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX\");\n\n return (unsigned long long)wnext((long long)(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n long wnext(long n, int type)\n {\n return (long)wnext((long long)(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long wnext(unsigned long n, int type)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long n, int type): n must be less LONG_MAX\");\n\n return (unsigned long)wnext((unsigned long long)(n), type);\n }\n\n /* Returns weighted random value in range [from, to]. */\n int wnext(int from, int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(int from, int to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n int wnext(unsigned int from, unsigned int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to\");\n return int(wnext(to - from + 1, type) + from);\n }\n \n /* Returns weighted random value in range [from, to]. */\n long long wnext(long long from, long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long long from, long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long long wnext(unsigned long long from, unsigned long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n long wnext(long from, long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long from, long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long wnext(unsigned long from, unsigned long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random double value in range [from, to). */\n double wnext(double from, double to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(double from, double to, int type): from can't not exceed to\");\n return wnext(to - from, type) + from;\n }\n\n /* Returns weighted random element from container. */\n template \n typename Container::value_type wany(const Container& c, int type)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::wany(const Container& c, int type): c.size() must be positive\");\n return *(c.begin() + wnext(size, type));\n }\n\n /* Returns weighted random element from iterator range. */\n template \n typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length\");\n return *(begin + wnext(size, type));\n }\n\n template\n std::vector perm(T size, E first)\n {\n if (size <= 0)\n __testlib_fail(\"random_t::perm(T size, E first = 0): size must be positive\");\n std::vector p(size);\n for (T i = 0; i < size; i++)\n p[i] = first + i;\n if (size > 1)\n for (T i = 1; i < size; i++)\n std::swap(p[i], p[next(i + 1)]);\n return p;\n }\n\n template\n std::vector perm(T size)\n {\n return perm(size, T(0));\n }\n};\n\nconst int random_t::lim = 25;\nconst unsigned long long random_t::multiplier = 0x5DEECE66DLL;\nconst unsigned long long random_t::addend = 0xBLL;\nconst unsigned long long random_t::mask = (1LL << 48) - 1;\nint random_t::version = -1;\n\n/* Pattern implementation */\nbool pattern::matches(const std::string& s) const\n{\n return matches(s, 0);\n}\n\nstatic bool __pattern_isSlash(const std::string& s, size_t pos)\n{\n return s[pos] == '\\\\';\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)\n{\n if (pos >= s.length())\n return false;\n\n int slashes = 0;\n\n int before = int(pos) - 1;\n while (before >= 0 && s[before] == '\\\\')\n before--, slashes++;\n\n return slashes % 2 == 0 && s[pos] == value;\n}\n\nstatic char __pattern_getChar(const std::string& s, size_t& pos)\n{\n if (__pattern_isSlash(s, pos))\n pos += 2;\n else\n pos++;\n\n return s[pos - 1];\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector chars)\n{\n int result = 0;\n\n while (pos < s.length())\n {\n char c = s[pos++];\n if (!std::binary_search(chars.begin(), chars.end(), c))\n break;\n else\n result++;\n }\n\n return result;\n}\n\nstd::string pattern::src() const\n{\n return s;\n}\n\nbool pattern::matches(const std::string& s, size_t pos) const\n{\n std::string result;\n\n if (to > 0)\n {\n int size = __pattern_greedyMatch(s, pos, chars);\n if (size < from)\n return false;\n if (size > to)\n size = to;\n pos += size;\n }\n\n if (children.size() > 0)\n {\n for (size_t child = 0; child < children.size(); child++)\n if (children[child].matches(s, pos))\n return true;\n return false;\n }\n else\n return pos == s.length();\n}\n\nstd::string pattern::next(random_t& rnd) const\n{\n std::string result;\n result.reserve(20);\n\n if (to == INT_MAX)\n __testlib_fail(\"pattern::next(random_t& rnd): can't process character '*' for generation\");\n\n if (to > 0)\n {\n int count = rnd.next(to - from + 1) + from;\n for (int i = 0; i < count; i++)\n result += chars[rnd.next(int(chars.size()))];\n }\n\n if (children.size() > 0)\n {\n int child = rnd.next(int(children.size()));\n result += children[child].next(rnd);\n }\n\n return result;\n}\n\nstatic void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)\n{\n if (pos >= s.length())\n {\n from = to = 1;\n return;\n }\n \n if (__pattern_isCommandChar(s, pos, '{'))\n {\n std::vector parts;\n std::string part;\n\n pos++;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))\n {\n if (__pattern_isCommandChar(s, pos, ','))\n parts.push_back(part), part = \"\", pos++;\n else\n part += __pattern_getChar(s, pos);\n }\n\n if (part != \"\")\n parts.push_back(part);\n\n if (!__pattern_isCommandChar(s, pos, '}'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (parts.size() < 1 || parts.size() > 2)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector numbers;\n\n for (size_t i = 0; i < parts.size(); i++)\n {\n if (parts[i].length() == 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n int number;\n if (std::sscanf(parts[i].c_str(), \"%d\", &number) != 1)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n numbers.push_back(number);\n }\n\n if (numbers.size() == 1)\n from = to = numbers[0];\n else\n from = numbers[0], to = numbers[1];\n\n if (from > to)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n }\n else\n {\n if (__pattern_isCommandChar(s, pos, '?'))\n {\n from = 0, to = 1, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '*'))\n {\n from = 0, to = INT_MAX, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '+'))\n {\n from = 1, to = INT_MAX, pos++;\n return;\n }\n \n from = to = 1;\n }\n}\n\nstatic std::vector __pattern_scanCharSet(const std::string& s, size_t& pos)\n{\n if (pos >= s.length())\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector result;\n\n if (__pattern_isCommandChar(s, pos, '['))\n {\n pos++;\n bool negative = __pattern_isCommandChar(s, pos, '^');\n\n char prev = 0;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))\n {\n if (__pattern_isCommandChar(s, pos, '-') && prev != 0)\n {\n pos++;\n\n if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']'))\n {\n result.push_back(prev);\n prev = '-';\n continue;\n }\n\n char next = __pattern_getChar(s, pos);\n if (prev > next)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n for (char c = prev; c != next; c++)\n result.push_back(c);\n result.push_back(next);\n\n prev = 0;\n }\n else\n {\n if (prev != 0)\n result.push_back(prev);\n prev = __pattern_getChar(s, pos);\n }\n }\n\n if (prev != 0)\n result.push_back(prev);\n\n if (!__pattern_isCommandChar(s, pos, ']'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (negative)\n {\n std::sort(result.begin(), result.end());\n std::vector actuals;\n for (int code = 0; code < 255; code++)\n {\n char c = char(code);\n if (!std::binary_search(result.begin(), result.end(), c))\n actuals.push_back(c);\n }\n result = actuals;\n }\n\n std::sort(result.begin(), result.end());\n }\n else\n result.push_back(__pattern_getChar(s, pos));\n\n return result;\n}\n\npattern::pattern(std::string s): s(s), from(0), to(0)\n{\n std::string t;\n for (size_t i = 0; i < s.length(); i++)\n if (!__pattern_isCommandChar(s, i, ' '))\n t += s[i];\n s = t;\n\n int opened = 0;\n int firstClose = -1;\n std::vector seps;\n\n for (size_t i = 0; i < s.length(); i++)\n {\n if (__pattern_isCommandChar(s, i, '('))\n {\n opened++;\n continue;\n }\n\n if (__pattern_isCommandChar(s, i, ')'))\n {\n opened--;\n if (opened == 0 && firstClose == -1)\n firstClose = int(i);\n continue;\n }\n \n if (opened < 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (__pattern_isCommandChar(s, i, '|') && opened == 0)\n seps.push_back(int(i));\n }\n\n if (opened != 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (seps.size() == 0 && firstClose + 1 == (int)s.length() \n && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))\n {\n children.push_back(pattern(s.substr(1, s.length() - 2)));\n }\n else\n {\n if (seps.size() > 0)\n {\n seps.push_back(int(s.length()));\n int last = 0;\n\n for (size_t i = 0; i < seps.size(); i++)\n {\n children.push_back(pattern(s.substr(last, seps[i] - last)));\n last = seps[i] + 1;\n }\n }\n else\n {\n size_t pos = 0;\n chars = __pattern_scanCharSet(s, pos);\n __pattern_scanCounts(s, pos, from, to);\n if (pos < s.length())\n children.push_back(pattern(s.substr(pos)));\n }\n }\n}\n/* End of pattern implementation */\n\ntemplate \ninline bool isEof(C c)\n{\n return c == EOFC;\n}\n\ntemplate \ninline bool isEoln(C c)\n{\n return (c == LF || c == CR);\n}\n\ntemplate\ninline bool isBlanks(C c)\n{\n return (c == LF || c == CR || c == SPACE || c == TAB);\n}\n\nenum TMode\n{\n _input, _output, _answer\n};\n\n/* Outcomes 6-15 are reserved for future use. */\nenum TResult\n{\n _ok = 0,\n _wa = 1,\n _pe = 2,\n _fail = 3,\n _dirt = 4,\n _points = 5,\n _unexpected_eof = 8,\n _sv = 10,\n _partially = 16\n};\n\nenum TTestlibMode\n{\n _unknown, _checker, _validator, _generator, _interactor\n};\n\n#define _pc(exitCode) (TResult(_partially + (exitCode)))\n\n/* Outcomes 6-15 are reserved for future use. */\nconst std::string outcomes[] = {\n \"accepted\",\n \"wrong-answer\",\n \"presentation-error\",\n \"fail\",\n \"fail\",\n#ifndef PCMS2\n \"points\",\n#else\n \"relative-scoring\",\n#endif\n \"reserved\",\n \"reserved\",\n \"unexpected-eof\",\n \"reserved\",\n \"security-violation\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"partially-correct\"\n};\n\nclass InputStreamReader\n{\npublic:\n virtual int curChar() = 0; \n virtual int nextChar() = 0; \n virtual void skipChar() = 0;\n virtual void unreadChar(int c) = 0;\n virtual std::string getName() = 0;\n virtual bool eof() = 0;\n virtual void close() = 0;\n virtual int getLine() = 0;\n virtual ~InputStreamReader() = 0;\n};\n\nInputStreamReader::~InputStreamReader()\n{\n // No operations.\n}\n\nclass StringInputStreamReader: public InputStreamReader\n{\nprivate:\n std::string s;\n size_t pos;\n\npublic:\n StringInputStreamReader(const std::string& content): s(content), pos(0)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (pos >= s.length())\n return EOFC;\n else\n return s[pos];\n }\n\n int nextChar()\n {\n if (pos >= s.length())\n {\n pos++;\n return EOFC;\n }\n else\n return s[pos++];\n }\n\n void skipChar()\n {\n pos++;\n }\n\n void unreadChar(int c)\n { \n if (pos == 0)\n __testlib_fail(\"FileFileInputStreamReader::unreadChar(int): pos == 0.\");\n pos--;\n if (pos < s.length())\n s[pos] = char(c);\n }\n\n std::string getName()\n {\n return __testlib_part(s);\n }\n\n int getLine()\n {\n return -1;\n }\n\n bool eof()\n {\n return pos >= s.length();\n }\n\n void close()\n {\n // No operations.\n }\n};\n\nclass FileInputStreamReader: public InputStreamReader\n{\nprivate:\n std::FILE* file;\n std::string name;\n int line;\n std::vector undoChars;\n\n inline int postprocessGetc(int getcResult)\n {\n if (getcResult != EOF)\n return getcResult;\n else\n return EOFC;\n }\n\n int getc(FILE* file)\n {\n int c;\n if (undoChars.empty())\n c = ::getc(file);\n else\n {\n c = undoChars.back();\n undoChars.pop_back();\n }\n\n if (c == LF)\n line++;\n return c;\n }\n\n int ungetc(int c/*, FILE* file*/)\n {\n if (c == LF)\n line--;\n undoChars.push_back(c);\n return c;\n }\n\npublic:\n FileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (feof(file))\n return EOFC;\n else\n {\n int c = getc(file);\n ungetc(c/*, file*/);\n return postprocessGetc(c);\n }\n }\n\n int nextChar()\n {\n if (feof(file))\n return EOFC;\n else\n return postprocessGetc(getc(file));\n }\n\n void skipChar()\n {\n getc(file);\n }\n\n void unreadChar(int c)\n { \n ungetc(c/*, file*/);\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n\n bool eof()\n {\n if (NULL == file || feof(file))\n return true;\n else\n {\n int c = nextChar();\n if (c == EOFC || (c == EOF && feof(file)))\n return true;\n unreadChar(c);\n return false;\n }\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nclass BufferedFileInputStreamReader: public InputStreamReader\n{\nprivate:\n static const size_t BUFFER_SIZE;\n static const size_t MAX_UNREAD_COUNT; \n \n std::FILE* file;\n char* buffer;\n bool* isEof;\n int bufferPos;\n size_t bufferSize;\n\n std::string name;\n int line;\n\n bool refill()\n {\n if (NULL == file)\n __testlib_fail(\"BufferedFileInputStreamReader: file == NULL (\" + getName() + \")\");\n\n if (bufferPos >= int(bufferSize))\n {\n size_t readSize = fread(\n buffer + MAX_UNREAD_COUNT,\n 1,\n BUFFER_SIZE - MAX_UNREAD_COUNT,\n file\n );\n\n if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT\n && ferror(file))\n __testlib_fail(\"BufferedFileInputStreamReader: unable to read (\" + getName() + \")\");\n\n bufferSize = MAX_UNREAD_COUNT + readSize;\n bufferPos = int(MAX_UNREAD_COUNT);\n std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);\n\n return readSize > 0;\n }\n else\n return true;\n }\n\n char increment()\n {\n char c;\n if ((c = buffer[bufferPos++]) == LF)\n line++;\n return c;\n }\n\npublic:\n BufferedFileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n buffer = new char[BUFFER_SIZE];\n isEof = new bool[BUFFER_SIZE];\n bufferSize = MAX_UNREAD_COUNT;\n bufferPos = int(MAX_UNREAD_COUNT);\n }\n\n ~BufferedFileInputStreamReader()\n {\n if (NULL != buffer)\n {\n delete[] buffer;\n buffer = NULL;\n }\n if (NULL != isEof)\n {\n delete[] isEof;\n isEof = NULL;\n }\n }\n\n int curChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : buffer[bufferPos];\n }\n\n int nextChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : increment();\n }\n\n void skipChar()\n {\n increment();\n }\n\n void unreadChar(int c)\n { \n bufferPos--;\n if (bufferPos < 0)\n __testlib_fail(\"BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0\");\n isEof[bufferPos] = (c == EOFC);\n buffer[bufferPos] = char(c);\n if (c == LF)\n line--;\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n \n bool eof()\n {\n return !refill() || EOFC == curChar();\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nconst size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;\nconst size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2; \n\n/*\n * Streams to be used for reading data in checkers or validators.\n * Each read*() method moves pointer to the next character after the\n * read value.\n */\nstruct InStream\n{\n /* Do not use them. */\n InStream();\n ~InStream();\n\n /* Wrap std::string with InStream. */\n InStream(const InStream& baseStream, std::string content);\n\n InputStreamReader* reader;\n int lastLine;\n\n std::string name;\n TMode mode;\n bool opened;\n bool stdfile;\n bool strict;\n\n int wordReserveSize;\n std::string _tmpReadToken;\n\n int readManyIteration;\n size_t maxFileSize;\n size_t maxTokenLength;\n size_t maxMessageLength;\n bool printMessage;\n\n void init(std::string fileName, TMode mode);\n void init(std::FILE* f, TMode mode);\n\n /* Moves stream pointer to the first non-white-space character or EOF. */ \n void skipBlanks();\n \n /* Returns current character in the stream. Doesn't remove it from stream. */\n char curChar();\n /* Moves stream pointer one character forward. */\n void skipChar();\n /* Returns current character and moves pointer one character forward. */\n char nextChar();\n \n /* Returns current character and moves pointer one character forward. */\n char readChar();\n /* As \"readChar()\" but ensures that the result is equal to given parameter. */\n char readChar(char c);\n /* As \"readChar()\" but ensures that the result is equal to the space (code=32). */\n char readSpace();\n /* Puts back the character into the stream. */\n void unreadChar(char c);\n\n /* Reopens stream, you should not use it. */\n void reset(std::FILE* file = NULL);\n /* Checks that current position is EOF. If not it doesn't move stream pointer. */\n bool eof();\n /* Moves pointer to the first non-white-space character and calls \"eof()\". */\n bool seekEof();\n\n /* \n * Checks that current position contains EOLN. \n * If not it doesn't move stream pointer. \n * In strict mode expects \"#13#10\" for windows or \"#10\" for other platforms.\n */\n bool eoln();\n /* Moves pointer to the first non-space and non-tab character and calls \"eoln()\". */\n bool seekEoln();\n\n /* Moves stream pointer to the first character of the next line (if exists). */\n void nextLine();\n\n /* \n * Reads new token. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n std::string readWord();\n /* The same as \"readWord()\", it is preffered to use \"readToken()\". */\n std::string readToken();\n /* The same as \"readWord()\", but ensures that token matches to given pattern. */\n std::string readWord(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readWord(const pattern& p, const std::string& variableName = \"\");\n std::vector readWords(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readWords(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n /* The same as \"readToken()\", but ensures that token matches to given pattern. */\n std::string readToken(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readToken(const pattern& p, const std::string& variableName = \"\");\n std::vector readTokens(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readTokens(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n\n void readWordTo(std::string& result);\n void readWordTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n void readTokenTo(std::string& result);\n void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads new long long value. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n long long readLong();\n unsigned long long readUnsignedLong();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInteger();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInt();\n\n /* As \"readLong()\" but ensures that value in the range [minv,maxv]. */\n long long readLong(long long minv, long long maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of long longs. */\n std::vector readLongs(int size, long long minv, long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n unsigned long long readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* As \"readInteger()\" but ensures that value in the range [minv,maxv]. */\n int readInteger(int minv, int maxv, const std::string& variableName = \"\");\n /* As \"readInt()\" but ensures that value in the range [minv,maxv]. */\n int readInt(int minv, int maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of integers. */\n std::vector readIntegers(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* Reads space-separated sequence of integers. */\n std::vector readInts(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readReal();\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readDouble();\n \n /* As \"readReal()\" but ensures that value in the range [minv,maxv]. */\n double readReal(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readReals(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* As \"readDouble()\" but ensures that value in the range [minv,maxv]. */\n double readDouble(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readDoubles(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n \n /* \n * As \"readReal()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * As \"readDouble()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n \n /* As readLine(). */\n std::string readString();\n /* Read many lines. */\n std::vector readStrings(int size, int indexBase = 1);\n /* See readLine(). */\n void readStringTo(std::string& result);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readStrings(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readStrings(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads line from the current position to EOLN or EOF. Moves stream pointer to \n * the first character of the new line (if possible). \n */\n std::string readLine();\n /* Read many lines. */\n std::vector readLines(int size, int indexBase = 1);\n /* See readLine(). */\n void readLineTo(std::string& result);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readLines(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readLines(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* Reads EOLN or fails. Use it in validators. Calls \"eoln()\" method internally. */\n void readEoln();\n /* Reads EOF or fails. Use it in validators. Calls \"eof()\" method internally. */\n void readEof();\n\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quit(TResult result, const char* msg);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quitf(TResult result, const char* msg, ...);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quits(TResult result, std::string msg);\n\n /* \n * Checks condition and aborts a program if codition is false.\n * Returns _wa for ouf and _fail on any other streams.\n */\n #ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n #endif\n void ensuref(bool cond, const char* format, ...);\n void __testlib_ensure(bool cond, std::string message);\n\n void close();\n\n const static int NO_INDEX = INT_MAX;\n\n const static WORD LightGray = 0x07; \n const static WORD LightRed = 0x0c; \n const static WORD LightCyan = 0x0b; \n const static WORD LightGreen = 0x0a; \n const static WORD LightYellow = 0x0e; \n const static WORD LightMagenta = 0x0d; \n\n static void textColor(WORD color);\n static void quitscr(WORD color, const char* msg);\n static void quitscrS(WORD color, std::string msg);\n void xmlSafeWrite(std::FILE * file, const char* msg);\n\n void readSecret(std::string secret);\n void readGraderResult();\n\nprivate:\n InStream(const InStream&);\n InStream& operator =(const InStream&);\n};\n\nInStream inf;\nInStream ouf;\nInStream ans;\nbool appesMode;\nstd::string resultName;\nstd::string checkerName = \"untitled checker\";\nrandom_t rnd;\nTTestlibMode testlibMode = _unknown;\ndouble __testlib_points = std::numeric_limits::infinity();\n\nstruct ValidatorBoundsHit\n{\n static const double EPS;\n bool minHit;\n bool maxHit;\n\n ValidatorBoundsHit(bool minHit = false, bool maxHit = false): minHit(minHit), maxHit(maxHit)\n {\n };\n\n ValidatorBoundsHit merge(const ValidatorBoundsHit& validatorBoundsHit)\n {\n return ValidatorBoundsHit(\n __testlib_max(minHit, validatorBoundsHit.minHit),\n __testlib_max(maxHit, validatorBoundsHit.maxHit)\n );\n }\n};\n\nconst double ValidatorBoundsHit::EPS = 1E-12;\n\nclass Validator\n{\nprivate:\n std::string _testset;\n std::string _group;\n std::string _testOverviewLogFileName;\n std::map _boundsHitByVariableName;\n std::set _features;\n std::set _hitFeatures;\n\n bool isVariableNameBoundsAnalyzable(const std::string& variableName)\n {\n for (size_t i = 0; i < variableName.length(); i++)\n if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')\n return false;\n return true;\n }\n\n bool isFeatureNameAnalyzable(const std::string& featureName)\n {\n for (size_t i = 0; i < featureName.length(); i++)\n if (featureName[i] < ' ')\n return false;\n return true;\n }\npublic:\n Validator(): _testset(\"tests\"), _group()\n {\n }\n\n std::string testset() const\n {\n return _testset;\n }\n \n std::string group() const\n {\n return _group;\n }\n\n std::string testOverviewLogFileName() const\n {\n return _testOverviewLogFileName;\n }\n \n void setTestset(const char* const testset)\n {\n _testset = testset;\n }\n\n void setGroup(const char* const group)\n {\n _group = group;\n }\n\n void setTestOverviewLogFileName(const char* const testOverviewLogFileName)\n {\n _testOverviewLogFileName = testOverviewLogFileName;\n }\n\n void addBoundsHit(const std::string& variableName, ValidatorBoundsHit boundsHit)\n {\n if (isVariableNameBoundsAnalyzable(variableName))\n {\n _boundsHitByVariableName[variableName]\n = boundsHit.merge(_boundsHitByVariableName[variableName]);\n }\n }\n\n std::string getBoundsHitLog()\n {\n std::string result;\n for (std::map::iterator i = _boundsHitByVariableName.begin();\n i != _boundsHitByVariableName.end();\n i++)\n {\n result += \"\\\"\" + i->first + \"\\\":\";\n if (i->second.minHit)\n result += \" min-value-hit\";\n if (i->second.maxHit)\n result += \" max-value-hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n std::string getFeaturesLog()\n {\n std::string result;\n for (std::set::iterator i = _features.begin();\n i != _features.end();\n i++)\n {\n result += \"feature \\\"\" + *i + \"\\\":\";\n if (_hitFeatures.count(*i))\n result += \" hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n void writeTestOverviewLog()\n {\n if (!_testOverviewLogFileName.empty())\n {\n std::string fileName(_testOverviewLogFileName);\n _testOverviewLogFileName = \"\";\n FILE* testOverviewLogFile = fopen(fileName.c_str(), \"w\");\n if (NULL == testOverviewLogFile)\n __testlib_fail(\"Validator::writeTestOverviewLog: can't test overview log to (\" + fileName + \")\");\n fprintf(testOverviewLogFile, \"%s%s\", getBoundsHitLog().c_str(), getFeaturesLog().c_str());\n if (fclose(testOverviewLogFile))\n __testlib_fail(\"Validator::writeTestOverviewLog: can't close test overview log file (\" + fileName + \")\");\n }\n }\n\n void addFeature(const std::string& feature)\n {\n if (_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" registered twice.\");\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n _features.insert(feature);\n }\n\n void feature(const std::string& feature)\n {\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n if (!_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" didn't registered via addFeature(feature).\");\n\n _hitFeatures.insert(feature);\n }\n} validator;\n\nstruct TestlibFinalizeGuard\n{\n static bool alive;\n int quitCount, readEofCount;\n\n TestlibFinalizeGuard() : quitCount(0), readEofCount(0)\n {\n // No operations.\n }\n\n ~TestlibFinalizeGuard()\n {\n bool _alive = alive;\n alive = false;\n\n if (_alive)\n {\n if (testlibMode == _checker && quitCount == 0)\n __testlib_fail(\"Checker must end with quit or quitf call.\");\n\n if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)\n __testlib_fail(\"Validator must end with readEof call.\");\n }\n\n validator.writeTestOverviewLog();\n }\n};\n\nbool TestlibFinalizeGuard::alive = true;\nTestlibFinalizeGuard testlibFinalizeGuard;\n\n/*\n * Call it to disable checks on finalization.\n */\nvoid disableFinalizeGuard()\n{\n TestlibFinalizeGuard::alive = false;\n}\n\n/* Interactor streams.\n */\nstd::fstream tout;\n\n/* implementation\n */\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate\nstatic std::string vtos(const T& t, std::true_type)\n{ \n if (t == 0)\n return \"0\";\n else\n {\n T n(t);\n bool negative = n < 0;\n std::string s;\n while (n != 0) {\n T digit = n % 10;\n if (digit < 0)\n digit = -digit;\n s += char('0' + digit);\n n /= 10;\n }\n std::reverse(s.begin(), s.end());\n return negative ? \"-\" + s : s;\n }\n}\n\ntemplate\nstatic std::string vtos(const T& t, std::false_type)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n\ntemplate \nstatic std::string vtos(const T& t)\n{\n return vtos(t, std::is_integral());\n}\n#else\ntemplate\nstatic std::string vtos(const T& t)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n#endif\n\ntemplate \nstatic std::string toString(const T& t)\n{\n return vtos(t);\n}\n\nInStream::InStream()\n{\n reader = NULL;\n lastLine = -1;\n name = \"\";\n mode = _input;\n strict = false;\n stdfile = false;\n wordReserveSize = 4;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n printMessage = true;\n}\n\nInStream::InStream(const InStream& baseStream, std::string content)\n{\n reader = new StringInputStreamReader(content);\n lastLine = -1;\n opened = true;\n strict = baseStream.strict;\n mode = baseStream.mode;\n name = \"based on \" + baseStream.name;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n printMessage = true;\n}\n\nInStream::~InStream()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\nint resultExitCode(TResult r)\n{\n if (testlibMode == _checker)\n return 0;//CMS Checkers should always finish with zero exit code.\n if (r == _ok)\n return OK_EXIT_CODE;\n if (r == _wa)\n return WA_EXIT_CODE;\n if (r == _pe)\n return PE_EXIT_CODE;\n if (r == _fail)\n return FAIL_EXIT_CODE;\n if (r == _dirt)\n return DIRT_EXIT_CODE;\n if (r == _points)\n return POINTS_EXIT_CODE;\n if (r == _unexpected_eof)\n#ifdef ENABLE_UNEXPECTED_EOF\n return UNEXPECTED_EOF_EXIT_CODE;\n#else\n return PE_EXIT_CODE;\n#endif\n if (r == _sv)\n return SV_EXIT_CODE;\n if (r >= _partially)\n return PC_BASE_EXIT_CODE + (r - _partially);\n return FAIL_EXIT_CODE;\n}\n\nvoid InStream::textColor(\n#if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)) && defined(__GNUC__)\n __attribute__((unused)) \n#endif\n WORD color\n)\n{\n#if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)\n HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(handle, color);\n#endif\n#if !defined(ON_WINDOWS) && defined(__GNUC__)\n if (isatty(2))\n {\n switch (color)\n {\n case LightRed:\n fprintf(stderr, \"\\033[1;31m\");\n break;\n case LightCyan:\n fprintf(stderr, \"\\033[1;36m\");\n break;\n case LightGreen:\n fprintf(stderr, \"\\033[1;32m\");\n break;\n case LightYellow:\n fprintf(stderr, \"\\033[1;33m\");\n break;\n case LightMagenta:\n fprintf(stderr, \"\\033[1;35m\");\n break;\n case LightGray:\n default:\n fprintf(stderr, \"\\033[0m\");\n }\n }\n#endif\n}\n\nNORETURN void halt(int exitCode)\n{\n#ifdef FOOTER\n InStream::textColor(InStream::LightGray);\n std::fprintf(stderr, \"Checker: \\\"%s\\\"\\n\", checkerName.c_str());\n std::fprintf(stderr, \"Exit code: %d\\n\", exitCode);\n InStream::textColor(InStream::LightGray);\n#endif\n std::exit(exitCode);\n}\n\nstatic bool __testlib_shouldCheckDirt(TResult result)\n{\n return result == _ok || result == _points || result >= _partially;\n}\n\nNORETURN void InStream::quit(TResult result, const char* msg)\n{\n if (TestlibFinalizeGuard::alive)\n testlibFinalizeGuard.quitCount++;\n\n // You can change maxMessageLength.\n // Example: 'inf.maxMessageLength = 1024 * 1024;'.\n if (strlen(msg) > maxMessageLength)\n {\n std::string message(msg);\n std::string warn = \"message length exceeds \" + vtos(maxMessageLength)\n + \", the message is truncated: \";\n msg = (warn + message.substr(0, maxMessageLength - warn.length())).c_str();\n }\n\n#ifndef ENABLE_UNEXPECTED_EOF\n if (result == _unexpected_eof)\n result = _pe;\n#endif\n\n if (mode != _output && result != _fail)\n {\n if (mode == _input && testlibMode == _validator && lastLine != -1)\n quits(_fail, std::string(msg) + \" (\" + name + \", line \" + vtos(lastLine) + \")\");\n else\n quits(_fail, std::string(msg) + \" (\" + name + \")\");\n }\n\n std::FILE * resultFile;\n std::string errorName;\n \n if (__testlib_shouldCheckDirt(result))\n {\n if (testlibMode != _interactor && !ouf.seekEof())\n quit(_dirt, \"Extra information in the output file\");\n }\n\n int pctype = result - _partially;\n bool isPartial = false;\n\n if (testlibMode == _checker) {\n WORD color;\n std::string pointsStr = \"0\";\n switch (result)\n {\n case _ok:\n pointsStr = format(\"%d\", 1);\n color = LightGreen;\n errorName = \"Output is correct\";\n break;\n case _wa:\n case _pe:\n case _dirt:\n case _unexpected_eof:\n color = LightRed;\n errorName = \"Output isn't correct\";\n break;\n case _fail:\n color = LightMagenta;\n errorName = \"Judge Failure; Contact staff!\";\n break;\n case _sv:\n color = LightMagenta;\n errorName = \"Protocol Violation\";\n break;\n case _points:\n if (__testlib_points < 1e-5)\n pointsStr = \"0.00001\";//prevent zero scores in CMS as zero is considered wrong\n else if (__testlib_points < 0.0001)\n pointsStr = format(\"%lf\", __testlib_points);//prevent rounding the numbers below 0.0001\n else\n pointsStr = format(\"%.4lf\", __testlib_points);\n color = LightYellow;\n errorName = \"Output is partially correct\";\n break;\n default:\n if (result >= _partially)\n quit(_fail, \"testlib partially mode not supported\");\n else\n quit(_fail, \"What is the code ??? \");\n } \n std::fprintf(stdout, \"%s\\n\", pointsStr.c_str());\n quitscrS(color, errorName);\n std::fprintf(stderr, \"\\n\");\n } else {\n switch (result)\n {\n case _ok:\n errorName = \"ok \";\n quitscrS(LightGreen, errorName);\n break;\n case _wa:\n errorName = \"wrong answer \";\n quitscrS(LightRed, errorName);\n break;\n case _pe:\n errorName = \"wrong output format \";\n quitscrS(LightRed, errorName);\n break;\n case _fail:\n errorName = \"FAIL \";\n quitscrS(LightRed, errorName);\n break;\n case _dirt:\n errorName = \"wrong output format \";\n quitscrS(LightCyan, errorName);\n result = _pe;\n break;\n case _points:\n errorName = \"points \";\n quitscrS(LightYellow, errorName);\n break;\n case _unexpected_eof:\n errorName = \"unexpected eof \";\n quitscrS(LightCyan, errorName);\n break;\n default:\n if (result >= _partially)\n {\n errorName = format(\"partially correct (%d) \", pctype);\n isPartial = true;\n quitscrS(LightYellow, errorName);\n }\n else\n quit(_fail, \"What is the code ??? \");\n }\n }\n\n if (resultName != \"\")\n {\n resultFile = std::fopen(resultName.c_str(), \"w\");\n if (resultFile == NULL)\n quit(_fail, \"Can not write to the result file\");\n if (appesMode)\n {\n std::fprintf(resultFile, \"\");\n if (isPartial)\n std::fprintf(resultFile, \"\", outcomes[(int)_partially].c_str(), pctype);\n else\n {\n if (result != _points)\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str());\n else\n {\n if (__testlib_points == std::numeric_limits::infinity())\n quit(_fail, \"Expected points, but infinity found\");\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", __testlib_points));\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str(), stringPoints.c_str());\n }\n }\n if (printMessage)\n xmlSafeWrite(resultFile, msg);\n std::fprintf(resultFile, \"\\n\");\n }\n else\n {\n if (printMessage)\n std::fprintf(resultFile, \"%s\", msg);\n }\n if (NULL == resultFile || fclose(resultFile) != 0)\n quit(_fail, \"Can not write to the result file\");\n }\n\n if (printMessage)\n {\n quitscr(LightGray, msg);\n std::fprintf(stderr, \"\\n\");\n }\n\n inf.close();\n ouf.close();\n ans.close();\n if (tout.is_open())\n tout.close();\n\n textColor(LightGray);\n\n if (resultName != \"\")\n std::fprintf(stderr, \"See file to check exit message\\n\");\n\n halt(resultExitCode(result));\n}\n\n#ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n#endif\nNORETURN void InStream::quitf(TResult result, const char* msg, ...)\n{\n FMT_TO_RESULT(msg, msg, message);\n InStream::quit(result, message.c_str());\n}\n\nNORETURN void InStream::quits(TResult result, std::string msg)\n{\n InStream::quit(result, msg.c_str());\n}\n\nvoid InStream::xmlSafeWrite(std::FILE * file, const char* msg)\n{\n size_t lmsg = strlen(msg);\n for (size_t i = 0; i < lmsg; i++)\n {\n if (msg[i] == '&')\n {\n std::fprintf(file, \"%s\", \"&\");\n continue;\n }\n if (msg[i] == '<')\n {\n std::fprintf(file, \"%s\", \"<\");\n continue;\n }\n if (msg[i] == '>')\n {\n std::fprintf(file, \"%s\", \">\");\n continue;\n }\n if (msg[i] == '\"')\n {\n std::fprintf(file, \"%s\", \""\");\n continue;\n }\n if (0 <= msg[i] && msg[i] <= 31)\n {\n std::fprintf(file, \"%c\", '.');\n continue;\n }\n std::fprintf(file, \"%c\", msg[i]);\n }\n}\n\nvoid InStream::quitscrS(WORD color, std::string msg)\n{\n quitscr(color, msg.c_str());\n}\n\nvoid InStream::quitscr(WORD color, const char* msg)\n{\n if (resultName == \"\")\n {\n textColor(color);\n std::fprintf(stderr, \"%s\", msg);\n textColor(LightGray);\n }\n}\n\nvoid InStream::reset(std::FILE* file)\n{\n if (opened && stdfile)\n quit(_fail, \"Can't reset standard handle\");\n\n if (opened)\n close();\n\n if (!stdfile)\n if (NULL == (file = std::fopen(name.c_str(), \"rb\")))\n {\n if (mode == _output)\n quits(_pe, std::string(\"Output file not found: \\\"\") + name + \"\\\"\");\n \n if (mode == _answer)\n quits(_fail, std::string(\"Answer file not found: \\\"\") + name + \"\\\"\");\n }\n\n if (NULL != file)\n {\n opened = true;\n\n __testlib_set_binary(file);\n\n if (stdfile)\n reader = new FileInputStreamReader(file, name);\n else\n reader = new BufferedFileInputStreamReader(file, name);\n }\n else\n {\n opened = false;\n reader = NULL;\n }\n}\n\nvoid InStream::init(std::string fileName, TMode mode)\n{\n opened = false;\n name = fileName;\n stdfile = false;\n this->mode = mode;\n \n std::ifstream stream;\n stream.open(fileName.c_str(), std::ios::in);\n if (stream.is_open())\n {\n std::streampos start = stream.tellg();\n stream.seekg(0, std::ios::end);\n std::streampos end = stream.tellg();\n size_t fileSize = size_t(end - start);\n stream.close();\n \n // You can change maxFileSize.\n // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'.\n if (fileSize > maxFileSize)\n quitf(_pe, \"File size exceeds %d bytes, size is %d\", int(maxFileSize), int(fileSize));\n }\n\n reset();\n}\n\nvoid InStream::init(std::FILE* f, TMode mode)\n{\n opened = false;\n name = \"untitled\";\n this->mode = mode;\n \n if (f == stdin)\n name = \"stdin\", stdfile = true;\n if (f == stdout)\n name = \"stdout\", stdfile = true;\n if (f == stderr)\n name = \"stderr\", stdfile = true;\n\n reset(f);\n}\n\nchar InStream::curChar()\n{\n return char(reader->curChar());\n}\n\nchar InStream::nextChar()\n{\n return char(reader->nextChar());\n}\n\nchar InStream::readChar()\n{\n return nextChar();\n}\n\nchar InStream::readChar(char c)\n{\n lastLine = reader->getLine();\n char found = readChar();\n if (c != found)\n {\n if (!isEoln(found))\n quit(_pe, (\"Unexpected character '\" + std::string(1, found) + \"', but '\" + std::string(1, c) + \"' expected\").c_str());\n else\n quit(_pe, (\"Unexpected character \" + (\"#\" + vtos(int(found))) + \", but '\" + std::string(1, c) + \"' expected\").c_str());\n }\n return found;\n}\n\nchar InStream::readSpace()\n{\n return readChar(' ');\n}\n\nvoid InStream::unreadChar(char c)\n{\n reader->unreadChar(c);\n}\n\nvoid InStream::skipChar()\n{\n reader->skipChar();\n}\n\nvoid InStream::skipBlanks()\n{\n while (isBlanks(reader->curChar()))\n reader->skipChar();\n}\n\nstd::string InStream::readWord()\n{\n readWordTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nvoid InStream::readWordTo(std::string& result)\n{\n if (!strict)\n skipBlanks();\n\n lastLine = reader->getLine();\n int cur = reader->nextChar();\n\n if (cur == EOFC)\n quit(_unexpected_eof, \"Unexpected end of file - token expected\");\n\n if (isBlanks(cur))\n quit(_pe, \"Unexpected white-space - token expected\");\n\n result.clear();\n\n while (!(isBlanks(cur) || cur == EOFC))\n {\n result += char(cur);\n \n // You can change maxTokenLength.\n // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'.\n if (result.length() > maxTokenLength)\n quitf(_pe, \"Length of token exceeds %d, token is '%s...'\", int(maxTokenLength), __testlib_part(result).c_str());\n\n cur = reader->nextChar();\n }\n\n reader->unreadChar(cur);\n\n if (result.length() == 0)\n quit(_unexpected_eof, \"Unexpected end of file or white-space - token expected\");\n}\n\nstd::string InStream::readToken()\n{\n return readWord();\n}\n\nvoid InStream::readTokenTo(std::string& result)\n{\n readWordTo(result);\n}\n\nstatic std::string __testlib_part(const std::string& s)\n{\n if (s.length() <= 64)\n return s;\n else\n return s.substr(0, 30) + \"...\" + s.substr(s.length() - 31, 31);\n}\n\n#define __testlib_readMany(readMany, readOne, typeName, space) \\\n if (size < 0) \\\n quit(_fail, #readMany \": size should be non-negative.\"); \\\n if (size > 100000000) \\\n quit(_fail, #readMany \": size should be at most 100000000.\"); \\\n \\\n std::vector result(size); \\\n readManyIteration = indexBase; \\\n \\\n for (int i = 0; i < size; i++) \\\n { \\\n result[i] = readOne; \\\n readManyIteration++; \\\n if (strict && space && i + 1 < size) \\\n readSpace(); \\\n } \\\n \\\n readManyIteration = NO_INDEX; \\\n return result; \\\n\nstd::string InStream::readWord(const pattern& p, const std::string& variableName)\n{\n readWordTo(_tmpReadToken);\n if (!p.matches(_tmpReadToken))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Token element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token element \" + variableName + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n return _tmpReadToken;\n}\n\nstd::vector InStream::readWords(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readWord(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(pattern(ptrn), variableName);\n}\n\nstd::vector InStream::readWords(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const pattern& p, const std::string& variableName)\n{\n return readWord(p, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(ptrn, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true);\n}\n\nvoid InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readWordTo(result);\n if (!p.matches(result))\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n}\n\nvoid InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, pattern(ptrn), variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n return readWordTo(result, p, variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, ptrn, variableName);\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(long long integer, const char* s)\n{\n if (integer == LLONG_MIN)\n return strcmp(s, \"-9223372036854775808\") == 0;\n\n if (integer == 0LL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n if (integer < 0 && s[0] != '-')\n return false;\n\n if (integer < 0)\n s++, length--, integer = -integer;\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(unsigned long long integer, const char* s)\n{\n if (integer == ULLONG_MAX)\n return strcmp(s, \"18446744073709551615\") == 0;\n\n if (integer == 0ULL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\nstatic inline double stringToDouble(InStream& in, const char* buffer)\n{\n double retval;\n\n size_t length = strlen(buffer);\n\n int minusCount = 0;\n int plusCount = 0;\n int decimalPointCount = 0;\n int digitCount = 0;\n int eCount = 0;\n\n for (size_t i = 0; i < length; i++)\n {\n if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.'\n || buffer[i] == 'e' || buffer[i] == 'E'\n || buffer[i] == '-' || buffer[i] == '+')\n {\n if ('0' <= buffer[i] && buffer[i] <= '9')\n digitCount++;\n if (buffer[i] == 'e' || buffer[i] == 'E')\n eCount++;\n if (buffer[i] == '-')\n minusCount++;\n if (buffer[i] == '+')\n plusCount++;\n if (buffer[i] == '.')\n decimalPointCount++;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n // If for sure is not a number in standard notation or in e-notation.\n if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)\n{\n if (minAfterPointDigitCount < 0)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be non-negative.\");\n \n if (minAfterPointDigitCount > maxAfterPointDigitCount)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.\");\n\n double retval;\n\n size_t length = strlen(buffer);\n\n if (length == 0 || length > 1000)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int pointPos = -1; \n for (size_t i = 1; i + 1 < length; i++)\n {\n if (buffer[i] == '.')\n {\n if (pointPos > -1)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n pointPos = int(i);\n }\n if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n if (buffer[length - 1] < '0' || buffer[length - 1] > '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);\n if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)\n in.quit(_pe, (\"Expected strict double with number of digits after point in range [\"\n + vtos(minAfterPointDigitCount)\n + \",\"\n + vtos(maxAfterPointDigitCount)\n + \"], but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str()\n );\n\n int firstDigitPos = -1;\n for (size_t i = 0; i < length; i++)\n if (buffer[i] >= '0' && buffer[i] <= '9')\n {\n firstDigitPos = int(i);\n break;\n }\n\n if (firstDigitPos > 1 || firstDigitPos == -1) \n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)\n && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline long long stringToLongLong(InStream& in, const char* buffer)\n{\n if (strcmp(buffer, \"-9223372036854775808\") == 0)\n return LLONG_MIN;\n\n bool minus = false;\n size_t length = strlen(buffer);\n \n if (length > 1 && buffer[0] == '-')\n minus = true;\n\n if (length > 20)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n long long retval = 0LL;\n\n int zeroes = 0;\n int processingZeroes = true;\n \n for (int i = (minus ? 1 : 0); i < int(length); i++)\n {\n if (buffer[i] == '0' && processingZeroes)\n zeroes++;\n else\n processingZeroes = false;\n\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (retval < 0)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n \n if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n retval = (minus ? -retval : +retval);\n\n if (length < 19)\n return retval;\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline unsigned long long stringToUnsignedLongLong(InStream& in, const char* buffer)\n{\n size_t length = strlen(buffer);\n\n if (length > 20)\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n if (length > 1 && buffer[0] == '0')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n unsigned long long retval = 0LL;\n for (int i = 0; i < int(length); i++)\n {\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (length < 19)\n return retval;\n\n if (length == 20 && strcmp(buffer, \"18446744073709551615\") == 1)\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nint InStream::readInteger()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int32 expected\");\n\n readWordTo(_tmpReadToken);\n \n long long value = stringToLongLong(*this, _tmpReadToken.c_str());\n if (value < INT_MIN || value > INT_MAX)\n quit(_pe, (\"Expected int32, but \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" found\").c_str());\n \n return int(value);\n}\n\nlong long InStream::readLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToLongLong(*this, _tmpReadToken.c_str());\n}\n\nunsigned long long InStream::readUnsignedLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToUnsignedLongLong(*this, _tmpReadToken.c_str());\n}\n\nlong long InStream::readLong(long long minv, long long maxv, const std::string& variableName)\n{\n long long result = readLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readLongs(int size, long long minv, long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true)\n}\n\nunsigned long long InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n unsigned long long result = readUnsignedLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true)\n}\n\nunsigned long long InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n return readUnsignedLong(minv, maxv, variableName);\n}\n\nint InStream::readInt()\n{\n return readInteger();\n}\n\nint InStream::readInt(int minv, int maxv, const std::string& variableName)\n{\n int result = readInt();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nint InStream::readInteger(int minv, int maxv, const std::string& variableName)\n{\n return readInt(minv, maxv, variableName);\n}\n\nstd::vector InStream::readInts(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true)\n}\n\nstd::vector InStream::readIntegers(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true)\n}\n\ndouble InStream::readReal()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - double expected\");\n\n return stringToDouble(*this, readWord().c_str());\n}\n\ndouble InStream::readDouble()\n{\n return readReal();\n}\n\ndouble InStream::readReal(double minv, double maxv, const std::string& variableName)\n{\n double result = readReal();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readReals(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readDouble(double minv, double maxv, const std::string& variableName)\n{\n return readReal(minv, maxv, variableName);\n} \n\nstd::vector InStream::readDoubles(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - strict double expected\");\n\n double result = stringToStrictDouble(*this, readWord().c_str(),\n minAfterPointDigitCount, maxAfterPointDigitCount);\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictReals, readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\ndouble InStream::readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n return readStrictReal(minv, maxv,\n minAfterPointDigitCount, maxAfterPointDigitCount,\n variableName);\n}\n\nstd::vector InStream::readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictDoubles, readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\nbool InStream::eof()\n{\n if (!strict && NULL == reader)\n return true;\n\n return reader->eof();\n}\n\nbool InStream::seekEof()\n{\n if (!strict && NULL == reader)\n return true;\n skipBlanks();\n return eof();\n}\n\nbool InStream::eoln()\n{\n if (!strict && NULL == reader)\n return true;\n\n int c = reader->nextChar();\n\n if (!strict)\n {\n if (c == EOFC)\n return true;\n\n if (c == CR)\n {\n c = reader->nextChar();\n\n if (c != LF)\n {\n reader->unreadChar(c);\n reader->unreadChar(CR);\n return false;\n }\n else\n return true;\n }\n \n if (c == LF)\n return true;\n\n reader->unreadChar(c);\n return false;\n }\n else\n {\n bool returnCr = false;\n\n#if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS)\n if (c != CR)\n {\n reader->unreadChar(c);\n return false;\n }\n else\n {\n if (!returnCr)\n returnCr = true;\n c = reader->nextChar();\n }\n#endif \n if (c != LF)\n {\n reader->unreadChar(c);\n if (returnCr)\n reader->unreadChar(CR);\n return false;\n }\n\n return true;\n }\n}\n\nvoid InStream::readEoln()\n{\n lastLine = reader->getLine();\n if (!eoln())\n quit(_pe, \"Expected EOLN\");\n}\n\nvoid InStream::readEof()\n{\n lastLine = reader->getLine();\n if (!eof())\n quit(_pe, \"Expected EOF\");\n\n if (TestlibFinalizeGuard::alive && this == &inf)\n testlibFinalizeGuard.readEofCount++;\n}\n\nbool InStream::seekEoln()\n{\n if (!strict && NULL == reader)\n return true;\n \n int cur;\n do\n {\n cur = reader->nextChar();\n } \n while (cur == SPACE || cur == TAB);\n\n reader->unreadChar(cur);\n return eoln();\n}\n\nvoid InStream::nextLine()\n{\n readLine();\n}\n\nvoid InStream::readStringTo(std::string& result)\n{\n if (NULL == reader)\n quit(_pe, \"Expected line\");\n\n result.clear();\n\n for (;;)\n {\n int cur = reader->curChar();\n\n if (cur == LF || cur == EOFC)\n break;\n\n if (cur == CR)\n {\n cur = reader->nextChar();\n if (reader->curChar() == LF)\n {\n reader->unreadChar(cur);\n break;\n }\n }\n\n lastLine = reader->getLine();\n result += char(reader->nextChar());\n }\n\n if (strict)\n readEoln();\n else\n eoln();\n}\n\nstd::string InStream::readString()\n{\n readStringTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, int indexBase)\n{\n __testlib_readMany(readStrings, readString(), std::string, false)\n}\n\nvoid InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result);\n if (!p.matches(result))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Line \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Line element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n}\n\nvoid InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, pattern(ptrn), variableName);\n}\n\nstd::string InStream::readString(const pattern& p, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, p, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readString(const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, ptrn, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result)\n{\n readStringTo(result);\n}\n\nstd::string InStream::readLine()\n{\n return readString();\n}\n\nstd::vector InStream::readLines(int size, int indexBase)\n{\n __testlib_readMany(readLines, readString(), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result, p, variableName);\n}\n\nvoid InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, ptrn, variableName);\n}\n\nstd::string InStream::readLine(const pattern& p, const std::string& variableName)\n{\n return readString(p, variableName);\n}\n\nstd::vector InStream::readLines(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readLine(const std::string& ptrn, const std::string& variableName)\n{\n return readString(ptrn, variableName);\n}\n\nstd::vector InStream::readLines(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid InStream::ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n this->__testlib_ensure(cond, message);\n }\n}\n\nvoid InStream::__testlib_ensure(bool cond, std::string message)\n{\n if (!cond)\n this->quit(_wa, message.c_str()); \n}\n\nvoid InStream::close()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n \n opened = false;\n}\n\nNORETURN void quit(TResult result, const std::string& msg)\n{\n ouf.quit(result, msg.c_str());\n}\n\nNORETURN void quit(TResult result, const char* msg)\n{\n ouf.quit(result, msg);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...);\n\nNORETURN void __testlib_quitp(double points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %lf, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", points));\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void __testlib_quitp(int points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %d, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = format(\"%d\", points);\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void quitp(float points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(double points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\nNORETURN void quitp(long double points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(int points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\ntemplate\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitp(F points, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quitp(points, message);\n}\n\ntemplate\nNORETURN void quitp(F points)\n{\n __testlib_quitp(points, std::string(\"\"));\n}\n\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid quitif(bool condition, TResult result, const char* format, ...)\n{\n if (condition)\n {\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n }\n}\n\nNORETURN void __testlib_help()\n{\n InStream::textColor(InStream::LightCyan);\n std::fprintf(stderr, \"TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ \", VERSION);\n std::fprintf(stderr, \"by Mike Mirzayanov, copyright(c) 2005-2018\\n\");\n std::fprintf(stderr, \"Checker name: \\\"%s\\\"\\n\", checkerName.c_str());\n InStream::textColor(InStream::LightGray);\n\n std::fprintf(stderr, \"\\n\");\n std::fprintf(stderr, \"Latest features: \\n\");\n for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)\n {\n std::fprintf(stderr, \"*) %s\\n\", latestFeatures[i]);\n }\n std::fprintf(stderr, \"\\n\");\n\n std::fprintf(stderr, \"Program must be run with the following arguments: \\n\");\n std::fprintf(stderr, \" [ [<-appes>]]\\n\\n\");\n\n std::exit(FAIL_EXIT_CODE);\n}\n\nstatic void __testlib_ensuresPreconditions()\n{\n // testlib assumes: sizeof(int) = 4.\n __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);\n\n // testlib assumes: INT_MAX == 2147483647.\n __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);\n\n // testlib assumes: sizeof(long long) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);\n\n // testlib assumes: sizeof(double) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);\n\n // testlib assumes: no -ffast-math.\n if (!__testlib_isNaN(+__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n if (!__testlib_isNaN(-__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n}\n\nvoid registerGen(int argc, char* argv[], int randomGeneratorVersion)\n{\n if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)\n quitf(_fail, \"Random generator version is expected to be 0 or 1.\");\n random_t::version = randomGeneratorVersion;\n\n __testlib_ensuresPreconditions();\n\n testlibMode = _generator;\n __testlib_set_binary(stdin);\n rnd.setSeed(argc, argv);\n}\n\n#ifdef USE_RND_AS_BEFORE_087\nvoid registerGen(int argc, char* argv[])\n{\n registerGen(argc, argv, 0);\n}\n#else\n#ifdef __GNUC__\n#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4))\n __attribute__ ((deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\")))\n#else\n __attribute__ ((deprecated))\n#endif\n#endif\n#ifdef _MSC_VER\n __declspec(deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\"))\n#endif\nvoid registerGen(int argc, char* argv[])\n{\n std::fprintf(stderr, \"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\\n\\n\");\n registerGen(argc, argv, 0);\n}\n#endif\n\nvoid registerInteraction(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _interactor;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n \n if (argc < 3 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [ [<-appes>]]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc <= 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n#ifndef EJUDGE\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n#endif\n\n inf.init(argv[1], _input);\n\n tout.open(argv[2], std::ios_base::out);\n if (tout.fail() || !tout.is_open())\n quit(_fail, std::string(\"Can not write to the test-output-file '\") + argv[2] + std::string(\"'\"));\n\n ouf.init(stdin, _output);\n \n if (argc >= 4)\n ans.init(argv[3], _answer);\n else\n ans.name = \"unopened answer stream\";\n}\n\nvoid registerValidation()\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _validator;\n __testlib_set_binary(stdin);\n\n inf.init(stdin, _input);\n inf.strict = true;\n}\n\nvoid registerValidation(int argc, char* argv[])\n{\n registerValidation();\n\n for (int i = 1; i < argc; i++)\n {\n if (!strcmp(\"--testset\", argv[i]))\n {\n if (i + 1 < argc && strlen(argv[i + 1]) > 0)\n validator.setTestset(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--group\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setGroup(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--testOverviewLogFileName\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setTestOverviewLogFileName(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n } \n}\n\nvoid addFeature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.addFeature(feature); \n}\n\nvoid feature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.feature(feature); \n}\n\nvoid registerTestlibCmd(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _checker;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n\n if (argc < 4 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [<-appes>]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc == 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n\n inf.init(argv[1], _input);\n ans.init(argv[2], _answer);\n ouf.init(argv[3], _output);\n}\n\nvoid registerTestlib(int argc, ...)\n{\n if (argc < 3 || argc > 5)\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n\n char** argv = new char*[argc + 1];\n \n va_list ap;\n va_start(ap, argc);\n argv[0] = NULL;\n for (int i = 0; i < argc; i++)\n {\n argv[i + 1] = va_arg(ap, char*);\n }\n va_end(ap);\n\n registerTestlibCmd(argc + 1, argv);\n delete[] argv;\n}\n\nstatic inline void __testlib_ensure(bool cond, const std::string& msg)\n{\n if (!cond)\n quit(_fail, msg.c_str());\n}\n\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\nstatic inline void __testlib_ensure(bool cond, const char* msg)\n{\n if (!cond)\n quit(_fail, msg);\n}\n\n#define ensure(cond) __testlib_ensure(cond, \"Condition failed: \\\"\" #cond \"\\\"\")\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\ninline void ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n __testlib_ensure(cond, message);\n }\n}\n\nNORETURN static void __testlib_fail(const std::string& message)\n{\n quitf(_fail, \"%s\", message.c_str());\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid setName(const char* format, ...)\n{\n FMT_TO_RESULT(format, format, name);\n checkerName = name;\n}\n\n/* \n * Do not use random_shuffle, because it will produce different result\n * for different C++ compilers.\n *\n * This implementation uses testlib random_t to produce random numbers, so\n * it is stable.\n */ \ntemplate\nvoid shuffle(_RandomAccessIter __first, _RandomAccessIter __last)\n{\n if (__first == __last) return;\n for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)\n std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));\n}\n\n\ntemplate\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use random_shuffle(), use shuffle() instead\")))\n#endif\nvoid random_shuffle(_RandomAccessIter , _RandomAccessIter )\n{\n quitf(_fail, \"Don't use random_shuffle(), use shuffle() instead\");\n}\n\n#ifdef __GLIBC__\n# define RAND_THROW_STATEMENT throw()\n#else\n# define RAND_THROW_STATEMENT\n#endif\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use rand(), use rnd.next() instead\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nint rand() RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use rand(), use rnd.next() instead\");\n \n /* This line never runs. */\n //throw \"Don't use rand(), use rnd.next() instead\";\n}\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1).\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nvoid srand(unsigned int seed) RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1) [ignored seed=%d].\", seed);\n}\n\nvoid startTest(int test)\n{\n const std::string testFileName = vtos(test);\n if (NULL == freopen(testFileName.c_str(), \"wt\", stdout))\n __testlib_fail(\"Unable to write file '\" + testFileName + \"'\");\n}\n\ninline std::string upperCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('a' <= s[i] && s[i] <= 'z')\n s[i] = char(s[i] - 'a' + 'A');\n return s;\n}\n\ninline std::string lowerCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('A' <= s[i] && s[i] <= 'Z')\n s[i] = char(s[i] - 'A' + 'a');\n return s;\n}\n\ninline std::string compress(const std::string& s)\n{\n return __testlib_part(s);\n}\n\ninline std::string englishEnding(int x)\n{\n x %= 100;\n if (x / 10 == 1)\n return \"th\";\n if (x % 10 == 1)\n return \"st\";\n if (x % 10 == 2)\n return \"nd\";\n if (x % 10 == 3)\n return \"rd\";\n return \"th\";\n}\n\ninline std::string trim(const std::string& s)\n{\n if (s.empty())\n return s;\n\n int left = 0;\n while (left < int(s.length()) && isBlanks(s[left]))\n left++;\n if (left >= int(s.length()))\n return \"\";\n\n int right = int(s.length()) - 1;\n while (right >= 0 && isBlanks(s[right]))\n right--;\n if (right < 0)\n return \"\";\n\n return s.substr(left, right - left + 1);\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator)\n{\n std::stringstream ss;\n bool repeated = false;\n for (_ForwardIterator i = first; i != last; i++)\n {\n if (repeated)\n ss << separator;\n else\n repeated = true;\n ss << *i;\n }\n return ss.str();\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last)\n{\n return join(first, last, ' ');\n}\n\ntemplate \nstd::string join(const _Collection& collection, _Separator separator)\n{\n return join(collection.begin(), collection.end(), separator);\n}\n\ntemplate \nstd::string join(const _Collection& collection)\n{\n return join(collection, ' ');\n}\n\n/**\n * Splits string s by character separator returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separator returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n if (!item.empty())\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n \n if (!item.empty())\n result.push_back(item);\n\n return result;\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char* prepend)\n{\n std::string message;\n if (strlen(prepend) != 0)\n message = format(\"%s: expected '%s', but found '%s'\",\n compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());\n else\n message = format(\"expected '%s', but found '%s'\",\n compress(expected).c_str(), compress(found).c_str());\n quit(result, message);\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char* prepend)\n{\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend);\n}\n\ntemplate \n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, T expected, T found, const char* prependFormat = \"\", ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = vtos(expected);\n std::string foundString = vtos(found);\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, std::string expected, std::string found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, expected, found, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, double expected, double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, const char* expected, const char* found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, float expected, float found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, long double expected, long double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\n#endif\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate \nstruct is_iterable\n{\n template \n static char test(typename U::iterator* x);\n \n template \n static long test(U* x);\n \n static const bool value = sizeof(test(0)) == 1;\n};\n\ntemplate\nstruct __testlib_enable_if {};\n \ntemplate\nstruct __testlib_enable_if { typedef T type; };\n\ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n std::cout << t;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n bool first = true;\n for (typename T::const_iterator i = t.begin(); i != t.end(); i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n std::cout << *i;\n }\n}\n\ntemplate<>\ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const std::string& t)\n{\n std::cout << t;\n}\n \ntemplate\nvoid __println_range(A begin, B end)\n{\n bool first = true;\n for (B i = B(begin); i != end; i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n __testlib_print_one(*i);\n }\n std::cout << std::endl;\n}\n\ntemplate\nstruct is_iterator\n{ \n static T makeT();\n typedef void * twoptrs[2];\n static twoptrs & test(...);\n template static typename R::iterator_category * test(R);\n template static void * test(R *);\n static const bool value = sizeof(test(makeT())) == sizeof(void *); \n};\n\ntemplate\nstruct is_iterator::value >::type>\n{\n static const bool value = false; \n};\n\ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __println_range(a, b);\n}\n\ntemplate \nvoid println(const A* a, const A* b)\n{\n __println_range(a, b);\n}\n\ntemplate <>\nvoid println(const char* a, const char* b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const T& x)\n{\n __testlib_print_one(x);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f, const G& g)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << \" \";\n __testlib_print_one(g);\n std::cout << std::endl;\n}\n#endif\n\n\n\nvoid registerChecker(std::string probName, int argc, char* argv[])\n{\n setName(\"checker for problem %s\", probName.c_str());\n registerTestlibCmd(argc, argv);\n}\n\n\n\nconst std::string _grader_OK = \"OK\";\nconst std::string _grader_SV = \"SV\";\nconst std::string _grader_WA = \"WA\";\nconst std::string _grader_FAIL = \"FAIL\";\n\n\nvoid InStream::readSecret(std::string secret)\n{\n if (readWord() != secret)\n quitf(_sv, \"secret mismatch\");\n eoln();\n}\n\nvoid readBothSecrets(std::string secret)\n{\n ans.readSecret(secret);\n ouf.readSecret(secret);\n}\n\nvoid InStream::readGraderResult()\n{\n std::string result = readWord();\n eoln();\n if (result == _grader_OK)\n return;\n if (result == _grader_SV)\n {\n if (eof())\n quitf(_sv, \"Security violation in grader\");\n std::string msg = readLine();\n quitf(_wa, \"Security violation in grader: %s\", msg.c_str());\n }\n if (result == _grader_WA)\n {\n if (eof())\n quitf(_wa, \"WA in grader\");\n std::string msg = readLine();\n quitf(_wa, \"WA in grader: %s\", msg.c_str());\n }\n if (result == _grader_FAIL)\n {\n if (eof())\n quitf(_fail, \"FAIL in grader\");\n std::string msg = readLine();\n quitf(_fail, \"FAIL in grader: %s\", msg.c_str());\n }\n quitf(_fail, \"Unknown grader result\");\n}\n\nvoid readBothGraderResults()\n{\n ans.readGraderResult();\n ouf.readGraderResult();\n}\n\n\nNORETURN void quit(TResult result)\n{\n ouf.quit(result, \"\");\n}\n\n/// Used in validators: skips the rest of input, assuming it to be correct\nNORETURN void skip_ok()\n{\n if (testlibMode != _validator)\n quitf(_fail, \"skip_ok() only works in validators\");\n testlibFinalizeGuard.quitCount++;\n exit(0);\n}\n\n/// 1 -> 1st, 2 -> 2nd, 3 -> 3rd, 4 -> 4th, ...\nstd::string englishTh(int x)\n{\n char c[100];\n sprintf(c, \"%d%s\", x, englishEnding(x).c_str());\n return c;\n}\n\n/// Compares the tokens of two lines\nvoid compareTokens(int lineNo, std::string a, std::string b, char separator=' ')\n{\n std::vector toka = tokenize(a, separator);\n std::vector tokb = tokenize(b, separator);\n if (toka == tokb)\n return;\n std::string dif = format(\"%s lines differ - \", englishTh(lineNo).c_str());\n if (toka.size() != tokb.size())\n quitf(_wa, \"%sexpected: %d tokens, found %d tokens\", dif.c_str(), int(toka.size()), int(tokb.size()));\n for (int i=0; i\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstatic const int CIPHER_SIZE = 64;\nstatic const int CIPHER_KEY[CIPHER_SIZE] = {1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0};\n\ntemplate \nstatic int xored(const V& c, int i) {\n\treturn (int)c[i] ^ (CIPHER_KEY[i % CIPHER_SIZE] & 1);\n}\n\nstatic int MAXQ = 30000;\n\nstatic int n, m, q = 0;\nstatic vector u, v;\nstatic vector goal;\nstatic vector parent;\n\nstatic int find(int node) {\n\treturn (parent[node] == node ? node : parent[node] = find(parent[node]));\n}\n\nstatic bool merge(int v1, int v2) {\n\tv1 = find(v1);\n\tv2 = find(v2);\n\tif (v1 == v2)\n\t\treturn false;\n\tparent[v1] = v2;\n\treturn true;\n}\n\nstatic void wrong_answer() {\n\tprintf(\"lxndanfdiadsfnslkj_output_simurgh_faifnbsidjvnsidjbgsidjgbs\\n\");\n\tprintf(\"WA\\n\");\n\tprintf(\"NO\\n\");\n\texit(0);\n}\n\nstatic bool is_valid(const vector& r) {\n\tif(int(r.size()) != n - 1)\n\t\treturn false;\n\n\tfor(int i = 0; i < n - 1; i++)\n\t\tif(r[i] < 0 || r[i] >= m)\n\t\t\treturn false;\n\n\tparent.resize(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tparent[i] = i;\n\t}\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tif (!merge(u[r[i]], v[r[i]])) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nstatic int _count_common_roads_internal(const vector& r) {\n\tif (!is_valid(r))\n\t\twrong_answer();\n\n\tint common = 0;\n\tfor(int i = 0; i < n - 1; i++) {\n\t\tbool is_common = goal[r[i]];\n\t\tis_common = xored(goal, r[i]);\n\t\tif (is_common)\n\t\t\tcommon++;\n\t}\n\n\treturn common;\t\n}\n\nint count_common_roads(const vector& r) {\n\tq++;\n\tif(q > MAXQ)\n\t\twrong_answer();\n\n\treturn _count_common_roads_internal(r);\n}\n\nint main() {\n\t{\n\t\tchar secret[1000];\n\t\tassert(1 == scanf(\"%s\", secret));\n\t\tif ((string)\"wrslcnopzlckvxbnair_input_simurgh_lmncvpisadngpiqdfngslcnvd\" != string(secret)) {\n\t\t\tprintf(\"lxndanfdiadsfnslkj_output_simurgh_faifnbsidjvnsidjbgsidjgbs\\n\");\n\t\t\tprintf(\"SV\\n\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tassert(2 == scanf(\"%d %d\", &n, &m));\n\tassert(1 == scanf(\"%d\", &MAXQ));\n\n\tu.resize(m);\n\tv.resize(m);\n\n\tfor(int i = 0; i < m; i++)\n\t\tassert(2 == scanf(\"%d %d\", &u[i], &v[i]));\n\n\tgoal.resize(m, false);\n\n\tfor(int i = 0; i < n - 1; i++) {\n\t\tint id;\n\t\tassert(1 == scanf(\"%d\", &id));\n\t\tgoal[id] = true;\n\t}\n\n\tfor (int i = 0; i < m; i++) {\n\t\tgoal[i] = xored(goal, i);\n\t}\n\n\tvector result = find_roads(n, u, v);\n\n\tif(_count_common_roads_internal(result) != n - 1)\n\t\twrong_answer();\n\n\tprintf(\"lxndanfdiadsfnslkj_output_simurgh_faifnbsidjvnsidjbgsidjgbs\\n\");\n\tprintf(\"OK\\n\");\n\tfor(int i = 0; i < (int)result.size(); i++){\n\t\tif(i)\n\t\t\tprintf(\" \");\n\t\tprintf(\"%d\", result[i]);\n\t}\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\n", "simurgh.h": "#include \n\nstd::vector find_roads(int n, std::vector u, std::vector v);\nint count_common_roads(const std::vector& r);\n"}, "problem_json": {"name": "simurgh", "code": "simurgh", "title": "Simurgh", "type": "Batch", "time_limit": 2.0, "memory_limit": 1024, "description": "Simurgh - Finding Spanning Tree"}} {"problem_id": "ioi10_b", "cate": ["search", "math"], "difficulty": "hard", "cpu_time_limit_ms": 2000, "memory_limit_mb": 256, "description": "Jack and Jill play a game called Hotter, Colder. Jill has a number between $1$ and $N$, and Jack makes repeated attempts to guess it.\n\nEach of Jack's guesses is a number between $1$ and $N$. In response to each guess, Jill answers hotter, colder or same. For Jack's first guess, Jill answers same. For the remaining guesses Jill answers:\n\n* hotter if this guess is closer to Jill's number than his previous guess\n* colder if this guess is farther from Jill's number than his previous guess\n* same if this guess is neither closer to nor further from Jill's number than his previous guess.\n\nYou are to implement a procedure HC(N) that plays Jack's role. This implementation may repeatedly call Guess(G), with $G$ a number between $1$ and $N$. Guess(G) will return $1$ to indicate hotter, $-1$ to indicate colder or $0$ to indicate same. HC(N) must return Jill's number.\n\nAs example, assume $N=5$, and Jill has chosen the number $2$. When procedure HC makes the following sequence of calls to Guess, the results in the second column will be returned.\n\n| | | |\n| --- | --- | --- |\n| Call | Returned value | Explanation |\n| Guess(5) | 0 | Same (first call) |\n| Guess(3) | 1 | Hotter |\n| Guess(4) | -1 | Colder |\n| Guess(1) | 1 | Hotter |\n| Guess(3) | 0 | Same |\n\nAt this point Jack knows the answer, and HC should return $2$. It has taken Jack $5$ guesses to determine Jill's number. You can do better.\n\nScoring\n\nSubtask 1 [25 points]\n\nHC(N) must call Guess(G) at most $500$ times. There will be at most $125\\,250$ calls to HC(N), with N between $1$ and $500$.\n\nSubtask 2 [25 points]\n\nHC(N) must call Guess(G) at most $18$ times. There will be at most $125\\,250$ calls to HC(N), with N between $1$ and $500$.\n\nSubtask 3 [25 points]\n\nHC(N) must call Guess(G) at most $16$ times. There will be at most $125\\,250$ calls to HC(N), with N between $1$ and $500$.\n\nSubtask 4 [up to 25 points]\n\nLet $W$ be the largest integer, such that $2^W \\le 3 N$. For this subtask your solution will score:\n\n* $0$ points, if HC(N) calls Guess(G) $2W$ times or more\n* $25\\alpha$ points, where $\\alpha$ is the largest real number, such that $0 < \\alpha < 1$ and HC(N) calls Guess(G) at most $2W-\\alpha W$ times,\n* 25 points, if HC(N) calls Guess(G) at most $W$ times.\n\nThere will be at most $1\\,000\\,000$ calls to HC(N) with $N$ between $1$ and $500\\,000\\,000$.\n\nBe sure to initialize any variables used by HC every time it is called.", "interactor_files": {"grader.cpp": "#include \"grader.h\"\n#include \"hottercolder.h\"\n#include \n#include \n#include \n\nstatic int moves, TT, NN, prev = -1;\nint Guess(int x){\n int r;\n if (prev == -1 || abs(x-TT) == abs(prev-TT)) r = 0;\n else if (abs(x-TT) > abs(prev-TT)) r = -1;\n else r = 1;\n prev = x;\n if (x < 1 || x > NN) exit(92);\n moves++;\n return r;\n}\n\nint main(){\n int n=0,i,t,OK=0,sub1=0,sub2=0,sub3=0;\n double worst = 999999;\n while (2 == scanf(\"%d%d\",&NN,&TT)) {\n if (NN > n) n = NN;\n prev = -1;\n moves = 0;\n int h = HC(NN);\n if (h != TT) {\n exit(91);\n }\n int W = floor(0.00001+log(3*NN)/log(2));\n double alpha = 2 - (double)moves/W;\n if (alpha < worst) worst = alpha;\n // 1 means failure\n if ( NN <= 500 && moves > 500 ) exit(93);\n if ( NN <= 500 && moves > 18 ) sub2=1; \n if ( NN <= 500 && moves > 16 ) sub3=1;\n OK++;\n }\n if (!sub1) printf(\"OK 1\\n\");\n if (!sub2) printf(\"OK 2\\n\");\n if (!sub3) printf(\"OK 3\\n\");\n if (worst > 0) printf(\"OK 4 alpha %0.2lf\\n\",worst);\n return 0;\n}\n", "hottercolder.cpp": "#include \"grader.h\"\n\nint HC(int N){\n int g = Guess(1);\n int h = Guess(N);\n if (g == 0) return N/2;\n if (g < 0) return N/4;\n if (g > 0) return 3*N/4;\n}\n", "grader.h": "int Guess(int G);\n", "hottercolder.h": "int HC(int N);\n"}} {"problem_id": "ioi24_f", "cate": ["graph", "search"], "difficulty": "hard", "cpu_time_limit_ms": 2000, "memory_limit_mb": 1024, "description": "The Great Sphinx has a riddle for you. You are given a graph on $N$ vertices. The vertices are numbered from $0$ to $N - 1$. There are $M$ edges in the graph, numbered from $0$ to $M-1$. Each edge connects a pair of distinct vertices and is bidirectional. Specifically, for each $j$ from $0$ to $M - 1$ (inclusive) edge $j$ connects vertices $X[j]$ and $Y[j]$. There is at most one edge connecting any pair of vertices. Two vertices are called adjacent if they are connected by an edge.\n\nA sequence of vertices $v_0, v_1, \\ldots, v_k$ (for $k \\ge 0$) is called a path if each two consecutive vertices $v_l$ and $v_{l+1}$ (for each $l$ such that $0 \\le l < k$) are adjacent. We say that a path $v_0, v_1, \\ldots, v_k$ connects vertices $v_0$ and $v_k$. In the graph given to you, each pair of vertices is connected by some path.\n\nThere are $N + 1$ colours, numbered from $0$ to $N$. Colour $N$ is special and is called the Sphinx's colour. Each vertex is assigned a colour. Specifically, vertex $i$ ($0 \\le i < N$) has colour $C[i]$. Multiple vertices may have the same colour, and there might be colours not assigned to any vertex. No vertex has the Sphinx's colour, that is, $0 \\le C[i] < N$ ($0 \\le i < N$).\n\nA path $v_0, v_1, \\ldots, v_k$ (for $k \\ge 0$) is called monochromatic if all of its vertices have the same colour, i.e. $C[v_l] = C[v_{l+1}]$ (for each $l$ such that $0 \\le l < k$). Additionally, we say that vertices $p$ and $q$ ($0 \\le p < N$, $0 \\le q < N$) are in the same monochromatic component if and only if they are connected by a monochromatic path.\n\nYou know the vertices and edges, but you do not know which colour each vertex has. You want to find out the colours of the vertices, by performing recolouring experiments.\n\nIn a recolouring experiment, you may recolour arbitrarily many vertices. Specifically, to perform a recolouring experiment you first choose an array $E$ of size $N$, where for each $i$ ($0 \\le i < N$), $E[i]$ is between $-1$ and $N$ inclusive. Then, the colour of each vertex $i$ becomes $S[i]$, where the value of $S[i]$ is:\n\n* $C[i]$, that is, the original colour of $i$, if $E[i] = -1$, or\n* $E[i]$, otherwise.\n\nNote that this means that you can use the Sphinx's colour in your recolouring.\n\nFinally, the Great Sphinx announces the number of monochromatic components in the graph, after setting the colour of each vertex $i$ to $S[i]$ ($0 \\le i < N$). The new colouring is applied only for this particular recolouring experiment, so the colours of all vertices return to the original ones after the experiment finishes.\n\nYour task is to identify the colours of the vertices in the graph by performing at most $2\\,750$ recolouring experiments. You may also receive a partial score if you correctly determine for every pair of adjacent vertices, whether they have the same colour.\n\nImplementation Details\n\nYou should implement the following procedure.\n\n```\nstd::vector find_colours(int N, \n std::vector X, std::vector Y)\n```\n\n* $N$: the number of vertices in the graph.\n* $X$, $Y$: arrays of length $M$ describing the edges.\n* This procedure should return an array $G$ of length $N$, representing the colours of vertices in the graph.\n* This procedure is called exactly once for each test case.\n\nThe above procedure can make calls to the following procedure to perform recolouring experiments:\n\nint perform\\_experiment(std::vector E)\n\n* $E$: an array of length $N$ specifying how vertices should be recoloured.\n* This procedure returns the number of monochromatic components after recolouring the vertices according to $E$.\n* This procedure can be called at most $2\\,750$ times.\n\nThe grader is not adaptive, that is, the colours of the vertices are fixed before a call to find\\_colours is made.\n\nInput\n\nThe sample grader reads in the following format:\n\n* line $1$: $N$ $M$ ($2 \\le N \\le 250$, $N - 1 \\le M \\le \\frac{N \\cdot (N - 1)}{2}$)\n* line $2$ $C[1]\\ldots C[N-1]$ ($0 \\le C[i] < N$)\n* line $3 + j$ ($0 \\le j \\le M - 1$): $X[j]$ $Y[j]$ ($0 \\le X[j] < Y[j] < N$)\n\n$X[j] \\neq X[k]$ or $Y[j] \\neq Y[k]$ for each $j$ and $k$ such that $0 \\le j < k < M$.\n\nEach pair of vertices is connected by some path.\n\nOutput\n\nThe sample grader prints $S$ lines, in the following format:\n\n* line $1$: $L$ $Q$\n* line $2$: $G[0]\\; G[1]\\ldots G[L-1]$\n\nHere, $L$ is the length of the array $G$ returned by find\\_colours, and $Q$ is the number of calls to perform\\_experiment.\n\nScoring\n\n| | | |\n| --- | --- | --- |\n| Subtask | Points | Additional Input Constraints |\n| 1 | 3 | $N = 2$ |\n| 2 | 7 | $N \\le 50$ |\n| 3 | 33 | The graph is a path: $M = N - 1$ and vertices $j$ and $j+1$ are adjacent ($0 \\leq j < M$). |\n| 4 | 21 | The graph is complete: $M = \\frac{N \\cdot (N - 1)}{2}$ and any two vertices are adjacent. |\n| 5 | 36 | No additional constraints. |\n\nIn each subtask, you can obtain a partial score if your program determines correctly for every pair of adjacent vertices whether they have the same colour.\n\nMore precisely, you get the whole score of a subtask if in all of its test cases, the array $G$ returned by find\\_colours is exactly the same as array $C$ (i.e. $G[i] = C[i]$ for all $i$ such that $0 \\le i < N$). Otherwise, you get $50\\%$ of the score for a subtask if the following conditions hold in all of its test cases:\n\n* $0 \\le G[i] < N$ for each $i$ such that $0 \\le i < N$;\n* For each $j$ such that $0 \\le j < M$:\n + $G[X[j]] = G[Y[j]]$ if and only if $C[X[j]] = C[Y[j]]$.\n\nNote\n\nConsider the following call.\n\nfind\\_colours(4, [0, 1, 0, 0], [1, 2, 2, 3])\n\nFor this example, suppose that the (hidden) colours of the vertices are given by $C = [2, 0, 0, 0]$. This scenario is shown in the following figure. Colours are additionally represented by numbers on white labels attached to each vertex.\n\n![](https://ioi.contest.codeforces.com/espresso/e93387951f9ee5c19b243d8637177805e3fb87f3.png)\n\nThe procedure may call perform\\_experiment as follows.\n\nperform\\_experiment([-1, -1, -1, -1])\n\nIn this call, no vertex is recoloured, as all vertices keep their original colours.\n\nConsider vertex $1$ and vertex $2$. They both have colour $0$ and the path $1, 2$ is a monochromatic path. As a result, vertices $1$ and $2$ are in the same monochromatic component.\n\nConsider vertex $1$ and vertex $3$. Even though both of them have colour $0$, they are in different monochromatic components as there is no monochromatic path connecting them.\n\nOverall, there are $3$ monochromatic components, with vertices $\\{0\\}$, $\\{1, 2\\}$, and $\\{3\\}$. Thus, this call returns $3$.\n\nNow the procedure may call perform\\_experiment as follows.\n\nperform\\_experiment([0, -1, -1, -1])\n\nIn this call, only vertex $0$ is recoloured to colour $0$, which results in the colouring shown in the following figure.\n\n![](https://ioi.contest.codeforces.com/espresso/a92f269d0a4a50727fc7cdbf92bcd6827b181a69.png)\n\nThis call returns $1$, as all the vertices belong to the same monochromatic component. We can now deduce that vertices $1$, $2$, and $3$ have colour $0$.\n\nThe procedure may then call perform\\_experiment as follows.\n\nperform\\_experiment([-1, -1, -1, 2])\n\nIn this call, vertex $3$ is recoloured to colour $2$, which results in the colouring shown in the following figure.\n\n![](https://ioi.contest.codeforces.com/espresso/bf9848cfefe18dd50b3afc559ae073841d1ea415.png)\n\nThis call returns $2$, as there are $2$ monochromatic components, with vertices $\\{0, 3\\}$ and $\\{1, 2\\}$ respectively. We can deduce that vertex $0$ has colour $2$.\n\nThe procedure find\\_colours then returns the array $[2, 0, 0, 0]$. Since $C = [2, 0, 0, 0]$, full score is given.\n\nNote that there are also multiple return values, for which $50\\%$ of the score would be given, for example $[1, 2, 2, 2]$ or $[1, 2, 2, 3]$.", "interactor_files": {"manager.cpp": "#include \"testlib.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n/******************************** Begin testlib-related material ********************************/\n\ninline FILE* openFile(const char* name, const char* mode) {\n\tFILE* file = fopen(name, mode);\n\tif (!file)\n\t\tquitf(_fail, \"Could not open file '%s' with mode '%s'.\", name, mode);\n\tcloseOnHalt(file);\n\treturn file;\n}\n\n\nvector mgr2sol, sol2mgr;\nFILE* log_file = nullptr;\n\nvoid nullifyFile(int idx) {\n\tmgr2sol[idx] = sol2mgr[idx] = nullptr;\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid log_printf(const char* fmt, ...) {\n\tif (log_file) {\n\t\tFMT_TO_RESULT(fmt, fmt, message);\n\t\tfprintf(log_file, \"%s\", message.c_str());\n\t\tfflush(log_file);\n\t}\n}\n\nvoid registerManager(std::string probName, int num_processes, int argc, char* argv[]) {\n\tsetName(\"manager for problem %s\", probName.c_str());\n\t__testlib_ensuresPreconditions();\n\ttestlibMode = _checker;\n\trandom_t::version = 1; // Random generator version\n\t__testlib_set_binary(stdin);\n\touf.mode = _output;\n\n\t{//Keep alive on broken pipes\n\t\t//signal(SIGPIPE, SIG_IGN);\n\t\tstruct sigaction sa;\n\t\tsa.sa_handler = SIG_IGN;\n\t\tsigaction(SIGPIPE, &sa, NULL);\n\t}\n\n\tint required_args = 1 + 2 * num_processes;\n\tif (argc < required_args || required_args+1 < argc) {\n\t\tstring usage = format(\"'%s'\", argv[0]);\n\t\tfor (int i = 0; i < num_processes; i++)\n\t\t\tusage += format(\" sol%d-to-mgr mgr-to-sol%d\", i, i);\n\t\tusage += \" [mgr_log] < input-file\";\n\t\tquitf(_fail,\n\t\t\t\"Manager for problem %s:\\n\"\n\t\t\t\"Invalid number of arguments: %d\\n\"\n\t\t\t\"Usage: %s\",\n\t\t\tprobName.c_str(), argc-1, usage.c_str());\n\t}\n\n\tinf.init(stdin, _input);\n\tcloseOnHalt(stdout);\n\tcloseOnHalt(stderr);\n\n\tmgr2sol.resize(num_processes);\n\tsol2mgr.resize(num_processes);\n\tfor (int i = 0; i < num_processes; i++) {\n\t\tmgr2sol[i] = openFile(argv[1 + 2*i + 1], \"a\");\n\t\tsol2mgr[i] = openFile(argv[1 + 2*i + 0], \"r\");\n\t}\n\n\tif (argc > required_args) {\n\t\tlog_file = openFile(argv[required_args], \"w\");\n\t} else {\n\t\tlog_file = nullptr;\n\t}\n}\n/********************************* End testlib-related material *********************************/\n\n\n// utils\n\n#define rep(i, n) for(int i = 0, i##__n = (int)(n); i < i##__n; ++i)\n\ntemplate int sz(const C& c) { return std::size(c); }\n\n#define log_var(var_name) log_printf(\"%s = %s\\n\", #var_name, toString(var_name).c_str());\n\ntemplate\nvoid log_array(const C& c, string delim=\" \", string ending=\"\\n\") {\n\tstring d = \"\";\n\tfor (const auto& x : c) {\n\t\tlog_printf(\"%s%s\", d.c_str(), toString(x).c_str());\n\t\td = delim;\n\t}\n\tlog_printf(\"%s\", ending.c_str());\n}\n\n\n// grader/manager protocol\n\nconst int secret_g2m = 0x34508C80;\nconst int secret_m2g = 0x75EC8020;\nconst int code_mask = 0x0000000F;\n\nconst int M2G_CODE__OK = 0;\nconst int M2G_CODE__DIE = 1;\n\nconst int G2M_CODE__OK_NEW_EXPERIMENT = 0;\nconst int G2M_CODE__OK_END_OF_EXPERIMENTS = 1;\nconst int G2M_CODE__INVALID_E_LENGTH = 2;\nconst int G2M_CODE__INVALID_G_LENGTH = 3;\nconst int G2M_CODE__PV_CALL_EXIT = 13;\nconst int G2M_CODE__PV_TAMPER_M2G = 14;\nconst int G2M_CODE__SILENT = 15;\n\nint fifo_idx = 0;\n\nenum class ActionMode {\n\tok_new_experiment,\n\tok_end_of_experiments,\n} ok_action_mode;\n\nvoid out_flush() {\n\tfflush(mgr2sol[fifo_idx]);\n}\n\nvoid write_int(int x) {\n\tif(1 > fprintf(mgr2sol[fifo_idx], \"%d\\n\", x)) {\n\t\tnullifyFile(fifo_idx);\n\t\tlog_printf(\"Could not write int to mgr2sol[%d]\\n\", fifo_idx);\n\t}\n}\n\nvoid write_secret(int m2g_code = M2G_CODE__OK) {\n\twrite_int(secret_m2g | m2g_code);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void die(TResult result, const char* format, ...) {\n\tFMT_TO_RESULT(format, format, message);\n\tlog_printf(\"Dying with message '%s'\\n\", message.c_str());\n\trep(i, sz(mgr2sol))\n\t\tif(mgr2sol[i] != nullptr) {\n\t\t\tfifo_idx = i;\n\t\t\tlog_printf(\"Sending secret with code DIE to mgr2sol[%d]\\n\", fifo_idx);\n\t\t\twrite_secret(M2G_CODE__DIE);\n\t\t\tout_flush();\n\t\t}\n\tlog_printf(\"Quitting with result code %d\\n\", int(result));\n\tquit(result, message);\n}\n\nNORETURN void die_invalid_argument(const string &msg) {\n\tRESULT_MESSAGE_WRONG += \": Invalid argument\";\n\tdie(_wa, \"%s\", msg.c_str());\n}\n\nNORETURN void die_too_many_calls(const string &msg) {\n\tRESULT_MESSAGE_WRONG += \": Too many calls\";\n\tdie(_wa, \"%s\", msg.c_str());\n}\n\nint read_int() {\n\tint x;\n\tif(1 != fscanf(sol2mgr[fifo_idx], \"%d\", &x)) {\n\t\tnullifyFile(fifo_idx);\n\t\tdie(_fail, \"Could not read int from sol2mgr[%d]\", fifo_idx);\n\t}\n\treturn x;\n}\n\nvector read_int_vector(int len) {\n\tvector v(len);\n\trep(i, len)\n\t\tv[i] = read_int();\n\treturn v;\n}\n\nvoid read_secret() {\n\tint secret = read_int();\n\tif((secret & ~code_mask) != secret_g2m)\n\t\tdie(_pv, \"Possible tampering with sol2mgr[%d]\", fifo_idx);\n\tint g2m_code = secret & code_mask;\n\tswitch (g2m_code) {\n\t\tcase G2M_CODE__OK_NEW_EXPERIMENT:\n\t\t\tok_action_mode = ActionMode::ok_new_experiment;\n\t\t\treturn;\n\t\tcase G2M_CODE__OK_END_OF_EXPERIMENTS:\n\t\t\tok_action_mode = ActionMode::ok_end_of_experiments;\n\t\t\treturn;\n\t\tcase G2M_CODE__INVALID_E_LENGTH:\n\t\t\tdie_invalid_argument(\"Invalid length of E\");\n\t\tcase G2M_CODE__INVALID_G_LENGTH:\n\t\t\tdie(_wa, \"Invalid length of G\");\n\t\tcase G2M_CODE__SILENT:\n\t\t\tdie(_fail, \"Unexpected g2m_code SILENT from sol2mgr[%d]\", fifo_idx);\n\t\tcase G2M_CODE__PV_TAMPER_M2G:\n\t\t\tdie(_pv, \"Possible tampering with mgr2sol[%d]\", fifo_idx);\n\t\tcase G2M_CODE__PV_CALL_EXIT:\n\t\t\tdie(_pv, \"Solution[%d] called exit()\", fifo_idx);\n\t\tdefault:\n\t\t\tdie(_fail, \"Unknown g2m_code %d from sol2mgr[%d]\", g2m_code, fifo_idx);\n\t}\n}\n\n\n// problem logic\n\nconst int CALLS_CNT_LIMIT = 2750;\n\nint calls_cnt;\n\nint N, M;\nstd::vector> adj;\n\nint count_components(const std::vector& S) {\n\tint components_cnt = 0;\n\tstd::vector vis(N, false);\n\tfor (int i = 0; i < N; i++) {\n\t\tif (vis[i])\n\t\t\tcontinue;\n\t\tcomponents_cnt++;\n\n\t\tstd::queue q;\n\t\tvis[i] = true;\n\t\tq.push(i);\n\t\twhile (!q.empty()) {\n\t\t\tint cur = q.front();\n\t\t\tq.pop();\n\t\t\tfor (int nxt : adj[cur])\n\t\t\t\tif (!vis[nxt] && S[nxt] == S[cur]) {\n\t\t\t\t\tvis[nxt] = true;\n\t\t\t\t\tq.push(nxt);\n\t\t\t\t}\n\t\t}\n\t}\n\treturn components_cnt;\n}\n\nint main(int argc, char *argv[]) {\n\tregisterManager(\"sphinx\", 1, argc, argv);\n\n\t// read input\n\tN = inf.readInt();\n\tM = inf.readInt();\n\tstd::vector C(N);\n\trep(i, N)\n\t\tC[i] = inf.readInt();\n\tstd::vector X(M), Y(M);\n\trep(j, M)\n\t\tX[j] = inf.readInt(), Y[j] = inf.readInt();\n\n\tadj.assign(N, vector());\n\trep(j, M) {\n\t\tadj[X[j]].push_back(Y[j]);\n\t\tadj[Y[j]].push_back(X[j]);\n\t}\n\n\twrite_secret();\n\twrite_int(N);\n\twrite_int(M);\n\trep(j, M)\n\t\twrite_int(X[j]), write_int(Y[j]);\n\tout_flush();\n\n\tcalls_cnt = 0;\n\twhile (true) {\n\t\tread_secret();\n\t\tif (ok_action_mode != ActionMode::ok_new_experiment) break;\n\n\t\tstd::vector E = read_int_vector(N);\n\n\t\tcalls_cnt++;\n\t\tif (calls_cnt > CALLS_CNT_LIMIT)\n\t\t\tdie_too_many_calls(\"#experiments reached \" + to_string(calls_cnt));\n\n\t\trep(i, N)\n\t\t\tif (!(-1 <= E[i] && E[i] <= N))\n\t\t\t\tdie_invalid_argument(\"Invalid value of E[\" + to_string(i) + \"]: \" + to_string(E[i]));\n\n\t\tvector S(N);\n\t\trep(i, N)\n\t\t\tS[i] = (E[i] == -1 ? C[i] : E[i]);\n\t\tint P = count_components(S);\n\n\t\twrite_secret();\n\t\twrite_int(P);\n\t\tout_flush();\n\t}\n\tensuref(ok_action_mode == ActionMode::ok_end_of_experiments, \"Expected action code ok_end_of_experiments\");\n\tlog_printf(\"End of experiments.\\n\");\n\n\tstd::vector G = read_int_vector(N);\n\n\t// Scoring\n\tif (C == G)\n\t\tquitf(_ok, \"#experiments: %d\", calls_cnt);\n\n\trep(i, N)\n\t\tif (!(0 <= G[i] && G[i] < N))\n\t\t\tquitf(_wa, \"Invalid value of G[%d]: %d\", i, G[i]);\n\n\trep(j, M) {\n\t\tint x = X[j], y = Y[j];\n\t\tif (C[x] == C[y] && !(G[x] == G[y]))\n\t\t\tquitf(_wa, \"Vertices %d and %d do have the same color, but they do not in returned answer\", x, y);\n\t\tif (C[x] != C[y] && !(G[x] != G[y]))\n\t\t\tquitf(_wa, \"Vertices %d and %d do not have the same color, but they do in returned answer\", x, y);\n\t}\n\tquitp(50 / 100.0);\n}\n", "stub.cpp": "#include \"sphinx.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\n\nnamespace {\n\n/******************************** Begin testlib-related material ********************************/\n#ifdef _MSC_VER\n# define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n# define NORETURN __attribute__ ((noreturn))\n#else\n# define NORETURN\n#endif\n/********************************* End testlib-related material *********************************/\n\n\n// utils\n\n#define rep(i, n) for(int i = 0, i##__n = (int)(n); i < i##__n; ++i)\n\ntemplate int sz(const C& c) { return std::size(c); }\n\n\n// grader/manager protocol\n\nconst int secret_g2m = 0x34508C80;\nconst int secret_m2g = 0x75EC8020;\nconst int code_mask = 0x0000000F;\n\nconst int M2G_CODE__OK = 0;\n\nconst int G2M_CODE__OK_NEW_EXPERIMENT = 0;\nconst int G2M_CODE__OK_END_OF_EXPERIMENTS = 1;\nconst int G2M_CODE__INVALID_E_LENGTH = 2;\nconst int G2M_CODE__INVALID_G_LENGTH = 3;\nconst int G2M_CODE__PV_CALL_EXIT = 13;\nconst int G2M_CODE__PV_TAMPER_M2G = 14;\nconst int G2M_CODE__SILENT = 15;\n\n\nbool exit_allowed = false;\n\nNORETURN void authorized_exit(int exit_code) {\n exit_allowed = true;\n exit(exit_code);\n}\n\n\nFILE* fin = stdin;\nFILE* fout = stdout;\n\nvoid out_flush() {\n\tfflush(fout);\n}\n\nvoid write_int(int x) {\n\tif(1 > fprintf(fout, \"%d\\n\", x)) {\n\t\tfprintf(stderr, \"Could not write int to fout\\n\");\n\t\tauthorized_exit(3);\n\t}\n}\n\nvoid write_int_vector(const vector& v) {\n\trep(i, sz(v))\n\t\twrite_int(v[i]);\n}\n\nvoid write_secret(int g2m_code) {\n\twrite_int(secret_g2m | g2m_code);\n}\n\nNORETURN void die(int g2m_code) {\n\tif(g2m_code == G2M_CODE__OK_NEW_EXPERIMENT || g2m_code == G2M_CODE__OK_END_OF_EXPERIMENTS) {\n\t\tfprintf(stderr, \"Shall not die with code OK\\n\");\n\t\tauthorized_exit(5);\n\t}\n\tfprintf(stderr, \"Dying with code %d\\n\", g2m_code);\n\tif(g2m_code != G2M_CODE__SILENT)\n\t\twrite_secret(g2m_code);\n\tfclose(fin);\n\tfclose(fout);\n\tauthorized_exit(0);\n}\n\nint read_int() {\n\tint x;\n\tif(1 != fscanf(fin, \"%d\", &x)) {\n\t\tfprintf(stderr, \"Could not read int from fin\\n\");\n\t\tauthorized_exit(3);\n\t}\n\treturn x;\n}\n\nvoid read_secret() {\n\tint secret = read_int();\n\tif((secret & ~code_mask) != secret_m2g)\n\t\tdie(G2M_CODE__PV_TAMPER_M2G);\n\tint m2g_code = secret & code_mask;\n\tif(m2g_code != M2G_CODE__OK)\n\t\tdie(G2M_CODE__SILENT);\n}\n\nvoid check_exit_protocol() {\n if (!exit_allowed)\n die(G2M_CODE__PV_CALL_EXIT);\n}\n\n\n// problem logic\n\nint N;\n\n} // namespace\n\n\nint perform_experiment(std::vector E) {\n\tif (sz(E) != N) die(G2M_CODE__INVALID_E_LENGTH);\n\twrite_secret(G2M_CODE__OK_NEW_EXPERIMENT);\n\twrite_int_vector(E);\n\tout_flush();\n\n\tread_secret();\n\tint P = read_int();\n\treturn P;\n}\n\nint main() {\n\tsignal(SIGPIPE, SIG_IGN);\n\tatexit(check_exit_protocol);\n\tat_quick_exit(check_exit_protocol);\n\n\tread_secret();\n\tN = read_int();\n\tint M = read_int();\n\tstd::vector X(M), Y(M);\n\trep(j, M)\n\t\tX[j] = read_int(), Y[j] = read_int();\n\n\tstd::vector G = find_colours(N, X, Y);\n\n\tif (sz(G) != N) die(G2M_CODE__INVALID_G_LENGTH);\n\n\twrite_secret(G2M_CODE__OK_END_OF_EXPERIMENTS);\n\twrite_int_vector(G);\n\tout_flush();\n\n\texit_allowed = true;\n\treturn 0;\n}\n", "sphinx.h": "#include \n\nstd::vector find_colours(int N, std::vector X, std::vector Y);\n\nint perform_experiment(std::vector E);\n", "testlib.h": "/* \n * It is strictly recommended to include \"testlib.h\" before any other include \n * in your code. In this case testlib overrides compiler specific \"random()\".\n *\n * If you can't compile your code and compiler outputs something about \n * ambiguous call of \"random_shuffle\", \"rand\" or \"srand\" it means that \n * you shouldn't use them. Use \"shuffle\", and \"rnd.next()\" instead of them\n * because these calls produce stable result for any C++ compiler. Read \n * sample generator sources for clarification.\n *\n * Please read the documentation for class \"random_t\" and use \"rnd\" instance in\n * generators. Probably, these sample calls will be usefull for you:\n * rnd.next(); rnd.next(100); rnd.next(1, 2); \n * rnd.next(3.14); rnd.next(\"[a-z]{1,100}\").\n *\n * Also read about wnext() to generate off-center random distribution.\n *\n * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker.\n */\n\n#ifndef _TESTLIB_H_\n#define _TESTLIB_H_\n\n/*\n * Copyright (c) 2005-2018\n */\n\n#define VERSION \"0.9.21\"\n\n/* \n * Mike Mirzayanov\n *\n * This material is provided \"as is\", with absolutely no warranty expressed\n * or implied. Any use is at your own risk.\n *\n * Permission to use or copy this software for any purpose is hereby granted \n * without fee, provided the above notices are retained on all copies.\n * Permission to modify the code and to distribute modified code is granted,\n * provided the above notices are retained, and a notice that the code was\n * modified is included with the above copyright notice.\n *\n */\n\n/*\n * Kian Mirjalali:\n *\n * Modified to be compatible with CMS & requirements for preparing IOI tasks\n *\n * * defined FOR_LINUX in order to force linux-based line endings in validators.\n *\n * * Changed the ordering of checker arguments\n * from \n * to \n *\n * * Added \"Security Violation\" & \"Protocol Violation\" as new result types.\n *\n * * Changed checker quit behaviors to make it compliant with CMS.\n *\n * * The checker exit codes should always be 0 in CMS.\n *\n * * For partial scoring, forced quitp() functions to accept only scores in the range [0,1].\n * If the partial score is less than 1e-5, it becomes 1e-5, because 0 grades are considered wrong in CMS.\n * Grades in range [1e-5, 0.0001) are printed exactly (to prevent rounding to zero).\n * Grades in [0.0001, 1] are printed with 4 digits after decimal point.\n *\n * * Added the following utility types/variables/functions/methods:\n * type HaltListener (as a function with no parameters or return values)\n * vector __haltListeners\n * void registerHaltListener(HaltListener haltListener)\n * void callHaltListeners() (which is called in quit)\n * void closeOnHalt(FILE* file)\n * void closeOnHalt(F& f) (template using f.close())\n * void InStream::readSecret(string secret, TResult mismatchResult, string mismatchMessage, string eofMessage)\n * void InStream::readGraderResult()\n * +supporting conversion of graderResult to CMS result\n * void quitp(double), quitp(int)\n * void registerChecker(string probName, argc, argv)\n * void readBothSecrets(string secret)\n * void readBothGraderResults()\n * void quit(TResult)\n * bool compareTokens(string a, string b, char separator=' ')\n * void compareRemainingLines(int lineNo=1)\n * void skip_ok()\n *\n */\n\n/* NOTE: This file contains testlib library for C++.\n *\n * Check, using testlib running format:\n * check.exe [ [-appes]],\n * If result file is specified it will contain results.\n *\n * Validator, using testlib running format: \n * validator.exe < input.txt,\n * It will return non-zero exit code and writes message to standard output.\n *\n * Generator, using testlib running format: \n * gen.exe [parameter-1] [parameter-2] [... paramerter-n]\n * You can write generated test(s) into standard output or into the file(s).\n *\n * Interactor, using testlib running format: \n * interactor.exe [ [ [-appes]]],\n * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],\n * can be judged by checker later), reads program output from ouf (mapped to stdin),\n * writes output to program via stdout (use cout, printf, etc).\n */\n\nconst char* latestFeatures[] = {\n \"Fixed stringstream repeated usage issue\",\n \"Fixed compilation in g++ (for std=c++03)\",\n \"Batch of println functions (support collections, iterator ranges)\",\n \"Introduced rnd.perm(size, first = 0) to generate a `first`-indexed permutation\",\n \"Allow any whitespace in readInts-like functions for non-validators\",\n \"Ignore 4+ command line arguments ifdef EJUDGE\",\n \"Speed up of vtos\",\n \"Show line number in validators in case of incorrect format\",\n \"Truncate huge checker/validator/interactor message\",\n \"Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type\",\n \"Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type\",\n \"Fixed compilation in VS 2015+\",\n \"Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines\",\n \"Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals\",\n \"Introduced split/tokenize functions to separate string by given char\",\n \"Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long paramerters\",\n \"Supported --testOverviewLogFileName for validator: bounds hits + features\",\n \"Fixed UB (sequence points) in random_t\",\n \"POINTS_EXIT_CODE returned back to 7 (instead of 0)\",\n \"Removed disable buffers for interactive problems, because it works unexpectedly in wine\",\n \"InStream over string: constructor of InStream from base InStream to inherit policies and std::string\",\n \"Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \\\"[n=%d,m=%d]\\\", n, m)\",\n \"Fixed incorrect interval parsing in patterns\",\n \"Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)\",\n \"Introduced disableFinalizeGuard() to switch off finalization checkings\",\n \"Use join() functions to format a range of items as a single string (separated by spaces or other separators)\",\n \"Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors\",\n \"Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7\",\n \"Fixed bug with nan in stringToDouble\", \n \"Fixed issue around overloads for size_t on x64\", \n \"Added attribute 'points' to the XML output in case of result=_points\", \n \"Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14\", \n \"Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading\", \n \"Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()\", \n \"Manual buffer in InStreams, some IO speed improvements\", \n \"Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true\", \n \"Introduced guard against missed quitf() in checker or readEof() in validators\", \n \"Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers\", \n \"Supported registerInteraction(argc, argv)\", \n \"Print checker message to the stderr instead of stdout\", \n \"Supported TResult _points to output calculated score, use quitp(...) functions\", \n \"Fixed to be compilable on Mac\", \n \"PC_BASE_EXIT_CODE=50 in case of defined TESTSYS\",\n \"Fixed issues 19-21, added __attribute__ format printf\", \n \"Some bug fixes\", \n \"ouf.readInt(1, 100) and similar calls return WA\", \n \"Modified random_t to avoid integer overflow\", \n \"Truncated checker output [patch by Stepan Gatilov]\", \n \"Renamed class random -> class random_t\", \n \"Supported name parameter for read-and-validation methods, like readInt(1, 2, \\\"n\\\")\", \n \"Fixed bug in readDouble()\", \n \"Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()\", \n \"Supported \\\"partially correct\\\", example: quitf(_pc(13), \\\"result=%d\\\", result)\", \n \"Added shuffle(begin, end), use it instead of random_shuffle(begin, end)\", \n \"Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode\", \n \"Package extended with samples of generators and validators\", \n \"Written the documentation for classes and public methods in testlib.h\",\n \"Implemented random routine to support generators, use registerGen() to switch it on\",\n \"Implemented strict mode to validate tests, use registerValidation() to switch it on\",\n \"Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output\",\n \"Added InStream::readLong() and removed InStream::readLongint()\",\n \"Now no footer added to each report by default (use directive FOOTER to switch on)\",\n \"Now every checker has a name, use setName(const char* format, ...) to set it\",\n \"Now it is compatible with TTS (by Kittens Computing)\",\n \"Added \\'ensure(condition, message = \\\"\\\")\\' feature, it works like assert()\",\n \"Fixed compatibility with MS C++ 7.1\",\n \"Added footer with exit code information\",\n \"Added compatibility with EJUDGE (compile with EJUDGE directive)\",\n \"Added compatibility with Contester (compile with CONTESTER directive)\"\n };\n\n#define FOR_LINUX\n\n#ifdef _MSC_VER\n#define _CRT_SECURE_NO_DEPRECATE\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_NO_VA_START_VALIDATION\n#endif\n\n/* Overrides random() for Borland C++. */\n#define random __random_deprecated\n#include \n#include \n#include \n#include \n#undef random\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ || __CYGWIN__ )\n# if !defined(_MSC_VER) || _MSC_VER>1400\n# define NOMINMAX 1\n# include \n# else\n# define WORD unsigned short\n# include \n# endif\n# include \n# define ON_WINDOWS\n# if defined(_MSC_VER) && _MSC_VER>1400\n# pragma warning( disable : 4127 )\n# pragma warning( disable : 4146 )\n# pragma warning( disable : 4458 )\n# endif\n#else\n# define WORD unsigned short\n# include \n#endif\n\n#if defined(FOR_WINDOWS) && defined(FOR_LINUX)\n#error Only one target system is allowed\n#endif\n\n#ifndef LLONG_MIN\n#define LLONG_MIN (-9223372036854775807LL - 1)\n#endif\n\n#ifndef ULLONG_MAX\n#define ULLONG_MAX (18446744073709551615)\n#endif\n\n#define LF ((char)10)\n#define CR ((char)13)\n#define TAB ((char)9)\n#define SPACE ((char)' ')\n#define EOFC (255)\n\n#ifndef OK_EXIT_CODE\n# ifdef CONTESTER\n# define OK_EXIT_CODE 0xAC\n# else\n# define OK_EXIT_CODE 0\n# endif\n#endif\n\n#ifndef WA_EXIT_CODE\n# ifdef EJUDGE\n# define WA_EXIT_CODE 5\n# elif defined(CONTESTER)\n# define WA_EXIT_CODE 0xAB\n# else\n# define WA_EXIT_CODE 1\n# endif\n#endif\n\n#ifndef PE_EXIT_CODE\n# ifdef EJUDGE\n# define PE_EXIT_CODE 4\n# elif defined(CONTESTER)\n# define PE_EXIT_CODE 0xAA\n# else\n# define PE_EXIT_CODE 2\n# endif\n#endif\n\n#ifndef FAIL_EXIT_CODE\n# ifdef EJUDGE\n# define FAIL_EXIT_CODE 6\n# elif defined(CONTESTER)\n# define FAIL_EXIT_CODE 0xA3\n# else\n# define FAIL_EXIT_CODE 3\n# endif\n#endif\n\n#ifndef DIRT_EXIT_CODE\n# ifdef EJUDGE\n# define DIRT_EXIT_CODE 6\n# else\n# define DIRT_EXIT_CODE 4\n# endif\n#endif\n\n#ifndef POINTS_EXIT_CODE\n# define POINTS_EXIT_CODE 7\n#endif\n\n#ifndef UNEXPECTED_EOF_EXIT_CODE\n# define UNEXPECTED_EOF_EXIT_CODE 8\n#endif\n\n#ifndef SV_EXIT_CODE\n# define SV_EXIT_CODE 20\n#endif\n\n#ifndef PV_EXIT_CODE\n# define PV_EXIT_CODE 21\n#endif\n\n#ifndef PC_BASE_EXIT_CODE\n# ifdef TESTSYS\n# define PC_BASE_EXIT_CODE 50\n# else\n# define PC_BASE_EXIT_CODE 0\n# endif\n#endif\n\n#ifdef __GNUC__\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused))\n#else\n# define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1]\n#endif\n\n#ifdef ON_WINDOWS\n#define I64 \"%I64d\"\n#define U64 \"%I64u\"\n#else\n#define I64 \"%lld\"\n#define U64 \"%llu\"\n#endif\n\n#ifdef _MSC_VER\n# define NORETURN __declspec(noreturn)\n#elif defined __GNUC__\n# define NORETURN __attribute__ ((noreturn))\n#else\n# define NORETURN\n#endif\n\n/**************** HaltListener material ****************/\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntypedef std::function HaltListener;\n#else\ntypedef void (*HaltListener)();\n#endif\n\nstd::vector __haltListeners;\n\ninline void registerHaltListener(HaltListener haltListener) {\n __haltListeners.push_back(haltListener);\n}\n\ninline void callHaltListeners() {\n // Removing and calling haltListeners in reverse order.\n while (!__haltListeners.empty()) {\n HaltListener haltListener = __haltListeners.back();\n __haltListeners.pop_back();\n haltListener();\n }\n}\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ninline void closeOnHalt(FILE* file) {\n registerHaltListener([file] { fclose(file); });\n}\ntemplate\ninline void closeOnHalt(F& f) {\n registerHaltListener([&f] { f.close(); });\n}\n#endif\n/*******************************************************/\n\nstatic char __testlib_format_buffer[16777216];\nstatic int __testlib_format_buffer_usage_count = 0;\n\n#define FMT_TO_RESULT(fmt, cstr, result) std::string result; \\\n if (__testlib_format_buffer_usage_count != 0) \\\n __testlib_fail(\"FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0\"); \\\n __testlib_format_buffer_usage_count++; \\\n va_list ap; \\\n va_start(ap, fmt); \\\n vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \\\n va_end(ap); \\\n __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \\\n result = std::string(__testlib_format_buffer); \\\n __testlib_format_buffer_usage_count--; \\\n\nconst long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;\n\nNORETURN static void __testlib_fail(const std::string& message);\n\ntemplate\nstatic inline T __testlib_abs(const T& x)\n{\n return x > 0 ? x : -x;\n}\n\ntemplate\nstatic inline T __testlib_min(const T& a, const T& b)\n{\n return a < b ? a : b;\n}\n\ntemplate\nstatic inline T __testlib_max(const T& a, const T& b)\n{\n return a > b ? a : b;\n}\n\nstatic bool __testlib_prelimIsNaN(double r)\n{\n volatile double ra = r;\n#ifndef __BORLANDC__\n return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false);\n#else\n return std::_isnan(ra);\n#endif\n}\n\nstatic std::string removeDoubleTrailingZeroes(std::string value)\n{\n while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos)\n value = value.substr(0, value.length() - 1);\n return value + '0';\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nstd::string format(const char* fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt, result);\n return result;\n}\n\nstd::string format(const std::string fmt, ...)\n{\n FMT_TO_RESULT(fmt, fmt.c_str(), result);\n return result;\n}\n\nstatic std::string __testlib_part(const std::string& s);\n\nstatic bool __testlib_isNaN(double r)\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n volatile double ra = r;\n long long llr1, llr2;\n std::memcpy((void*)&llr1, (void*)&ra, sizeof(double)); \n ra = -ra;\n std::memcpy((void*)&llr2, (void*)&ra, sizeof(double)); \n long long llnan = 0xFFF8000000000000LL;\n return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2;\n}\n\nstatic double __testlib_nan()\n{\n __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long));\n#ifndef NAN\n long long llnan = 0xFFF8000000000000LL;\n double nan;\n std::memcpy(&nan, &llnan, sizeof(double));\n return nan;\n#else\n return NAN;\n#endif\n}\n\nstatic bool __testlib_isInfinite(double r)\n{\n volatile double ra = r;\n return (ra > 1E300 || ra < -1E300);\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)\n{\n if (__testlib_isNaN(expected))\n {\n return __testlib_isNaN(result);\n }\n else \n if (__testlib_isInfinite(expected))\n {\n if (expected > 0)\n {\n return result > 0 && __testlib_isInfinite(result);\n }\n else\n {\n return result < 0 && __testlib_isInfinite(result);\n }\n }\n else \n if (__testlib_isNaN(result) || __testlib_isInfinite(result))\n {\n return false;\n }\n else \n if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)\n {\n return true;\n }\n else\n {\n double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),\n expected * (1.0 + MAX_DOUBLE_ERROR));\n return result + 1E-15 >= minv && result <= maxv + 1E-15;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\ninline double doubleDelta(double expected, double result)\n{\n double absolute = __testlib_abs(result - expected);\n \n if (__testlib_abs(expected) > 1E-9)\n {\n double relative = __testlib_abs(absolute / expected);\n return __testlib_min(absolute, relative);\n }\n else\n return absolute;\n}\n\n#if !defined(_MSC_VER) || _MSC_VER<1900\n#ifndef _fileno\n#define _fileno(_stream) ((_stream)->_file)\n#endif\n#endif\n\n#ifndef O_BINARY\nstatic void __testlib_set_binary(\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\n std::FILE* file\n)\n#else\nstatic void __testlib_set_binary(std::FILE* file)\n#endif\n{\n#ifdef O_BINARY\n if (NULL != file)\n {\n#ifndef __BORLANDC__\n _setmode(_fileno(file), O_BINARY);\n#else\n setmode(fileno(file), O_BINARY);\n#endif\n }\n#endif\n}\n\n/*\n * Very simple regex-like pattern.\n * It used for two purposes: validation and generation.\n * \n * For example, pattern(\"[a-z]{1,5}\").next(rnd) will return\n * random string from lowercase latin letters with length \n * from 1 to 5. It is easier to call rnd.next(\"[a-z]{1,5}\") \n * for the same effect. \n * \n * Another samples:\n * \"mike|john\" will generate (match) \"mike\" or \"john\";\n * \"-?[1-9][0-9]{0,3}\" will generate (match) non-zero integers from -9999 to 9999;\n * \"id-([ac]|b{2})\" will generate (match) \"id-a\", \"id-bb\", \"id-c\";\n * \"[^0-9]*\" will match sequences (empty or non-empty) without digits, you can't \n * use it for generations.\n *\n * You can't use pattern for generation if it contains meta-symbol '*'. Also it\n * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].\n *\n * For matching very simple greedy algorithm is used. For example, pattern\n * \"[0-9]?1\" will not match \"1\", because of greedy nature of matching.\n * Alternations (meta-symbols \"|\") are processed with brute-force algorithm, so \n * do not use many alternations in one expression.\n *\n * If you want to use one expression many times it is better to compile it into\n * a single pattern like \"pattern p(\"[a-z]+\")\". Later you can use \n * \"p.matches(std::string s)\" or \"p.next(random_t& rd)\" to check matching or generate\n * new string by pattern.\n * \n * Simpler way to read token and check it for pattern matching is \"inf.readToken(\"[a-z]+\")\".\n */\nclass random_t;\n\nclass pattern\n{\npublic:\n /* Create pattern instance by string. */\n pattern(std::string s);\n /* Generate new string by pattern and given random_t. */\n std::string next(random_t& rnd) const;\n /* Checks if given string match the pattern. */\n bool matches(const std::string& s) const;\n /* Returns source string of the pattern. */\n std::string src() const;\nprivate:\n bool matches(const std::string& s, size_t pos) const;\n\n std::string s;\n std::vector children;\n std::vector chars;\n int from;\n int to;\n};\n\n/* \n * Use random_t instances to generate random values. It is preffered\n * way to use randoms instead of rand() function or self-written \n * randoms.\n *\n * Testlib defines global variable \"rnd\" of random_t class.\n * Use registerGen(argc, argv, 1) to setup random_t seed be command\n * line (to use latest random generator version).\n *\n * Random generates uniformly distributed values if another strategy is\n * not specified explicitly.\n */\nclass random_t\n{\nprivate:\n unsigned long long seed;\n static const unsigned long long multiplier;\n static const unsigned long long addend;\n static const unsigned long long mask;\n static const int lim;\n\n long long nextBits(int bits) \n {\n if (bits <= 48)\n {\n seed = (seed * multiplier + addend) & mask;\n return (long long)(seed >> (48 - bits));\n }\n else\n {\n if (bits > 63)\n __testlib_fail(\"random_t::nextBits(int bits): n must be less than 64\");\n\n int lowerBitCount = (random_t::version == 0 ? 31 : 32);\n \n long long left = (nextBits(31) << 32);\n long long right = nextBits(lowerBitCount);\n \n return left ^ right;\n }\n }\n\npublic:\n static int version;\n\n /* New random_t with fixed seed. */\n random_t()\n : seed(3905348978240129619LL)\n {\n }\n\n /* Sets seed by command line. */\n void setSeed(int argc, char* argv[])\n {\n random_t p;\n\n seed = 3905348978240129619LL;\n for (int i = 1; i < argc; i++)\n {\n std::size_t le = std::strlen(argv[i]);\n for (std::size_t j = 0; j < le; j++)\n seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;\n seed += multiplier / addend;\n }\n\n seed = seed & mask;\n }\n\n /* Sets seed by given value. */ \n void setSeed(long long _seed)\n {\n _seed = (_seed ^ multiplier) & mask;\n seed = _seed;\n }\n\n#ifndef __BORLANDC__\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(const std::string& ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#else\n /* Random string value by given pattern (see pattern documentation). */\n std::string next(std::string ptrn)\n {\n pattern p(ptrn);\n return p.next(*this);\n }\n#endif\n\n /* Random value in range [0, n-1]. */\n int next(int n)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(int n): n must be positive\");\n\n if ((n & -n) == n) // n is a power of 2\n return (int)((n * (long long)nextBits(31)) >> 31);\n\n const long long limit = INT_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(31);\n } while (bits >= limit);\n\n return int(bits % n);\n }\n\n /* Random value in range [0, n-1]. */\n unsigned int next(unsigned int n)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::next(unsigned int n): n must be less INT_MAX\");\n return (unsigned int)next(int(n));\n }\n\n /* Random value in range [0, n-1]. */\n long long next(long long n) \n {\n if (n <= 0)\n __testlib_fail(\"random_t::next(long long n): n must be positive\");\n\n const long long limit = __TESTLIB_LONGLONG_MAX / n * n;\n \n long long bits;\n do {\n bits = nextBits(63);\n } while (bits >= limit);\n\n return bits % n;\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long long next(unsigned long long n)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long long n): n must be less LONGLONG_MAX\");\n return (unsigned long long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n long next(long n)\n {\n return (long)next((long long)(n));\n }\n\n /* Random value in range [0, n-1]. */\n unsigned long next(unsigned long n)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::next(unsigned long n): n must be less LONG_MAX\");\n return (unsigned long)next((unsigned long long)(n));\n }\n\n /* Returns random value in range [from,to]. */\n int next(int from, int to)\n {\n return int(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n unsigned int next(unsigned int from, unsigned int to)\n {\n return (unsigned int)(next((long long)to - from + 1) + from);\n }\n\n /* Returns random value in range [from,to]. */\n long long next(long long from, long long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long long next(unsigned long long from, unsigned long long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n long next(long from, long to)\n {\n return next(to - from + 1) + from;\n }\n\n /* Returns random value in range [from,to]. */\n unsigned long next(unsigned long from, unsigned long to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(unsigned long from, unsigned long to): from can't not exceed to\");\n return next(to - from + 1) + from;\n }\n\n /* Random double value in range [0, 1). */\n double next() \n {\n long long left = ((long long)(nextBits(26)) << 27);\n long long right = nextBits(27);\n return (double)(left + right) / (double)(1LL << 53);\n }\n\n /* Random double value in range [0, n). */\n double next(double n)\n {\n return n * next();\n }\n\n /* Random double value in range [from, to). */\n double next(double from, double to)\n {\n if (from > to)\n __testlib_fail(\"random_t::next(double from, double to): from can't not exceed to\");\n return next(to - from) + from;\n }\n\n /* Returns random element from container. */\n template \n typename Container::value_type any(const Container& c)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Container& c): c.size() must be positive\");\n return *(c.begin() + next(size));\n }\n\n /* Returns random element from iterator range. */\n template \n typename Iter::value_type any(const Iter& begin, const Iter& end)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end): range must have positive length\");\n return *(begin + next(size));\n }\n\n /* Random string value by given pattern (see pattern documentation). */\n#ifdef __GNUC__\n __attribute__ ((format (printf, 2, 3)))\n#endif\n std::string next(const char* format, ...)\n {\n FMT_TO_RESULT(format, format, ptrn);\n return next(ptrn);\n }\n\n /* \n * Weighted next. If type == 0 than it is usual \"next()\".\n *\n * If type = 1, than it returns \"max(next(), next())\"\n * (the number of \"max\" functions equals to \"type\").\n *\n * If type < 0, than \"max\" function replaces with \"min\".\n */\n int wnext(int n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(int n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n int result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));\n\n return int(n * p);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n long long wnext(long long n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(long long n, int type): n must be positive\");\n \n if (abs(type) < random_t::lim)\n {\n long long result = next(n);\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next(n));\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next(n));\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(int type)\n {\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return p;\n }\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n double wnext(double n, int type)\n {\n if (n <= 0)\n __testlib_fail(\"random_t::wnext(double n, int type): n must be positive\");\n\n if (abs(type) < random_t::lim)\n {\n double result = next();\n\n for (int i = 0; i < +type; i++)\n result = __testlib_max(result, next());\n \n for (int i = 0; i < -type; i++)\n result = __testlib_min(result, next());\n\n return n * result;\n }\n else\n {\n double p;\n \n if (type > 0)\n p = std::pow(next() + 0.0, 1.0 / (type + 1));\n else\n p = std::pow(next() + 0.0, - type + 1);\n\n return n * p;\n }\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n unsigned int wnext(unsigned int n, int type)\n {\n if (n >= INT_MAX)\n __testlib_fail(\"random_t::wnext(unsigned int n, int type): n must be less INT_MAX\");\n return (unsigned int)wnext(int(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long long wnext(unsigned long long n, int type)\n {\n if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX\");\n\n return (unsigned long long)wnext((long long)(n), type);\n }\n\n /* See wnext(int, int). It uses the same algorithms. */\n long wnext(long n, int type)\n {\n return (long)wnext((long long)(n), type);\n }\n \n /* See wnext(int, int). It uses the same algorithms. */\n unsigned long wnext(unsigned long n, int type)\n {\n if (n >= (unsigned long)(LONG_MAX))\n __testlib_fail(\"random_t::wnext(unsigned long n, int type): n must be less LONG_MAX\");\n\n return (unsigned long)wnext((unsigned long long)(n), type);\n }\n\n /* Returns weighted random value in range [from, to]. */\n int wnext(int from, int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(int from, int to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n int wnext(unsigned int from, unsigned int to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to\");\n return int(wnext(to - from + 1, type) + from);\n }\n \n /* Returns weighted random value in range [from, to]. */\n long long wnext(long long from, long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long long from, long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long long wnext(unsigned long long from, unsigned long long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n long wnext(long from, long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(long from, long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random value in range [from, to]. */\n unsigned long wnext(unsigned long from, unsigned long to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to\");\n return wnext(to - from + 1, type) + from;\n }\n \n /* Returns weighted random double value in range [from, to). */\n double wnext(double from, double to, int type)\n {\n if (from > to)\n __testlib_fail(\"random_t::wnext(double from, double to, int type): from can't not exceed to\");\n return wnext(to - from, type) + from;\n }\n\n /* Returns weighted random element from container. */\n template \n typename Container::value_type wany(const Container& c, int type)\n {\n size_t size = c.size();\n if (size <= 0)\n __testlib_fail(\"random_t::wany(const Container& c, int type): c.size() must be positive\");\n return *(c.begin() + wnext(size, type));\n }\n\n /* Returns weighted random element from iterator range. */\n template \n typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)\n {\n int size = int(end - begin);\n if (size <= 0)\n __testlib_fail(\"random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length\");\n return *(begin + wnext(size, type));\n }\n\n template\n std::vector perm(T size, E first)\n {\n if (size <= 0)\n __testlib_fail(\"random_t::perm(T size, E first = 0): size must be positive\");\n std::vector p(size);\n for (T i = 0; i < size; i++)\n p[i] = first + i;\n if (size > 1)\n for (T i = 1; i < size; i++)\n std::swap(p[i], p[next(i + 1)]);\n return p;\n }\n\n template\n std::vector perm(T size)\n {\n return perm(size, T(0));\n }\n};\n\nconst int random_t::lim = 25;\nconst unsigned long long random_t::multiplier = 0x5DEECE66DLL;\nconst unsigned long long random_t::addend = 0xBLL;\nconst unsigned long long random_t::mask = (1LL << 48) - 1;\nint random_t::version = -1;\n\n/* Pattern implementation */\nbool pattern::matches(const std::string& s) const\n{\n return matches(s, 0);\n}\n\nstatic bool __pattern_isSlash(const std::string& s, size_t pos)\n{\n return s[pos] == '\\\\';\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)\n{\n if (pos >= s.length())\n return false;\n\n int slashes = 0;\n\n int before = int(pos) - 1;\n while (before >= 0 && s[before] == '\\\\')\n before--, slashes++;\n\n return slashes % 2 == 0 && s[pos] == value;\n}\n\nstatic char __pattern_getChar(const std::string& s, size_t& pos)\n{\n if (__pattern_isSlash(s, pos))\n pos += 2;\n else\n pos++;\n\n return s[pos - 1];\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector chars)\n{\n int result = 0;\n\n while (pos < s.length())\n {\n char c = s[pos++];\n if (!std::binary_search(chars.begin(), chars.end(), c))\n break;\n else\n result++;\n }\n\n return result;\n}\n\nstd::string pattern::src() const\n{\n return s;\n}\n\nbool pattern::matches(const std::string& s, size_t pos) const\n{\n std::string result;\n\n if (to > 0)\n {\n int size = __pattern_greedyMatch(s, pos, chars);\n if (size < from)\n return false;\n if (size > to)\n size = to;\n pos += size;\n }\n\n if (children.size() > 0)\n {\n for (size_t child = 0; child < children.size(); child++)\n if (children[child].matches(s, pos))\n return true;\n return false;\n }\n else\n return pos == s.length();\n}\n\nstd::string pattern::next(random_t& rnd) const\n{\n std::string result;\n result.reserve(20);\n\n if (to == INT_MAX)\n __testlib_fail(\"pattern::next(random_t& rnd): can't process character '*' for generation\");\n\n if (to > 0)\n {\n int count = rnd.next(to - from + 1) + from;\n for (int i = 0; i < count; i++)\n result += chars[rnd.next(int(chars.size()))];\n }\n\n if (children.size() > 0)\n {\n int child = rnd.next(int(children.size()));\n result += children[child].next(rnd);\n }\n\n return result;\n}\n\nstatic void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)\n{\n if (pos >= s.length())\n {\n from = to = 1;\n return;\n }\n \n if (__pattern_isCommandChar(s, pos, '{'))\n {\n std::vector parts;\n std::string part;\n\n pos++;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))\n {\n if (__pattern_isCommandChar(s, pos, ','))\n parts.push_back(part), part = \"\", pos++;\n else\n part += __pattern_getChar(s, pos);\n }\n\n if (part != \"\")\n parts.push_back(part);\n\n if (!__pattern_isCommandChar(s, pos, '}'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (parts.size() < 1 || parts.size() > 2)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector numbers;\n\n for (size_t i = 0; i < parts.size(); i++)\n {\n if (parts[i].length() == 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n int number;\n if (std::sscanf(parts[i].c_str(), \"%d\", &number) != 1)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n numbers.push_back(number);\n }\n\n if (numbers.size() == 1)\n from = to = numbers[0];\n else\n from = numbers[0], to = numbers[1];\n\n if (from > to)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n }\n else\n {\n if (__pattern_isCommandChar(s, pos, '?'))\n {\n from = 0, to = 1, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '*'))\n {\n from = 0, to = INT_MAX, pos++;\n return;\n }\n\n if (__pattern_isCommandChar(s, pos, '+'))\n {\n from = 1, to = INT_MAX, pos++;\n return;\n }\n \n from = to = 1;\n }\n}\n\nstatic std::vector __pattern_scanCharSet(const std::string& s, size_t& pos)\n{\n if (pos >= s.length())\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n std::vector result;\n\n if (__pattern_isCommandChar(s, pos, '['))\n {\n pos++;\n bool negative = __pattern_isCommandChar(s, pos, '^');\n\n char prev = 0;\n\n while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))\n {\n if (__pattern_isCommandChar(s, pos, '-') && prev != 0)\n {\n pos++;\n\n if (pos + 1 == s.length() || __pattern_isCommandChar(s, pos, ']'))\n {\n result.push_back(prev);\n prev = '-';\n continue;\n }\n\n char next = __pattern_getChar(s, pos);\n if (prev > next)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n for (char c = prev; c != next; c++)\n result.push_back(c);\n result.push_back(next);\n\n prev = 0;\n }\n else\n {\n if (prev != 0)\n result.push_back(prev);\n prev = __pattern_getChar(s, pos);\n }\n }\n\n if (prev != 0)\n result.push_back(prev);\n\n if (!__pattern_isCommandChar(s, pos, ']'))\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n pos++;\n\n if (negative)\n {\n std::sort(result.begin(), result.end());\n std::vector actuals;\n for (int code = 0; code < 255; code++)\n {\n char c = char(code);\n if (!std::binary_search(result.begin(), result.end(), c))\n actuals.push_back(c);\n }\n result = actuals;\n }\n\n std::sort(result.begin(), result.end());\n }\n else\n result.push_back(__pattern_getChar(s, pos));\n\n return result;\n}\n\npattern::pattern(std::string s): s(s), from(0), to(0)\n{\n std::string t;\n for (size_t i = 0; i < s.length(); i++)\n if (!__pattern_isCommandChar(s, i, ' '))\n t += s[i];\n s = t;\n\n int opened = 0;\n int firstClose = -1;\n std::vector seps;\n\n for (size_t i = 0; i < s.length(); i++)\n {\n if (__pattern_isCommandChar(s, i, '('))\n {\n opened++;\n continue;\n }\n\n if (__pattern_isCommandChar(s, i, ')'))\n {\n opened--;\n if (opened == 0 && firstClose == -1)\n firstClose = int(i);\n continue;\n }\n \n if (opened < 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (__pattern_isCommandChar(s, i, '|') && opened == 0)\n seps.push_back(int(i));\n }\n\n if (opened != 0)\n __testlib_fail(\"pattern: Illegal pattern (or part) \\\"\" + s + \"\\\"\");\n\n if (seps.size() == 0 && firstClose + 1 == (int)s.length() \n && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))\n {\n children.push_back(pattern(s.substr(1, s.length() - 2)));\n }\n else\n {\n if (seps.size() > 0)\n {\n seps.push_back(int(s.length()));\n int last = 0;\n\n for (size_t i = 0; i < seps.size(); i++)\n {\n children.push_back(pattern(s.substr(last, seps[i] - last)));\n last = seps[i] + 1;\n }\n }\n else\n {\n size_t pos = 0;\n chars = __pattern_scanCharSet(s, pos);\n __pattern_scanCounts(s, pos, from, to);\n if (pos < s.length())\n children.push_back(pattern(s.substr(pos)));\n }\n }\n}\n/* End of pattern implementation */\n\ntemplate \ninline bool isEof(C c)\n{\n return c == EOFC;\n}\n\ntemplate \ninline bool isEoln(C c)\n{\n return (c == LF || c == CR);\n}\n\ntemplate\ninline bool isBlanks(C c)\n{\n return (c == LF || c == CR || c == SPACE || c == TAB);\n}\n\nenum TMode\n{\n _input, _output, _answer\n};\n\n/* Outcomes 6-15 are reserved for future use. */\nenum TResult\n{\n _ok = 0,\n _wa = 1,\n _pe = 2,\n _fail = 3,\n _dirt = 4,\n _points = 5,\n _unexpected_eof = 8,\n _sv = 10,\n _pv = 11,\n _partially = 16\n};\n\nenum TTestlibMode\n{\n _unknown, _checker, _validator, _generator, _interactor\n};\n\n#define _pc(exitCode) (TResult(_partially + (exitCode)))\n\n/* Outcomes 6-15 are reserved for future use. */\nconst std::string outcomes[] = {\n \"accepted\",\n \"wrong-answer\",\n \"presentation-error\",\n \"fail\",\n \"fail\",\n#ifndef PCMS2\n \"points\",\n#else\n \"relative-scoring\",\n#endif\n \"reserved\",\n \"reserved\",\n \"unexpected-eof\",\n \"reserved\",\n \"security-violation\",\n \"protocol-violation\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"reserved\",\n \"partially-correct\"\n};\n\nclass InputStreamReader\n{\npublic:\n virtual int curChar() = 0; \n virtual int nextChar() = 0; \n virtual void skipChar() = 0;\n virtual void unreadChar(int c) = 0;\n virtual std::string getName() = 0;\n virtual bool eof() = 0;\n virtual void close() = 0;\n virtual int getLine() = 0;\n virtual ~InputStreamReader() = 0;\n};\n\nInputStreamReader::~InputStreamReader()\n{\n // No operations.\n}\n\nclass StringInputStreamReader: public InputStreamReader\n{\nprivate:\n std::string s;\n size_t pos;\n\npublic:\n StringInputStreamReader(const std::string& content): s(content), pos(0)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (pos >= s.length())\n return EOFC;\n else\n return s[pos];\n }\n\n int nextChar()\n {\n if (pos >= s.length())\n {\n pos++;\n return EOFC;\n }\n else\n return s[pos++];\n }\n\n void skipChar()\n {\n pos++;\n }\n\n void unreadChar(int c)\n { \n if (pos == 0)\n __testlib_fail(\"FileFileInputStreamReader::unreadChar(int): pos == 0.\");\n pos--;\n if (pos < s.length())\n s[pos] = char(c);\n }\n\n std::string getName()\n {\n return __testlib_part(s);\n }\n\n int getLine()\n {\n return -1;\n }\n\n bool eof()\n {\n return pos >= s.length();\n }\n\n void close()\n {\n // No operations.\n }\n};\n\nclass FileInputStreamReader: public InputStreamReader\n{\nprivate:\n std::FILE* file;\n std::string name;\n int line;\n std::vector undoChars;\n\n inline int postprocessGetc(int getcResult)\n {\n if (getcResult != EOF)\n return getcResult;\n else\n return EOFC;\n }\n\n int getc(FILE* file)\n {\n int c;\n if (undoChars.empty())\n c = ::getc(file);\n else\n {\n c = undoChars.back();\n undoChars.pop_back();\n }\n\n if (c == LF)\n line++;\n return c;\n }\n\n int ungetc(int c/*, FILE* file*/)\n {\n if (c == LF)\n line--;\n undoChars.push_back(c);\n return c;\n }\n\npublic:\n FileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n // No operations.\n }\n\n int curChar()\n {\n if (feof(file))\n return EOFC;\n else\n {\n int c = getc(file);\n ungetc(c/*, file*/);\n return postprocessGetc(c);\n }\n }\n\n int nextChar()\n {\n if (feof(file))\n return EOFC;\n else\n return postprocessGetc(getc(file));\n }\n\n void skipChar()\n {\n getc(file);\n }\n\n void unreadChar(int c)\n { \n ungetc(c/*, file*/);\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n\n bool eof()\n {\n if (NULL == file || feof(file))\n return true;\n else\n {\n int c = nextChar();\n if (c == EOFC || (c == EOF && feof(file)))\n return true;\n unreadChar(c);\n return false;\n }\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nclass BufferedFileInputStreamReader: public InputStreamReader\n{\nprivate:\n static const size_t BUFFER_SIZE;\n static const size_t MAX_UNREAD_COUNT; \n \n std::FILE* file;\n char* buffer;\n bool* isEof;\n int bufferPos;\n size_t bufferSize;\n\n std::string name;\n int line;\n\n bool refill()\n {\n if (NULL == file)\n __testlib_fail(\"BufferedFileInputStreamReader: file == NULL (\" + getName() + \")\");\n\n if (bufferPos >= int(bufferSize))\n {\n size_t readSize = fread(\n buffer + MAX_UNREAD_COUNT,\n 1,\n BUFFER_SIZE - MAX_UNREAD_COUNT,\n file\n );\n\n if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT\n && ferror(file))\n __testlib_fail(\"BufferedFileInputStreamReader: unable to read (\" + getName() + \")\");\n\n bufferSize = MAX_UNREAD_COUNT + readSize;\n bufferPos = int(MAX_UNREAD_COUNT);\n std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);\n\n return readSize > 0;\n }\n else\n return true;\n }\n\n char increment()\n {\n char c;\n if ((c = buffer[bufferPos++]) == LF)\n line++;\n return c;\n }\n\npublic:\n BufferedFileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name), line(1)\n {\n buffer = new char[BUFFER_SIZE];\n isEof = new bool[BUFFER_SIZE];\n bufferSize = MAX_UNREAD_COUNT;\n bufferPos = int(MAX_UNREAD_COUNT);\n }\n\n ~BufferedFileInputStreamReader()\n {\n if (NULL != buffer)\n {\n delete[] buffer;\n buffer = NULL;\n }\n if (NULL != isEof)\n {\n delete[] isEof;\n isEof = NULL;\n }\n }\n\n int curChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : buffer[bufferPos];\n }\n\n int nextChar()\n {\n if (!refill())\n return EOFC;\n\n return isEof[bufferPos] ? EOFC : increment();\n }\n\n void skipChar()\n {\n increment();\n }\n\n void unreadChar(int c)\n { \n bufferPos--;\n if (bufferPos < 0)\n __testlib_fail(\"BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0\");\n isEof[bufferPos] = (c == EOFC);\n buffer[bufferPos] = char(c);\n if (c == LF)\n line--;\n }\n\n std::string getName()\n {\n return name;\n }\n\n int getLine()\n {\n return line;\n }\n \n bool eof()\n {\n return !refill() || EOFC == curChar();\n }\n\n void close()\n {\n if (NULL != file)\n {\n fclose(file);\n file = NULL;\n }\n }\n};\n\nconst size_t BufferedFileInputStreamReader::BUFFER_SIZE = 2000000;\nconst size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = BufferedFileInputStreamReader::BUFFER_SIZE / 2; \n\n/*\n * Streams to be used for reading data in checkers or validators.\n * Each read*() method moves pointer to the next character after the\n * read value.\n */\nstruct InStream\n{\n /* Do not use them. */\n InStream();\n ~InStream();\n\n /* Wrap std::string with InStream. */\n InStream(const InStream& baseStream, std::string content);\n\n InputStreamReader* reader;\n int lastLine;\n\n std::string name;\n TMode mode;\n bool opened;\n bool stdfile;\n bool strict;\n\n int wordReserveSize;\n std::string _tmpReadToken;\n\n int readManyIteration;\n size_t maxFileSize;\n size_t maxTokenLength;\n size_t maxMessageLength;\n\n void init(std::string fileName, TMode mode);\n void init(std::FILE* f, TMode mode);\n\n /* Moves stream pointer to the first non-white-space character or EOF. */ \n void skipBlanks();\n \n /* Returns current character in the stream. Doesn't remove it from stream. */\n char curChar();\n /* Moves stream pointer one character forward. */\n void skipChar();\n /* Returns current character and moves pointer one character forward. */\n char nextChar();\n \n /* Returns current character and moves pointer one character forward. */\n char readChar();\n /* As \"readChar()\" but ensures that the result is equal to given parameter. */\n char readChar(char c);\n /* As \"readChar()\" but ensures that the result is equal to the space (code=32). */\n char readSpace();\n /* Puts back the character into the stream. */\n void unreadChar(char c);\n\n /* Reopens stream, you should not use it. */\n void reset(std::FILE* file = NULL);\n /* Checks that current position is EOF. If not it doesn't move stream pointer. */\n bool eof();\n /* Moves pointer to the first non-white-space character and calls \"eof()\". */\n bool seekEof();\n\n /* \n * Checks that current position contains EOLN. \n * If not it doesn't move stream pointer. \n * In strict mode expects \"#13#10\" for windows or \"#10\" for other platforms.\n */\n bool eoln();\n /* Moves pointer to the first non-space and non-tab character and calls \"eoln()\". */\n bool seekEoln();\n\n /* Moves stream pointer to the first character of the next line (if exists). */\n void nextLine();\n\n /* \n * Reads new token. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n std::string readWord();\n /* The same as \"readWord()\", it is preffered to use \"readToken()\". */\n std::string readToken();\n /* The same as \"readWord()\", but ensures that token matches to given pattern. */\n std::string readWord(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readWord(const pattern& p, const std::string& variableName = \"\");\n std::vector readWords(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readWords(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n /* The same as \"readToken()\", but ensures that token matches to given pattern. */\n std::string readToken(const std::string& ptrn, const std::string& variableName = \"\");\n std::string readToken(const pattern& p, const std::string& variableName = \"\");\n std::vector readTokens(int size, const std::string& ptrn, const std::string& variablesName = \"\", int indexBase = 1);\n std::vector readTokens(int size, const pattern& p, const std::string& variablesName = \"\", int indexBase = 1);\n\n void readWordTo(std::string& result);\n void readWordTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n void readTokenTo(std::string& result);\n void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads new long long value. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n long long readLong();\n unsigned long long readUnsignedLong();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInteger();\n /* \n * Reads new int. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n int readInt();\n\n /* As \"readLong()\" but ensures that value in the range [minv,maxv]. */\n long long readLong(long long minv, long long maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of long longs. */\n std::vector readLongs(int size, long long minv, long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n unsigned long long readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n unsigned long long readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName = \"\");\n std::vector readLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* As \"readInteger()\" but ensures that value in the range [minv,maxv]. */\n int readInteger(int minv, int maxv, const std::string& variableName = \"\");\n /* As \"readInt()\" but ensures that value in the range [minv,maxv]. */\n int readInt(int minv, int maxv, const std::string& variableName = \"\");\n /* Reads space-separated sequence of integers. */\n std::vector readIntegers(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* Reads space-separated sequence of integers. */\n std::vector readInts(int size, int minv, int maxv, const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readReal();\n /* \n * Reads new double. Ignores white-spaces into the non-strict mode \n * (strict mode is used in validators usually). \n */\n double readDouble();\n \n /* As \"readReal()\" but ensures that value in the range [minv,maxv]. */\n double readReal(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readReals(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n /* As \"readDouble()\" but ensures that value in the range [minv,maxv]. */\n double readDouble(double minv, double maxv, const std::string& variableName = \"\");\n std::vector readDoubles(int size, double minv, double maxv, const std::string& variablesName = \"\", int indexBase = 1);\n \n /* \n * As \"readReal()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n\n /* \n * As \"readDouble()\" but ensures that value in the range [minv,maxv] and\n * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]\n * and number is in the form \"[-]digit(s)[.digit(s)]\".\n */\n double readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName = \"\");\n std::vector readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName = \"\", int indexBase = 1);\n \n /* As readLine(). */\n std::string readString();\n /* Read many lines. */\n std::vector readStrings(int size, int indexBase = 1);\n /* See readLine(). */\n void readStringTo(std::string& result);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n std::string readString(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readStrings(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readStrings(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()/readString()\", but ensures that line matches to the given pattern. */\n void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* \n * Reads line from the current position to EOLN or EOF. Moves stream pointer to \n * the first character of the new line (if possible). \n */\n std::string readLine();\n /* Read many lines. */\n std::vector readLines(int size, int indexBase = 1);\n /* See readLine(). */\n void readLineTo(std::string& result);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n std::string readLine(const std::string& ptrn, const std::string& variableName = \"\");\n /* Read many lines. */\n std::vector readLines(int size, const pattern& p, const std::string& variableName = \"\", int indexBase = 1);\n /* Read many lines. */\n std::vector readLines(int size, const std::string& ptrn, const std::string& variableName = \"\", int indexBase = 1);\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const pattern& p, const std::string& variableName = \"\");\n /* The same as \"readLine()\", but ensures that line matches to the given pattern. */\n void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = \"\");\n\n /* Reads EOLN or fails. Use it in validators. Calls \"eoln()\" method internally. */\n void readEoln();\n /* Reads EOF or fails. Use it in validators. Calls \"eof()\" method internally. */\n void readEof();\n\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quit(TResult result, const char* msg);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quitf(TResult result, const char* msg, ...);\n /* \n * Quit-functions aborts program with and :\n * input/answer streams replace any result to FAIL.\n */\n NORETURN void quits(TResult result, std::string msg);\n\n /* \n * Checks condition and aborts a program if codition is false.\n * Returns _wa for ouf and _fail on any other streams.\n */\n #ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n #endif\n void ensuref(bool cond, const char* format, ...);\n void __testlib_ensure(bool cond, std::string message);\n\n void close();\n\n const static int NO_INDEX = INT_MAX;\n\n const static WORD LightGray = 0x07; \n const static WORD LightRed = 0x0c; \n const static WORD LightCyan = 0x0b; \n const static WORD LightGreen = 0x0a; \n const static WORD LightYellow = 0x0e; \n const static WORD LightMagenta = 0x0d; \n\n static void textColor(WORD color);\n static void quitscr(WORD color, const char* msg);\n static void quitscrS(WORD color, std::string msg);\n void xmlSafeWrite(std::FILE * file, const char* msg);\n\n void readSecret(\n std::string secret,\n TResult mismatchResult = _pv,\n std::string mismatchMessage = \"Secret mismatch\",\n std::string eofMessage = \"Unexpected end of file - secret expected\");\n void readGraderResult();\n\nprivate:\n InStream(const InStream&);\n InStream& operator =(const InStream&);\n void quitByGraderResult(TResult result, std::string defaultMessage);\n};\n\nInStream inf;\nInStream ouf;\nInStream ans;\nbool appesMode;\nstd::string resultName;\nstd::string checkerName = \"untitled checker\";\nrandom_t rnd;\nTTestlibMode testlibMode = _unknown;\ndouble __testlib_points = std::numeric_limits::infinity();\n\nstruct ValidatorBoundsHit\n{\n static const double EPS;\n bool minHit;\n bool maxHit;\n\n ValidatorBoundsHit(bool minHit = false, bool maxHit = false): minHit(minHit), maxHit(maxHit)\n {\n };\n\n ValidatorBoundsHit merge(const ValidatorBoundsHit& validatorBoundsHit)\n {\n return ValidatorBoundsHit(\n __testlib_max(minHit, validatorBoundsHit.minHit),\n __testlib_max(maxHit, validatorBoundsHit.maxHit)\n );\n }\n};\n\nconst double ValidatorBoundsHit::EPS = 1E-12;\n\nclass Validator\n{\nprivate:\n std::string _testset;\n std::string _group;\n std::string _testOverviewLogFileName;\n std::map _boundsHitByVariableName;\n std::set _features;\n std::set _hitFeatures;\n\n bool isVariableNameBoundsAnalyzable(const std::string& variableName)\n {\n for (size_t i = 0; i < variableName.length(); i++)\n if ((variableName[i] >= '0' && variableName[i] <= '9') || variableName[i] < ' ')\n return false;\n return true;\n }\n\n bool isFeatureNameAnalyzable(const std::string& featureName)\n {\n for (size_t i = 0; i < featureName.length(); i++)\n if (featureName[i] < ' ')\n return false;\n return true;\n }\npublic:\n Validator(): _testset(\"tests\"), _group()\n {\n }\n\n std::string testset() const\n {\n return _testset;\n }\n \n std::string group() const\n {\n return _group;\n }\n\n std::string testOverviewLogFileName() const\n {\n return _testOverviewLogFileName;\n }\n \n void setTestset(const char* const testset)\n {\n _testset = testset;\n }\n\n void setGroup(const char* const group)\n {\n _group = group;\n }\n\n void setTestOverviewLogFileName(const char* const testOverviewLogFileName)\n {\n _testOverviewLogFileName = testOverviewLogFileName;\n }\n\n void addBoundsHit(const std::string& variableName, ValidatorBoundsHit boundsHit)\n {\n if (isVariableNameBoundsAnalyzable(variableName))\n {\n _boundsHitByVariableName[variableName]\n = boundsHit.merge(_boundsHitByVariableName[variableName]);\n }\n }\n\n std::string getBoundsHitLog()\n {\n std::string result;\n for (std::map::iterator i = _boundsHitByVariableName.begin();\n i != _boundsHitByVariableName.end();\n i++)\n {\n result += \"\\\"\" + i->first + \"\\\":\";\n if (i->second.minHit)\n result += \" min-value-hit\";\n if (i->second.maxHit)\n result += \" max-value-hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n std::string getFeaturesLog()\n {\n std::string result;\n for (std::set::iterator i = _features.begin();\n i != _features.end();\n i++)\n {\n result += \"feature \\\"\" + *i + \"\\\":\";\n if (_hitFeatures.count(*i))\n result += \" hit\";\n result += \"\\n\";\n }\n return result;\n }\n\n void writeTestOverviewLog()\n {\n if (!_testOverviewLogFileName.empty())\n {\n std::string fileName(_testOverviewLogFileName);\n _testOverviewLogFileName = \"\";\n FILE* testOverviewLogFile = fopen(fileName.c_str(), \"w\");\n if (NULL == testOverviewLogFile)\n __testlib_fail(\"Validator::writeTestOverviewLog: can't test overview log to (\" + fileName + \")\");\n fprintf(testOverviewLogFile, \"%s%s\", getBoundsHitLog().c_str(), getFeaturesLog().c_str());\n if (fclose(testOverviewLogFile))\n __testlib_fail(\"Validator::writeTestOverviewLog: can't close test overview log file (\" + fileName + \")\");\n }\n }\n\n void addFeature(const std::string& feature)\n {\n if (_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" registered twice.\");\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n _features.insert(feature);\n }\n\n void feature(const std::string& feature)\n {\n if (!isFeatureNameAnalyzable(feature))\n __testlib_fail(\"Feature name '\" + feature + \"' contains restricted characters.\");\n\n if (!_features.count(feature))\n __testlib_fail(\"Feature \" + feature + \" didn't registered via addFeature(feature).\");\n\n _hitFeatures.insert(feature);\n }\n} validator;\n\nstruct TestlibFinalizeGuard\n{\n static bool alive;\n int quitCount, readEofCount;\n\n TestlibFinalizeGuard() : quitCount(0), readEofCount(0)\n {\n // No operations.\n }\n\n ~TestlibFinalizeGuard()\n {\n bool _alive = alive;\n alive = false;\n\n if (_alive)\n {\n if (testlibMode == _checker && quitCount == 0)\n __testlib_fail(\"Checker must end with quit or quitf call.\");\n\n if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)\n __testlib_fail(\"Validator must end with readEof call.\");\n }\n\n validator.writeTestOverviewLog();\n }\n};\n\nbool TestlibFinalizeGuard::alive = true;\nTestlibFinalizeGuard testlibFinalizeGuard;\n\n/*\n * Call it to disable checks on finalization.\n */\nvoid disableFinalizeGuard()\n{\n TestlibFinalizeGuard::alive = false;\n}\n\n/* Interactor streams.\n */\nstd::fstream tout;\n\n/* implementation\n */\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate\nstatic std::string vtos(const T& t, std::true_type)\n{ \n if (t == 0)\n return \"0\";\n else\n {\n T n(t);\n bool negative = n < 0;\n std::string s;\n while (n != 0) {\n T digit = n % 10;\n if (digit < 0)\n digit = -digit;\n s += char('0' + digit);\n n /= 10;\n }\n std::reverse(s.begin(), s.end());\n return negative ? \"-\" + s : s;\n }\n}\n\ntemplate\nstatic std::string vtos(const T& t, std::false_type)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n\ntemplate \nstatic std::string vtos(const T& t)\n{\n return vtos(t, std::is_integral());\n}\n#else\ntemplate\nstatic std::string vtos(const T& t)\n{\n std::string s;\n static std::stringstream ss;\n ss.str(std::string());\n ss.clear();\n ss << t;\n ss >> s;\n return s;\n}\n#endif\n\ntemplate \nstatic std::string toString(const T& t)\n{\n return vtos(t);\n}\n\nInStream::InStream()\n{\n reader = NULL;\n lastLine = -1;\n name = \"\";\n mode = _input;\n strict = false;\n stdfile = false;\n wordReserveSize = 4;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::InStream(const InStream& baseStream, std::string content)\n{\n reader = new StringInputStreamReader(content);\n lastLine = -1;\n opened = true;\n strict = baseStream.strict;\n mode = baseStream.mode;\n name = \"based on \" + baseStream.name;\n readManyIteration = NO_INDEX;\n maxFileSize = 128 * 1024 * 1024; // 128MB.\n maxTokenLength = 32 * 1024 * 1024; // 32MB.\n maxMessageLength = 32000;\n}\n\nInStream::~InStream()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n}\n\n#ifdef __GNUC__\n__attribute__((const))\n#endif\nint resultExitCode(TResult r)\n{\n if (testlibMode == _checker)\n return 0;//CMS Checkers should always finish with zero exit code.\n if (r == _ok)\n return OK_EXIT_CODE;\n if (r == _wa)\n return WA_EXIT_CODE;\n if (r == _pe)\n return PE_EXIT_CODE;\n if (r == _fail)\n return FAIL_EXIT_CODE;\n if (r == _dirt)\n return DIRT_EXIT_CODE;\n if (r == _points)\n return POINTS_EXIT_CODE;\n if (r == _unexpected_eof)\n#ifdef ENABLE_UNEXPECTED_EOF\n return UNEXPECTED_EOF_EXIT_CODE;\n#else\n return PE_EXIT_CODE;\n#endif\n if (r == _sv)\n return SV_EXIT_CODE;\n if (r == _pv)\n return PV_EXIT_CODE;\n if (r >= _partially)\n return PC_BASE_EXIT_CODE + (r - _partially);\n return FAIL_EXIT_CODE;\n}\n\nvoid InStream::textColor(\n#if !(defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)) && defined(__GNUC__)\n __attribute__((unused)) \n#endif\n WORD color\n)\n{\n#if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)\n HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(handle, color);\n#endif\n#if !defined(ON_WINDOWS) && defined(__GNUC__)\n if (isatty(2))\n {\n switch (color)\n {\n case LightRed:\n fprintf(stderr, \"\\033[1;31m\");\n break;\n case LightCyan:\n fprintf(stderr, \"\\033[1;36m\");\n break;\n case LightGreen:\n fprintf(stderr, \"\\033[1;32m\");\n break;\n case LightYellow:\n fprintf(stderr, \"\\033[1;33m\");\n break;\n case LightMagenta:\n fprintf(stderr, \"\\033[1;35m\");\n break;\n case LightGray:\n default:\n fprintf(stderr, \"\\033[0m\");\n }\n }\n#endif\n}\n\nNORETURN void halt(int exitCode)\n{\n callHaltListeners();\n#ifdef FOOTER\n InStream::textColor(InStream::LightGray);\n std::fprintf(stderr, \"Checker: \\\"%s\\\"\\n\", checkerName.c_str());\n std::fprintf(stderr, \"Exit code: %d\\n\", exitCode);\n InStream::textColor(InStream::LightGray);\n#endif\n std::exit(exitCode);\n}\n\nstatic bool __testlib_shouldCheckDirt(TResult result)\n{\n return result == _ok || result == _points || result >= _partially;\n}\n\n\nstd::string RESULT_MESSAGE_CORRECT = \"Output is correct\";\nstd::string RESULT_MESSAGE_PARTIALLY_CORRECT = \"Output is partially correct\";\nstd::string RESULT_MESSAGE_WRONG = \"Output isn't correct\";\nstd::string RESULT_MESSAGE_SECURITY_VIOLATION = \"Security Violation\";\nstd::string RESULT_MESSAGE_PROTOCOL_VIOLATION = \"Protocol Violation\";\nstd::string RESULT_MESSAGE_FAIL = \"Judge Failure; Contact staff!\";\n\nNORETURN void InStream::quit(TResult result, const char* msg)\n{\n if (TestlibFinalizeGuard::alive)\n testlibFinalizeGuard.quitCount++;\n\n // You can change maxMessageLength.\n // Example: 'inf.maxMessageLength = 1024 * 1024;'.\n if (strlen(msg) > maxMessageLength)\n {\n std::string message(msg);\n std::string warn = \"message length exceeds \" + vtos(maxMessageLength)\n + \", the message is truncated: \";\n msg = (warn + message.substr(0, maxMessageLength - warn.length())).c_str();\n }\n\n#ifndef ENABLE_UNEXPECTED_EOF\n if (result == _unexpected_eof)\n result = _pe;\n#endif\n\n if (mode != _output && result != _fail)\n {\n if (mode == _input && testlibMode == _validator && lastLine != -1)\n quits(_fail, std::string(msg) + \" (\" + name + \", line \" + vtos(lastLine) + \")\");\n else\n quits(_fail, std::string(msg) + \" (\" + name + \")\");\n }\n\n std::FILE * resultFile;\n std::string errorName;\n \n if (__testlib_shouldCheckDirt(result))\n {\n if (testlibMode != _interactor && !ouf.seekEof())\n quit(_dirt, \"Extra information in the output file\");\n }\n\n int pctype = result - _partially;\n bool isPartial = false;\n\n if (testlibMode == _checker) {\n WORD color;\n std::string pointsStr = \"0\";\n switch (result)\n {\n case _ok:\n pointsStr = format(\"%d\", 1);\n color = LightGreen;\n errorName = RESULT_MESSAGE_CORRECT;\n break;\n case _wa:\n case _pe:\n case _dirt:\n case _unexpected_eof:\n color = LightRed;\n errorName = RESULT_MESSAGE_WRONG;\n break;\n case _fail:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_FAIL;\n break;\n case _sv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_SECURITY_VIOLATION;\n break;\n case _pv:\n color = LightMagenta;\n errorName = RESULT_MESSAGE_PROTOCOL_VIOLATION;\n break;\n case _points:\n if (__testlib_points < 1e-5)\n pointsStr = \"0.00001\"; // Prevent zero scores in CMS as zero is considered wrong\n else if (__testlib_points < 0.0001)\n pointsStr = format(\"%lf\", __testlib_points); // Prevent rounding the numbers below 0.0001\n else\n pointsStr = format(\"%.4lf\", __testlib_points);\n color = LightYellow;\n errorName = RESULT_MESSAGE_PARTIALLY_CORRECT;\n break;\n default:\n if (result >= _partially)\n quit(_fail, \"testlib partially mode not supported\");\n else\n quit(_fail, \"What is the code ??? \");\n } \n std::fprintf(stdout, \"%s\\n\", pointsStr.c_str());\n quitscrS(color, errorName);\n std::fprintf(stderr, \"\\n\");\n } else {\n switch (result)\n {\n case _ok:\n errorName = \"ok \";\n quitscrS(LightGreen, errorName);\n break;\n case _wa:\n errorName = \"wrong answer \";\n quitscrS(LightRed, errorName);\n break;\n case _pe:\n errorName = \"wrong output format \";\n quitscrS(LightRed, errorName);\n break;\n case _fail:\n errorName = \"FAIL \";\n quitscrS(LightRed, errorName);\n break;\n case _dirt:\n errorName = \"wrong output format \";\n quitscrS(LightCyan, errorName);\n result = _pe;\n break;\n case _points:\n errorName = \"points \";\n quitscrS(LightYellow, errorName);\n break;\n case _unexpected_eof:\n errorName = \"unexpected eof \";\n quitscrS(LightCyan, errorName);\n break;\n default:\n if (result >= _partially)\n {\n errorName = format(\"partially correct (%d) \", pctype);\n isPartial = true;\n quitscrS(LightYellow, errorName);\n }\n else\n quit(_fail, \"What is the code ??? \");\n }\n }\n\n if (resultName != \"\")\n {\n resultFile = std::fopen(resultName.c_str(), \"w\");\n if (resultFile == NULL)\n quit(_fail, \"Can not write to the result file\");\n if (appesMode)\n {\n std::fprintf(resultFile, \"\");\n if (isPartial)\n std::fprintf(resultFile, \"\", outcomes[(int)_partially].c_str(), pctype);\n else\n {\n if (result != _points)\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str());\n else\n {\n if (__testlib_points == std::numeric_limits::infinity())\n quit(_fail, \"Expected points, but infinity found\");\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", __testlib_points));\n std::fprintf(resultFile, \"\", outcomes[(int)result].c_str(), stringPoints.c_str());\n }\n }\n xmlSafeWrite(resultFile, msg);\n std::fprintf(resultFile, \"\\n\");\n }\n else\n std::fprintf(resultFile, \"%s\", msg);\n if (NULL == resultFile || fclose(resultFile) != 0)\n quit(_fail, \"Can not write to the result file\");\n }\n\n quitscr(LightGray, msg);\n std::fprintf(stderr, \"\\n\");\n\n inf.close();\n ouf.close();\n ans.close();\n if (tout.is_open())\n tout.close();\n\n textColor(LightGray);\n\n if (resultName != \"\")\n std::fprintf(stderr, \"See file to check exit message\\n\");\n\n halt(resultExitCode(result));\n}\n\n#ifdef __GNUC__\n __attribute__ ((format (printf, 3, 4)))\n#endif\nNORETURN void InStream::quitf(TResult result, const char* msg, ...)\n{\n FMT_TO_RESULT(msg, msg, message);\n InStream::quit(result, message.c_str());\n}\n\nNORETURN void InStream::quits(TResult result, std::string msg)\n{\n InStream::quit(result, msg.c_str());\n}\n\nvoid InStream::xmlSafeWrite(std::FILE * file, const char* msg)\n{\n size_t lmsg = strlen(msg);\n for (size_t i = 0; i < lmsg; i++)\n {\n if (msg[i] == '&')\n {\n std::fprintf(file, \"%s\", \"&\");\n continue;\n }\n if (msg[i] == '<')\n {\n std::fprintf(file, \"%s\", \"<\");\n continue;\n }\n if (msg[i] == '>')\n {\n std::fprintf(file, \"%s\", \">\");\n continue;\n }\n if (msg[i] == '\"')\n {\n std::fprintf(file, \"%s\", \""\");\n continue;\n }\n if (0 <= msg[i] && msg[i] <= 31)\n {\n std::fprintf(file, \"%c\", '.');\n continue;\n }\n std::fprintf(file, \"%c\", msg[i]);\n }\n}\n\nvoid InStream::quitscrS(WORD color, std::string msg)\n{\n quitscr(color, msg.c_str());\n}\n\nvoid InStream::quitscr(WORD color, const char* msg)\n{\n if (resultName == \"\")\n {\n textColor(color);\n std::fprintf(stderr, \"%s\", msg);\n textColor(LightGray);\n }\n}\n\nvoid InStream::reset(std::FILE* file)\n{\n if (opened && stdfile)\n quit(_fail, \"Can't reset standard handle\");\n\n if (opened)\n close();\n\n if (!stdfile)\n if (NULL == (file = std::fopen(name.c_str(), \"rb\")))\n {\n if (mode == _output)\n quits(_pe, std::string(\"Output file not found: \\\"\") + name + \"\\\"\");\n \n if (mode == _answer)\n quits(_fail, std::string(\"Answer file not found: \\\"\") + name + \"\\\"\");\n }\n\n if (NULL != file)\n {\n opened = true;\n\n __testlib_set_binary(file);\n\n if (stdfile)\n reader = new FileInputStreamReader(file, name);\n else\n reader = new BufferedFileInputStreamReader(file, name);\n }\n else\n {\n opened = false;\n reader = NULL;\n }\n}\n\nvoid InStream::init(std::string fileName, TMode mode)\n{\n opened = false;\n name = fileName;\n stdfile = false;\n this->mode = mode;\n \n std::ifstream stream;\n stream.open(fileName.c_str(), std::ios::in);\n if (stream.is_open())\n {\n std::streampos start = stream.tellg();\n stream.seekg(0, std::ios::end);\n std::streampos end = stream.tellg();\n size_t fileSize = size_t(end - start);\n stream.close();\n \n // You can change maxFileSize.\n // Example: 'inf.maxFileSize = 256 * 1024 * 1024;'.\n if (fileSize > maxFileSize)\n quitf(_pe, \"File size exceeds %d bytes, size is %d\", int(maxFileSize), int(fileSize));\n }\n\n reset();\n}\n\nvoid InStream::init(std::FILE* f, TMode mode)\n{\n opened = false;\n name = \"untitled\";\n this->mode = mode;\n \n if (f == stdin)\n name = \"stdin\", stdfile = true;\n if (f == stdout)\n name = \"stdout\", stdfile = true;\n if (f == stderr)\n name = \"stderr\", stdfile = true;\n\n reset(f);\n}\n\nchar InStream::curChar()\n{\n return char(reader->curChar());\n}\n\nchar InStream::nextChar()\n{\n return char(reader->nextChar());\n}\n\nchar InStream::readChar()\n{\n return nextChar();\n}\n\nchar InStream::readChar(char c)\n{\n lastLine = reader->getLine();\n char found = readChar();\n if (c != found)\n {\n if (!isEoln(found))\n quit(_pe, (\"Unexpected character '\" + std::string(1, found) + \"', but '\" + std::string(1, c) + \"' expected\").c_str());\n else\n quit(_pe, (\"Unexpected character \" + (\"#\" + vtos(int(found))) + \", but '\" + std::string(1, c) + \"' expected\").c_str());\n }\n return found;\n}\n\nchar InStream::readSpace()\n{\n return readChar(' ');\n}\n\nvoid InStream::unreadChar(char c)\n{\n reader->unreadChar(c);\n}\n\nvoid InStream::skipChar()\n{\n reader->skipChar();\n}\n\nvoid InStream::skipBlanks()\n{\n while (isBlanks(reader->curChar()))\n reader->skipChar();\n}\n\nstd::string InStream::readWord()\n{\n readWordTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nvoid InStream::readWordTo(std::string& result)\n{\n if (!strict)\n skipBlanks();\n\n lastLine = reader->getLine();\n int cur = reader->nextChar();\n\n if (cur == EOFC)\n quit(_unexpected_eof, \"Unexpected end of file - token expected\");\n\n if (isBlanks(cur))\n quit(_pe, \"Unexpected white-space - token expected\");\n\n result.clear();\n\n while (!(isBlanks(cur) || cur == EOFC))\n {\n result += char(cur);\n \n // You can change maxTokenLength.\n // Example: 'inf.maxTokenLength = 128 * 1024 * 1024;'.\n if (result.length() > maxTokenLength)\n quitf(_pe, \"Length of token exceeds %d, token is '%s...'\", int(maxTokenLength), __testlib_part(result).c_str());\n\n cur = reader->nextChar();\n }\n\n reader->unreadChar(cur);\n\n if (result.length() == 0)\n quit(_unexpected_eof, \"Unexpected end of file or white-space - token expected\");\n}\n\nstd::string InStream::readToken()\n{\n return readWord();\n}\n\nvoid InStream::readTokenTo(std::string& result)\n{\n readWordTo(result);\n}\n\nstatic std::string __testlib_part(const std::string& s)\n{\n if (s.length() <= 64)\n return s;\n else\n return s.substr(0, 30) + \"...\" + s.substr(s.length() - 31, 31);\n}\n\n#define __testlib_readMany(readMany, readOne, typeName, space) \\\n if (size < 0) \\\n quit(_fail, #readMany \": size should be non-negative.\"); \\\n if (size > 100000000) \\\n quit(_fail, #readMany \": size should be at most 100000000.\"); \\\n \\\n std::vector result(size); \\\n readManyIteration = indexBase; \\\n \\\n for (int i = 0; i < size; i++) \\\n { \\\n result[i] = readOne; \\\n readManyIteration++; \\\n if (strict && space && i + 1 < size) \\\n readSpace(); \\\n } \\\n \\\n readManyIteration = NO_INDEX; \\\n return result; \\\n\nstd::string InStream::readWord(const pattern& p, const std::string& variableName)\n{\n readWordTo(_tmpReadToken);\n if (!p.matches(_tmpReadToken))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Token element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token element \" + variableName + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(_tmpReadToken) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n return _tmpReadToken;\n}\n\nstd::vector InStream::readWords(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readWord(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(pattern(ptrn), variableName);\n}\n\nstd::vector InStream::readWords(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readWords, readWord(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const pattern& p, const std::string& variableName)\n{\n return readWord(p, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readTokens, readToken(p, variablesName), std::string, true);\n}\n\nstd::string InStream::readToken(const std::string& ptrn, const std::string& variableName)\n{\n return readWord(ptrn, variableName);\n}\n\nstd::vector InStream::readTokens(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readTokens, readWord(p, variablesName), std::string, true);\n}\n\nvoid InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readWordTo(result);\n if (!p.matches(result))\n {\n if (variableName.empty())\n quit(_wa, (\"Token \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Token parameter [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n}\n\nvoid InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, pattern(ptrn), variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n return readWordTo(result, p, variableName);\n}\n\nvoid InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n return readWordTo(result, ptrn, variableName);\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(long long integer, const char* s)\n{\n if (integer == LLONG_MIN)\n return strcmp(s, \"-9223372036854775808\") == 0;\n\n if (integer == 0LL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n if (integer < 0 && s[0] != '-')\n return false;\n\n if (integer < 0)\n s++, length--, integer = -integer;\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\n#ifdef __GNUC__\n__attribute__((pure))\n#endif\nstatic inline bool equals(unsigned long long integer, const char* s)\n{\n if (integer == ULLONG_MAX)\n return strcmp(s, \"18446744073709551615\") == 0;\n\n if (integer == 0ULL)\n return strcmp(s, \"0\") == 0;\n\n size_t length = strlen(s);\n\n if (length == 0)\n return false;\n\n while (integer > 0)\n {\n int digit = int(integer % 10);\n\n if (s[length - 1] != '0' + digit)\n return false;\n\n length--;\n integer /= 10;\n }\n\n return length == 0;\n}\n\nstatic inline double stringToDouble(InStream& in, const char* buffer)\n{\n double retval;\n\n size_t length = strlen(buffer);\n\n int minusCount = 0;\n int plusCount = 0;\n int decimalPointCount = 0;\n int digitCount = 0;\n int eCount = 0;\n\n for (size_t i = 0; i < length; i++)\n {\n if (('0' <= buffer[i] && buffer[i] <= '9') || buffer[i] == '.'\n || buffer[i] == 'e' || buffer[i] == 'E'\n || buffer[i] == '-' || buffer[i] == '+')\n {\n if ('0' <= buffer[i] && buffer[i] <= '9')\n digitCount++;\n if (buffer[i] == 'e' || buffer[i] == 'E')\n eCount++;\n if (buffer[i] == '-')\n minusCount++;\n if (buffer[i] == '+')\n plusCount++;\n if (buffer[i] == '.')\n decimalPointCount++;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n // If for sure is not a number in standard notation or in e-notation.\n if (digitCount == 0 || minusCount > 2 || plusCount > 2 || decimalPointCount > 1 || eCount > 1)\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)\n{\n if (minAfterPointDigitCount < 0)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be non-negative.\");\n \n if (minAfterPointDigitCount > maxAfterPointDigitCount)\n in.quit(_fail, \"stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.\");\n\n double retval;\n\n size_t length = strlen(buffer);\n\n if (length == 0 || length > 1000)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int pointPos = -1; \n for (size_t i = 1; i + 1 < length; i++)\n {\n if (buffer[i] == '.')\n {\n if (pointPos > -1)\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n pointPos = int(i);\n }\n if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n }\n\n if (buffer[length - 1] < '0' || buffer[length - 1] > '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);\n if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)\n in.quit(_pe, (\"Expected strict double with number of digits after point in range [\"\n + vtos(minAfterPointDigitCount)\n + \",\"\n + vtos(maxAfterPointDigitCount)\n + \"], but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str()\n );\n\n int firstDigitPos = -1;\n for (size_t i = 0; i < length; i++)\n if (buffer[i] >= '0' && buffer[i] <= '9')\n {\n firstDigitPos = int(i);\n break;\n }\n\n if (firstDigitPos > 1 || firstDigitPos == -1) \n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)\n && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')\n in.quit(_pe, (\"Expected strict double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n char* suffix = new char[length + 1];\n int scanned = std::sscanf(buffer, \"%lf%s\", &retval, suffix);\n bool empty = strlen(suffix) == 0;\n delete[] suffix;\n\n if (scanned == 1 || (scanned == 2 && empty))\n {\n if (__testlib_isNaN(retval) || __testlib_isInfinite(retval))\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n return retval;\n }\n else\n in.quit(_pe, (\"Expected double, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline long long stringToLongLong(InStream& in, const char* buffer)\n{\n if (strcmp(buffer, \"-9223372036854775808\") == 0)\n return LLONG_MIN;\n\n bool minus = false;\n size_t length = strlen(buffer);\n \n if (length > 1 && buffer[0] == '-')\n minus = true;\n\n if (length > 20)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n long long retval = 0LL;\n\n int zeroes = 0;\n int processingZeroes = true;\n \n for (int i = (minus ? 1 : 0); i < int(length); i++)\n {\n if (buffer[i] == '0' && processingZeroes)\n zeroes++;\n else\n processingZeroes = false;\n\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (retval < 0)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n \n if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)\n in.quit(_pe, (\"Expected integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n retval = (minus ? -retval : +retval);\n\n if (length < 19)\n return retval;\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nstatic inline unsigned long long stringToUnsignedLongLong(InStream& in, const char* buffer)\n{\n size_t length = strlen(buffer);\n\n if (length > 20)\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n if (length > 1 && buffer[0] == '0')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n unsigned long long retval = 0LL;\n for (int i = 0; i < int(length); i++)\n {\n if (buffer[i] < '0' || buffer[i] > '9')\n in.quit(_pe, (\"Expected unsigned integer, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n retval = retval * 10 + (buffer[i] - '0');\n }\n\n if (length < 19)\n return retval;\n\n if (length == 20 && strcmp(buffer, \"18446744073709551615\") == 1)\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n\n if (equals(retval, buffer))\n return retval;\n else\n in.quit(_pe, (\"Expected unsigned int64, but \\\"\" + __testlib_part(buffer) + \"\\\" found\").c_str());\n}\n\nint InStream::readInteger()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int32 expected\");\n\n readWordTo(_tmpReadToken);\n \n long long value = stringToLongLong(*this, _tmpReadToken.c_str());\n if (value < INT_MIN || value > INT_MAX)\n quit(_pe, (\"Expected int32, but \\\"\" + __testlib_part(_tmpReadToken) + \"\\\" found\").c_str());\n \n return int(value);\n}\n\nlong long InStream::readLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToLongLong(*this, _tmpReadToken.c_str());\n}\n\nunsigned long long InStream::readUnsignedLong()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - int64 expected\");\n\n readWordTo(_tmpReadToken);\n\n return stringToUnsignedLongLong(*this, _tmpReadToken.c_str());\n}\n\nlong long InStream::readLong(long long minv, long long maxv, const std::string& variableName)\n{\n long long result = readLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readLongs(int size, long long minv, long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLongs, readLong(minv, maxv, variablesName), long long, true)\n}\n\nunsigned long long InStream::readUnsignedLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n unsigned long long result = readUnsignedLong();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Unsigned integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Unsigned integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nstd::vector InStream::readUnsignedLongs(int size, unsigned long long minv, unsigned long long maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readUnsignedLongs, readUnsignedLong(minv, maxv, variablesName), unsigned long long, true)\n}\n\nunsigned long long InStream::readLong(unsigned long long minv, unsigned long long maxv, const std::string& variableName)\n{\n return readUnsignedLong(minv, maxv, variableName);\n}\n\nint InStream::readInt()\n{\n return readInteger();\n}\n\nint InStream::readInt(int minv, int maxv, const std::string& variableName)\n{\n int result = readInt();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Integer \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Integer element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Integer element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(minv == result, maxv == result));\n\n return result;\n}\n\nint InStream::readInteger(int minv, int maxv, const std::string& variableName)\n{\n return readInt(minv, maxv, variableName);\n}\n\nstd::vector InStream::readInts(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readInts, readInt(minv, maxv, variablesName), int, true)\n}\n\nstd::vector InStream::readIntegers(int size, int minv, int maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readIntegers, readInt(minv, maxv, variablesName), int, true)\n}\n\ndouble InStream::readReal()\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - double expected\");\n\n return stringToDouble(*this, readWord().c_str());\n}\n\ndouble InStream::readDouble()\n{\n return readReal();\n}\n\ndouble InStream::readReal(double minv, double maxv, const std::string& variableName)\n{\n double result = readReal();\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readReals(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readReals, readReal(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readDouble(double minv, double maxv, const std::string& variableName)\n{\n return readReal(minv, maxv, variableName);\n} \n\nstd::vector InStream::readDoubles(int size, double minv, double maxv, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readDoubles, readDouble(minv, maxv, variablesName), double, true)\n}\n\ndouble InStream::readStrictReal(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n if (!strict && seekEof())\n quit(_unexpected_eof, \"Unexpected end of file - strict double expected\");\n\n double result = stringToStrictDouble(*this, readWord().c_str(),\n minAfterPointDigitCount, maxAfterPointDigitCount);\n\n if (result < minv || result > maxv)\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double \" + vtos(result) + \" violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double parameter [name=\" + std::string(variableName) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Strict double element [index=\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n else\n quit(_wa, (\"Strict double element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \" + vtos(result) + \", violates the range [\" + vtos(minv) + \", \" + vtos(maxv) + \"]\").c_str());\n }\n }\n\n if (strict && !variableName.empty())\n validator.addBoundsHit(variableName, ValidatorBoundsHit(\n doubleDelta(minv, result) < ValidatorBoundsHit::EPS,\n doubleDelta(maxv, result) < ValidatorBoundsHit::EPS\n ));\n\n return result;\n}\n\nstd::vector InStream::readStrictReals(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictReals, readStrictReal(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\ndouble InStream::readStrictDouble(double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variableName)\n{\n return readStrictReal(minv, maxv,\n minAfterPointDigitCount, maxAfterPointDigitCount,\n variableName);\n}\n\nstd::vector InStream::readStrictDoubles(int size, double minv, double maxv,\n int minAfterPointDigitCount, int maxAfterPointDigitCount,\n const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrictDoubles, readStrictDouble(minv, maxv, minAfterPointDigitCount, maxAfterPointDigitCount, variablesName), double, true)\n}\n\nbool InStream::eof()\n{\n if (!strict && NULL == reader)\n return true;\n\n return reader->eof();\n}\n\nbool InStream::seekEof()\n{\n if (!strict && NULL == reader)\n return true;\n skipBlanks();\n return eof();\n}\n\nbool InStream::eoln()\n{\n if (!strict && NULL == reader)\n return true;\n\n int c = reader->nextChar();\n\n if (!strict)\n {\n if (c == EOFC)\n return true;\n\n if (c == CR)\n {\n c = reader->nextChar();\n\n if (c != LF)\n {\n reader->unreadChar(c);\n reader->unreadChar(CR);\n return false;\n }\n else\n return true;\n }\n \n if (c == LF)\n return true;\n\n reader->unreadChar(c);\n return false;\n }\n else\n {\n bool returnCr = false;\n\n#if (defined(ON_WINDOWS) && !defined(FOR_LINUX)) || defined(FOR_WINDOWS)\n if (c != CR)\n {\n reader->unreadChar(c);\n return false;\n }\n else\n {\n if (!returnCr)\n returnCr = true;\n c = reader->nextChar();\n }\n#endif \n if (c != LF)\n {\n reader->unreadChar(c);\n if (returnCr)\n reader->unreadChar(CR);\n return false;\n }\n\n return true;\n }\n}\n\nvoid InStream::readEoln()\n{\n lastLine = reader->getLine();\n if (!eoln())\n quit(_pe, \"Expected EOLN\");\n}\n\nvoid InStream::readEof()\n{\n lastLine = reader->getLine();\n if (!eof())\n quit(_pe, \"Expected EOF\");\n\n if (TestlibFinalizeGuard::alive && this == &inf)\n testlibFinalizeGuard.readEofCount++;\n}\n\nbool InStream::seekEoln()\n{\n if (!strict && NULL == reader)\n return true;\n \n int cur;\n do\n {\n cur = reader->nextChar();\n } \n while (cur == SPACE || cur == TAB);\n\n reader->unreadChar(cur);\n return eoln();\n}\n\nvoid InStream::nextLine()\n{\n readLine();\n}\n\nvoid InStream::readStringTo(std::string& result)\n{\n if (NULL == reader)\n quit(_pe, \"Expected line\");\n\n result.clear();\n\n for (;;)\n {\n int cur = reader->curChar();\n\n if (cur == LF || cur == EOFC)\n break;\n\n if (cur == CR)\n {\n cur = reader->nextChar();\n if (reader->curChar() == LF)\n {\n reader->unreadChar(cur);\n break;\n }\n }\n\n lastLine = reader->getLine();\n result += char(reader->nextChar());\n }\n\n if (strict)\n readEoln();\n else\n eoln();\n}\n\nstd::string InStream::readString()\n{\n readStringTo(_tmpReadToken);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, int indexBase)\n{\n __testlib_readMany(readStrings, readString(), std::string, false)\n}\n\nvoid InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result);\n if (!p.matches(result))\n {\n if (readManyIteration == NO_INDEX)\n {\n if (variableName.empty())\n quit(_wa, (\"Line \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line [name=\" + variableName + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n else\n {\n if (variableName.empty())\n quit(_wa, (\"Line element [index=\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\" doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n else\n quit(_wa, (\"Line element \" + std::string(variableName) + \"[\" + vtos(readManyIteration) + \"] equals to \\\"\" + __testlib_part(result) + \"\\\", doesn't correspond to pattern \\\"\" + p.src() + \"\\\"\").c_str());\n }\n }\n}\n\nvoid InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, pattern(ptrn), variableName);\n}\n\nstd::string InStream::readString(const pattern& p, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, p, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readString(const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(_tmpReadToken, ptrn, variableName);\n return _tmpReadToken;\n}\n\nstd::vector InStream::readStrings(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readStrings, readString(p, variablesName), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result)\n{\n readStringTo(result);\n}\n\nstd::string InStream::readLine()\n{\n return readString();\n}\n\nstd::vector InStream::readLines(int size, int indexBase)\n{\n __testlib_readMany(readLines, readString(), std::string, false)\n}\n\nvoid InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)\n{\n readStringTo(result, p, variableName);\n}\n\nvoid InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)\n{\n readStringTo(result, ptrn, variableName);\n}\n\nstd::string InStream::readLine(const pattern& p, const std::string& variableName)\n{\n return readString(p, variableName);\n}\n\nstd::vector InStream::readLines(int size, const pattern& p, const std::string& variablesName, int indexBase)\n{\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\nstd::string InStream::readLine(const std::string& ptrn, const std::string& variableName)\n{\n return readString(ptrn, variableName);\n}\n\nstd::vector InStream::readLines(int size, const std::string& ptrn, const std::string& variablesName, int indexBase)\n{\n pattern p(ptrn);\n __testlib_readMany(readLines, readString(p, variablesName), std::string, false)\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid InStream::ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n this->__testlib_ensure(cond, message);\n }\n}\n\nvoid InStream::__testlib_ensure(bool cond, std::string message)\n{\n if (!cond)\n this->quit(_wa, message.c_str()); \n}\n\nvoid InStream::close()\n{\n if (NULL != reader)\n {\n reader->close();\n delete reader;\n reader = NULL;\n }\n \n opened = false;\n}\n\nNORETURN void quit(TResult result, const std::string& msg)\n{\n ouf.quit(result, msg.c_str());\n}\n\nNORETURN void quit(TResult result, const char* msg)\n{\n ouf.quit(result, msg);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...);\n\nNORETURN void __testlib_quitp(double points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %lf, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = removeDoubleTrailingZeroes(format(\"%.10f\", points));\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void __testlib_quitp(int points, const char* message)\n{\n if (points<0 || points>1)\n quitf(_fail, \"wrong points: %d, it must be in [0,1]\", points);\n __testlib_points = points;\n std::string stringPoints = format(\"%d\", points);\n\n std::string quitMessage;\n if (NULL == message || 0 == strlen(message))\n quitMessage = stringPoints;\n else\n quitMessage = message;\n\n quit(_points, quitMessage.c_str());\n}\n\nNORETURN void quitp(float points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(double points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\nNORETURN void quitp(long double points, const std::string& message = \"\")\n{\n __testlib_quitp(double(points), message.c_str());\n}\n\nNORETURN void quitp(int points, const std::string& message = \"\")\n{\n __testlib_quitp(points, message.c_str());\n}\n\ntemplate\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitp(F points, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quitp(points, message);\n}\n\ntemplate\nNORETURN void quitp(F points)\n{\n __testlib_quitp(points, std::string(\"\"));\n}\n\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\nNORETURN void quitf(TResult result, const char* format, ...)\n{\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 3, 4)))\n#endif\nvoid quitif(bool condition, TResult result, const char* format, ...)\n{\n if (condition)\n {\n FMT_TO_RESULT(format, format, message);\n quit(result, message);\n }\n}\n\nNORETURN void __testlib_help()\n{\n InStream::textColor(InStream::LightCyan);\n std::fprintf(stderr, \"TESTLIB %s, https://github.com/MikeMirzayanov/testlib/ \", VERSION);\n std::fprintf(stderr, \"by Mike Mirzayanov, copyright(c) 2005-2018\\n\");\n std::fprintf(stderr, \"Checker name: \\\"%s\\\"\\n\", checkerName.c_str());\n InStream::textColor(InStream::LightGray);\n\n std::fprintf(stderr, \"\\n\");\n std::fprintf(stderr, \"Latest features: \\n\");\n for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)\n {\n std::fprintf(stderr, \"*) %s\\n\", latestFeatures[i]);\n }\n std::fprintf(stderr, \"\\n\");\n\n std::fprintf(stderr, \"Program must be run with the following arguments: \\n\");\n std::fprintf(stderr, \" [ [<-appes>]]\\n\\n\");\n\n std::exit(FAIL_EXIT_CODE);\n}\n\nstatic void __testlib_ensuresPreconditions()\n{\n // testlib assumes: sizeof(int) = 4.\n __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);\n\n // testlib assumes: INT_MAX == 2147483647.\n __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);\n\n // testlib assumes: sizeof(long long) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);\n\n // testlib assumes: sizeof(double) = 8.\n __TESTLIB_STATIC_ASSERT(sizeof(double) == 8);\n\n // testlib assumes: no -ffast-math.\n if (!__testlib_isNaN(+__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n if (!__testlib_isNaN(-__testlib_nan()))\n quit(_fail, \"Function __testlib_isNaN is not working correctly: possible reason is '-ffast-math'\");\n}\n\nvoid registerGen(int argc, char* argv[], int randomGeneratorVersion)\n{\n if (randomGeneratorVersion < 0 || randomGeneratorVersion > 1)\n quitf(_fail, \"Random generator version is expected to be 0 or 1.\");\n random_t::version = randomGeneratorVersion;\n\n __testlib_ensuresPreconditions();\n\n testlibMode = _generator;\n __testlib_set_binary(stdin);\n rnd.setSeed(argc, argv);\n}\n\n#ifdef USE_RND_AS_BEFORE_087\nvoid registerGen(int argc, char* argv[])\n{\n registerGen(argc, argv, 0);\n}\n#else\n#ifdef __GNUC__\n#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4))\n __attribute__ ((deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\")))\n#else\n __attribute__ ((deprecated))\n#endif\n#endif\n#ifdef _MSC_VER\n __declspec(deprecated(\"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\"))\n#endif\nvoid registerGen(int argc, char* argv[])\n{\n std::fprintf(stderr, \"Use registerGen(argc, argv, 0) or registerGen(argc, argv, 1).\"\n \" The third parameter stands for the random generator version.\"\n \" If you are trying to compile old generator use macro -DUSE_RND_AS_BEFORE_087 or registerGen(argc, argv, 0).\"\n \" Version 1 has been released on Spring, 2013. Use it to write new generators.\\n\\n\");\n registerGen(argc, argv, 0);\n}\n#endif\n\nvoid registerInteraction(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _interactor;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n \n if (argc < 3 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [ [<-appes>]]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc <= 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n#ifndef EJUDGE\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n#endif\n\n inf.init(argv[1], _input);\n\n tout.open(argv[2], std::ios_base::out);\n if (tout.fail() || !tout.is_open())\n quit(_fail, std::string(\"Can not write to the test-output-file '\") + argv[2] + std::string(\"'\"));\n\n ouf.init(stdin, _output);\n \n if (argc >= 4)\n ans.init(argv[3], _answer);\n else\n ans.name = \"unopened answer stream\";\n}\n\nvoid registerValidation()\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _validator;\n __testlib_set_binary(stdin);\n\n inf.init(stdin, _input);\n inf.strict = true;\n}\n\nvoid registerValidation(int argc, char* argv[])\n{\n registerValidation();\n\n for (int i = 1; i < argc; i++)\n {\n if (!strcmp(\"--testset\", argv[i]))\n {\n if (i + 1 < argc && strlen(argv[i + 1]) > 0)\n validator.setTestset(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--group\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setGroup(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n if (!strcmp(\"--testOverviewLogFileName\", argv[i]))\n {\n if (i + 1 < argc)\n validator.setTestOverviewLogFileName(argv[++i]);\n else\n quit(_fail, std::string(\"Validator must be run with the following arguments: \") +\n \"[--testset testset] [--group group] [--testOverviewLogFileName fileName]\");\n }\n } \n}\n\nvoid addFeature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.addFeature(feature); \n}\n\nvoid feature(const std::string& feature)\n{\n if (testlibMode != _validator)\n quit(_fail, \"Features are supported in validators only.\");\n validator.feature(feature); \n}\n\nvoid registerTestlibCmd(int argc, char* argv[])\n{\n __testlib_ensuresPreconditions();\n\n testlibMode = _checker;\n __testlib_set_binary(stdin);\n\n if (argc > 1 && !strcmp(\"--help\", argv[1]))\n __testlib_help();\n\n if (argc < 4 || argc > 6)\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n std::string(\" [ [<-appes>]]\") + \n \"\\nUse \\\"--help\\\" to get help information\");\n }\n\n if (argc == 4)\n {\n resultName = \"\";\n appesMode = false;\n }\n\n if (argc == 5)\n {\n resultName = argv[4];\n appesMode = false;\n }\n\n if (argc == 6)\n {\n if (strcmp(\"-APPES\", argv[5]) && strcmp(\"-appes\", argv[5]))\n {\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n }\n else\n {\n resultName = argv[4];\n appesMode = true;\n }\n }\n\n inf.init(argv[1], _input);\n ans.init(argv[2], _answer);\n ouf.init(argv[3], _output);\n}\n\nvoid registerTestlib(int argc, ...)\n{\n if (argc < 3 || argc > 5)\n quit(_fail, std::string(\"Program must be run with the following arguments: \") +\n \" [ [<-appes>]]\");\n\n char** argv = new char*[argc + 1];\n \n va_list ap;\n va_start(ap, argc);\n argv[0] = NULL;\n for (int i = 0; i < argc; i++)\n {\n argv[i + 1] = va_arg(ap, char*);\n }\n va_end(ap);\n\n registerTestlibCmd(argc + 1, argv);\n delete[] argv;\n}\n\nstatic inline void __testlib_ensure(bool cond, const std::string& msg)\n{\n if (!cond)\n quit(_fail, msg.c_str());\n}\n\n#ifdef __GNUC__\n __attribute__((unused)) \n#endif\nstatic inline void __testlib_ensure(bool cond, const char* msg)\n{\n if (!cond)\n quit(_fail, msg);\n}\n\n#define ensure(cond) __testlib_ensure(cond, \"Condition failed: \\\"\" #cond \"\\\"\")\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 2, 3)))\n#endif\ninline void ensuref(bool cond, const char* format, ...)\n{\n if (!cond)\n {\n FMT_TO_RESULT(format, format, message);\n __testlib_ensure(cond, message);\n }\n}\n\nNORETURN static void __testlib_fail(const std::string& message)\n{\n quitf(_fail, \"%s\", message.c_str());\n}\n\n#ifdef __GNUC__\n__attribute__ ((format (printf, 1, 2)))\n#endif\nvoid setName(const char* format, ...)\n{\n FMT_TO_RESULT(format, format, name);\n checkerName = name;\n}\n\n/* \n * Do not use random_shuffle, because it will produce different result\n * for different C++ compilers.\n *\n * This implementation uses testlib random_t to produce random numbers, so\n * it is stable.\n */ \ntemplate\nvoid shuffle(_RandomAccessIter __first, _RandomAccessIter __last)\n{\n if (__first == __last) return;\n for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)\n std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));\n}\n\n\ntemplate\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use random_shuffle(), use shuffle() instead\")))\n#endif\nvoid random_shuffle(_RandomAccessIter , _RandomAccessIter )\n{\n quitf(_fail, \"Don't use random_shuffle(), use shuffle() instead\");\n}\n\n#ifdef __GLIBC__\n# define RAND_THROW_STATEMENT throw()\n#else\n# define RAND_THROW_STATEMENT\n#endif\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use rand(), use rnd.next() instead\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nint rand() RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use rand(), use rnd.next() instead\");\n \n /* This line never runs. */\n //throw \"Don't use rand(), use rnd.next() instead\";\n}\n\n#if defined(__GNUC__) && !defined(__clang__)\n__attribute__ ((error(\"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1).\")))\n#endif\n#ifdef _MSC_VER\n# pragma warning( disable : 4273 )\n#endif\nvoid srand(unsigned int seed) RAND_THROW_STATEMENT\n{\n quitf(_fail, \"Don't use srand(), you should use \" \n \"'registerGen(argc, argv, 1);' to initialize generator seed \"\n \"by hash code of the command line params. The third parameter \"\n \"is randomGeneratorVersion (currently the latest is 1) [ignored seed=%d].\", seed);\n}\n\nvoid startTest(int test)\n{\n const std::string testFileName = vtos(test);\n if (NULL == freopen(testFileName.c_str(), \"wt\", stdout))\n __testlib_fail(\"Unable to write file '\" + testFileName + \"'\");\n}\n\ninline std::string upperCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('a' <= s[i] && s[i] <= 'z')\n s[i] = char(s[i] - 'a' + 'A');\n return s;\n}\n\ninline std::string lowerCase(std::string s)\n{\n for (size_t i = 0; i < s.length(); i++)\n if ('A' <= s[i] && s[i] <= 'Z')\n s[i] = char(s[i] - 'A' + 'a');\n return s;\n}\n\ninline std::string compress(const std::string& s)\n{\n return __testlib_part(s);\n}\n\ninline std::string englishEnding(int x)\n{\n x %= 100;\n if (x / 10 == 1)\n return \"th\";\n if (x % 10 == 1)\n return \"st\";\n if (x % 10 == 2)\n return \"nd\";\n if (x % 10 == 3)\n return \"rd\";\n return \"th\";\n}\n\ninline std::string trim(const std::string& s)\n{\n if (s.empty())\n return s;\n\n int left = 0;\n while (left < int(s.length()) && isBlanks(s[left]))\n left++;\n if (left >= int(s.length()))\n return \"\";\n\n int right = int(s.length()) - 1;\n while (right >= 0 && isBlanks(s[right]))\n right--;\n if (right < 0)\n return \"\";\n\n return s.substr(left, right - left + 1);\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last, _Separator separator)\n{\n std::stringstream ss;\n bool repeated = false;\n for (_ForwardIterator i = first; i != last; i++)\n {\n if (repeated)\n ss << separator;\n else\n repeated = true;\n ss << *i;\n }\n return ss.str();\n}\n\ntemplate \nstd::string join(_ForwardIterator first, _ForwardIterator last)\n{\n return join(first, last, ' ');\n}\n\ntemplate \nstd::string join(const _Collection& collection, _Separator separator)\n{\n return join(collection.begin(), collection.end(), separator);\n}\n\ntemplate \nstd::string join(const _Collection& collection)\n{\n return join(collection, ' ');\n}\n\n/**\n * Splits string s by character separator returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning exactly k+1 items,\n * where k is the number of separator occurences.\n */ \nstd::vector split(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separator returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, char separator)\n{\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (s[i] == separator)\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n if (!item.empty())\n result.push_back(item);\n return result;\n}\n\n/**\n * Splits string s by character separators returning non-empty items.\n */ \nstd::vector tokenize(const std::string& s, const std::string& separators)\n{\n if (separators.empty())\n return std::vector(1, s);\n\n std::vector isSeparator(256);\n for (size_t i = 0; i < separators.size(); i++)\n isSeparator[(unsigned char)(separators[i])] = true;\n\n std::vector result;\n std::string item;\n for (size_t i = 0; i < s.length(); i++)\n if (isSeparator[(unsigned char)(s[i])])\n {\n if (!item.empty())\n result.push_back(item);\n item = \"\";\n }\n else\n item += s[i];\n \n if (!item.empty())\n result.push_back(item);\n\n return result;\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, std::string expected, std::string found, const char* prepend)\n{\n std::string message;\n if (strlen(prepend) != 0)\n message = format(\"%s: expected '%s', but found '%s'\",\n compress(prepend).c_str(), compress(expected).c_str(), compress(found).c_str());\n else\n message = format(\"expected '%s', but found '%s'\",\n compress(expected).c_str(), compress(found).c_str());\n quit(result, message);\n}\n\nNORETURN void __testlib_expectedButFound(TResult result, double expected, double found, const char* prepend)\n{\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend);\n}\n\ntemplate \n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, T expected, T found, const char* prependFormat = \"\", ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = vtos(expected);\n std::string foundString = vtos(found);\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, std::string expected, std::string found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, expected, found, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, double expected, double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n std::string expectedString = removeDoubleTrailingZeroes(format(\"%.12f\", expected));\n std::string foundString = removeDoubleTrailingZeroes(format(\"%.12f\", found));\n __testlib_expectedButFound(result, expectedString, foundString, prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, const char* expected, const char* found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, std::string(expected), std::string(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, float expected, float found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\ntemplate <>\n#ifdef __GNUC__\n__attribute__ ((format (printf, 4, 5)))\n#endif\nNORETURN void expectedButFound(TResult result, long double expected, long double found, const char* prependFormat, ...)\n{\n FMT_TO_RESULT(prependFormat, prependFormat, prepend);\n __testlib_expectedButFound(result, double(expected), double(found), prepend.c_str());\n}\n\n#endif\n\n#if __cplusplus > 199711L || defined(_MSC_VER)\ntemplate \nstruct is_iterable\n{\n template \n static char test(typename U::iterator* x);\n \n template \n static long test(U* x);\n \n static const bool value = sizeof(test(0)) == 1;\n};\n\ntemplate\nstruct __testlib_enable_if {};\n \ntemplate\nstruct __testlib_enable_if { typedef T type; };\n\ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n std::cout << t;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const T& t)\n{\n bool first = true;\n for (typename T::const_iterator i = t.begin(); i != t.end(); i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n std::cout << *i;\n }\n}\n\ntemplate<>\ntypename __testlib_enable_if::value, void>::type __testlib_print_one(const std::string& t)\n{\n std::cout << t;\n}\n \ntemplate\nvoid __println_range(A begin, B end)\n{\n bool first = true;\n for (B i = B(begin); i != end; i++)\n {\n if (first)\n first = false;\n else\n std::cout << \" \";\n __testlib_print_one(*i);\n }\n std::cout << std::endl;\n}\n\ntemplate\nstruct is_iterator\n{ \n static T makeT();\n typedef void * twoptrs[2];\n static twoptrs & test(...);\n template static typename R::iterator_category * test(R);\n template static void * test(R *);\n static const bool value = sizeof(test(makeT())) == sizeof(void *); \n};\n\ntemplate\nstruct is_iterator::value >::type>\n{\n static const bool value = false; \n};\n\ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n \ntemplate \ntypename __testlib_enable_if::value, void>::type println(const A& a, const B& b)\n{\n __println_range(a, b);\n}\n\ntemplate \nvoid println(const A* a, const A* b)\n{\n __println_range(a, b);\n}\n\ntemplate <>\nvoid println(const char* a, const char* b)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const T& x)\n{\n __testlib_print_one(x);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << std::endl;\n}\n\ntemplate\nvoid println(const A& a, const B& b, const C& c, const D& d, const E& e, const F& f, const G& g)\n{\n __testlib_print_one(a);\n std::cout << \" \";\n __testlib_print_one(b);\n std::cout << \" \";\n __testlib_print_one(c);\n std::cout << \" \";\n __testlib_print_one(d);\n std::cout << \" \";\n __testlib_print_one(e);\n std::cout << \" \";\n __testlib_print_one(f);\n std::cout << \" \";\n __testlib_print_one(g);\n std::cout << std::endl;\n}\n#endif\n\n\n\nvoid registerChecker(std::string probName, int argc, char* argv[])\n{\n setName(\"checker for problem %s\", probName.c_str());\n registerTestlibCmd(argc, argv);\n}\n\n\n\nconst std::string _grader_OK = \"OK\";\nconst std::string _grader_SV = \"SV\";\nconst std::string _grader_PV = \"PV\";\nconst std::string _grader_WA = \"WA\";\nconst std::string _grader_FAIL = \"FAIL\";\n\n\nvoid InStream::readSecret(\n std::string secret,\n TResult mismatchResult,\n std::string mismatchMessage,\n std::string eofMessage)\n{\n if (seekEof())\n quits(mismatchResult, eofMessage);\n if (readWord() != secret)\n quits(mismatchResult, mismatchMessage);\n eoln();\n}\n\nvoid readBothSecrets(std::string secret)\n{\n ans.readSecret(\n secret,\n _fail,\n \"Secret mismatch in the (correct) answer file\",\n \"Empty (correct) answer file\");\n ouf.readSecret(\n secret,\n _pv,\n \"Possible tampering with the output\",\n \"Early termination of the solution (possibly calling exit)\");\n}\n\n\nvoid InStream::quitByGraderResult(TResult result, std::string defaultMessage)\n{\n std::string msg = \"\";\n if (!eof())\n msg = readLine();\n if (msg.empty())\n quits(result, defaultMessage);\n quits(result, msg);\n}\n\nvoid InStream::readGraderResult()\n{\n std::string result = readWord();\n eoln();\n if (result == _grader_OK)\n return;\n if (result == _grader_SV)\n quitByGraderResult(_sv, \"Security violation detected in grader\");\n if (result == _grader_PV)\n quitByGraderResult(_pv, \"Protocol violation detected in grader\");\n if (result == _grader_WA)\n quitByGraderResult(_wa, \"Wrong answer detected in grader\");\n if (result == _grader_FAIL)\n quitByGraderResult(_fail, \"Failure in grader\");\n quitf(_fail, \"Unknown grader result\");\n}\n\nvoid readBothGraderResults()\n{\n ans.readGraderResult();\n ouf.readGraderResult();\n}\n\n\nNORETURN void quit(TResult result)\n{\n ouf.quit(result, \"\");\n}\n\n/// Used in validators: skips the rest of input, assuming it to be correct\nNORETURN void skip_ok()\n{\n if (testlibMode != _validator)\n quitf(_fail, \"skip_ok() only works in validators\");\n testlibFinalizeGuard.quitCount++;\n halt(0);\n}\n\n/// 1 -> 1st, 2 -> 2nd, 3 -> 3rd, 4 -> 4th, ...\nstd::string englishTh(int x)\n{\n char c[100];\n snprintf(c, sizeof(c), \"%d%s\", x, englishEnding(x).c_str());\n return c;\n}\n\n/// Compares the tokens of two lines\nvoid compareTokens(int lineNo, std::string a, std::string b, char separator=' ')\n{\n std::vector toka = tokenize(a, separator);\n std::vector tokb = tokenize(b, separator);\n if (toka == tokb)\n return;\n std::string dif = format(\"%s lines differ - \", englishTh(lineNo).c_str());\n if (toka.size() != tokb.size())\n quitf(_wa, \"%sexpected: %d tokens, found %d tokens\", dif.c_str(), int(toka.size()), int(tokb.size()));\n for (int i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \"messy.h\"\n\nusing namespace std;\n\nnamespace helper {\n\n set set_;\n bool compiled = false;\n int n;\n vector p;\n int w;\n int r;\n\n int read_int() {\n int x;\n cin >> x;\n return x;\n }\n\n}\n\nusing namespace helper;\n\n\n// A convenience function.\nint get_p(int i) {\n int ret = p[i];\n return ret;\n}\n\nint main() {\n n = read_int();\n w = read_int();\n r = read_int();\n p = vector(n);\n for (int i = 0; i < n; i++) {\n p[i] = read_int();\n }\n vector answer = restore_permutation(n, w, r);\n \n if (answer.size() != n) {\n printf(\"WA\\n\");\n return 0;\n }\n\n\n printf(\"%d\", answer[0]);\n\n for (int i = 1; i < n; i++) {\n printf(\" %d\", answer[i]);\n }\n printf(\"\\n\");\n return 0;\n}\n\nvoid wa() {\n printf(\"WA\\n\");\n exit(0);\n}\n\nbool check(const string& x) {\n if ((int)x.length() != n) {\n return false;\n }\n for (int i = 0; i < n; i++) {\n if (x[i] != '0' && x[i] != '1') {\n return false;\n }\n }\n return true;\n}\n\nvoid add_element(string x) {\n if (--w < 0 || compiled || !check(x)) {\n wa();\n }\n set_.insert(x);\n}\n\nbool check_element(string x) {\n if (--r < 0 || !compiled || !check(x)) {\n wa();\n }\n return set_.count(x);\n}\n\nvoid compile_set() {\n if (compiled) {\n wa();\n }\n compiled = true;\n set compiledSet;\n string compiledElement = string(n, ' ');\n for (set::iterator it = set_.begin(); it != set_.end(); it++) {\n string s = *it;\n for (int i = 0; i < n; i++) {\n compiledElement[i] = s[get_p(i)];\n }\n compiledSet.insert(compiledElement);\n }\n set_ = compiledSet;\n}\n", "messy.cpp": "#include \n\n#include \"messy.h\"\n\nstd::vector restore_permutation(int n, int w, int r) {\n add_element(\"0\");\n compile_set();\n check_element(\"0\");\n return std::vector();\n}\n", "messy.h": "#pragma once\n\n#include \n#include \n\nvoid add_element(std::string x);\nbool check_element(std::string x);\nvoid compile_set();\n\nstd::vector restore_permutation(int n, int w, int r);\n"}, "materialization": {"case_outputs": [{"mode": "input_token_slice", "input_glob": "cases/*", "output_suffix": ".out", "length_index": 0, "start_index": 3}]}} {"problem_id": "ioi15_b", "cate": ["search", "math"], "difficulty": "hard", "cpu_time_limit_ms": 2000, "memory_limit_mb": 1024, "description": "Amina has six coins, numbered from $1$ to $6$. She knows that the coins all have different weights. She would like to order them according to their weight. For this purpose she has developed a new kind of balance scale.\n\nA traditional balance scale has two pans. To use such a scale, you place a coin into each pan and the scale will determine which coin is heavier.\n\nAmina's new scale is more complex. It has four pans, labeled $A$, $B$, $C$, and $D$. The scale has four different settings, each of which answers a different question regarding the coins. To use the scale, Amina must place exactly one coin into each of the pans $A$, $B$, and $C$. Additionally, in the fourth setting she must also place exactly one coin into pan $D$.\n\nThe four settings will instruct the scale to answer the following four questions:\n\n1. Which of the coins in pans $A$, $B$ and $C$ is the heaviest?\n2. Which of the coins in pans $A$, $B$ and $C$ is the lightest?\n3. Which of the coins in pans $A$, $B$ and $C$ is the median? (This is the coin that is neither the heaviest nor the lightest of the three.)\n4. Among the coins in pans $A$, $B$ and $C$, consider only the coins that are heavier than the coin on pan $D$. If there are any such coins, which of these coins is the lightest? Otherwise, if there are no such coins, which of the coins in pans $A$, $B$ and $C$ and is the lightest?\n\nWrite a program that will order Amina's six coins according to their weight. The program can query Amina's scale to compare weights of coins. Your program will be given several test cases to solve, each corresponding to a new set of six coins.\n\nYour program should implement the functions init and orderCoins. During each run of your program, the grader will first call init exactly once. This gives you the number of test cases and allows you to initialize any variables. The grader will then call orderCoins() once per test case.\n\n* void init(int T)\n + $T$: The number of test cases your program will have to solve during this run. $T$ is an integer from the range $1,\\dots,18$.\n + This function has no return value.\n* void orderCoins()\n + This function is called exactly once per test case.\n + The function should determine the correct order of Amina's coins by calling the grader functions getHeaviest(), getLightest(), getMedian(), and/or getNextLightest().\n + Once the function knows the correct order, it should report it by calling the grader function answer().\n + After calling answer(), the function orderCoins() should return. It has no return value.\n\nYou may use the following grader functions in your program:\n\n* answer(W) — your program should use this function to report the answer that it has found.\n + $W$: An array of length $6$ containing the correct order of coins. $W[0]$ through $W[5]$ should be the coin numbers (i.e., numbers from $1$ to $6$) in order from the lightest to the heaviest coin.\n + Your program should only call this function from orderCoins(), once per test case.\n + This function has no return value.\n* getHeaviest(A, B, C), getLightest(A, B, C), getMedian(A, B, C) — these correspond to settings $1$, $2$ and $3$ respectively for Amina's scale.\n + $A, B, C$: The coins that are put in pans $A$, $B$ and $C$, respectively. $A$, $B$, and $C$ should be three distinct integers, each between $1$ and $6$ inclusive.\n + Each function returns one of the numbers $A$, $B$, and $C$: the number of the appropriate coin. For example, getHeaviest(A, B, C) returns the number of the heaviest of the three\n + given coins.\n* getNextLightest(A, B, C, D) — this corresponds to setting 4 for Amina's scale\n + $A, B, C, D$: The coins that are put in pans $A$, $B$, $C$, and $D$, respectively. $A$, $B$, $C$, and $D$ should be four distinct integers, each between $1$ and $6$ inclusive.\n + The function returns one of the numbers $A$, $B$, and $C$: the number of the coin selected by the scale as described above for setting $4$. That is, the returned coin is the lightest amongst those coins on pans $A$, $B$, and $C$ that are heavier than the coin in pan $D$; or, if none of them is heavier than the coin on pan $D$, the returned coin is simply the lightest of all three coins on pans $A$, $B$, and $C$.\n\nInput\n\nThe sample grader reads input in the following format:\n\n* line $1$: $T$ — the number of test cases\n* each of the lines from $2$ to $T + 1$: a sequence of $6$ distinct numbers from $1$ to $6$ the coins from the lightest to the heaviest.\n\nScoring\n\nThere are no subtasks in this problem. Instead, your score will be based on how many weighings (total number of calls to grader functions getLightest(), getHeaviest(), getMedian() and/or getNextLightest()) your program makes.\n\nYour program will be run multiple times with multiple test cases in each run. Let $r$ be the number of runs of your program. This number is fixed by the test data. If your program does not order the coins correctly in any test case of any run, it will get $0$ points. Otherwise, the runs are scored individually as follows.\n\nLet $Q$ be the smallest number such that it is possible to sort any sequence of six coins using $Q$ weighings on Amina's scale. To make the task more challenging, we do not reveal the value of $Q$ here.\n\nSuppose the largest number of weighings amongst all test cases of all runs is $Q + y$ for some integer $y$. Then, consider a single run of your program.\n\nThen, the score for this run will be $\\frac{100}{r(y / 2.5 + 1)}$, rounded down to two digits after the decimal point.\n\nIn particular, if your program makes at most $Q$ weighings in each test case of every run, you will get $100$ points.\n\nOn the original contest, scoring was a bit different to award solutions, which are good on average. It's not implemented here.\n\nExample\n\nInput\n\n```\n2\n1 2 3 4 5 6\n3 4 6 2 1 5\n```\n\nOutput\n\n```\n1 2 3 4 5 6 6\n3 4 6 2 1 5 6\n```\n\nNote\n\nSuppose the coins are ordered $3\\ 4\\ 6\\ 2\\ 1\\ 5$ from the lightest to the heaviest.\n\n| | | |\n| --- | --- | --- |\n| Function call | Returns | Explanation |\n| getMedian(4, 5, 6) | 6 | Coin $6$ is the median among coins $4$, $5$, and $6$. |\n| getHeaviest(3, 1, 2) | 1 | Coin $1$ is the heaviest among coins $1$, $2$, and $3$. |\n| getNextLightest(2, 3, 4, 5) | 3 | Coins $2$, $3$, $4$ and are all lighter than coin $5$, so the lightest among them $(3)$ is returned. |\n| getNextLightest(1, 6, 3, 4) | 6 | Coins $1$ and $6$ are both heavier than coin $4$. Among coins $1$ and $6$, coin $6$ is the lightest one. |\n| getHeaviest(3, 5, 6) | 5 | Coin $5$ is the heaviest among coins $3$, $5$ and $6$. |\n| getMedian(1, 5, 6) | 1 | Coin $1$ is the median among coins $1$, $5$ and $6$. |\n| getMedian(2, 4, 6) | 6 | Coin $6$ is the median among coins $2$, $4$ and $6$. |\n| answer([3, 4, 6, 2, 1, 5]) | | The program found the right answer fot this test case. |", "interactor_files": {"grader.cpp": "#include \"graderlib.c\"\n\nint main() {\n\n int T, i;\n\n T = _getNumberOfTests();\n init(T);\n\n for (i = 1; i <= T; i++) {\n _initNewTest();\n orderCoins();\n }\n \n return 0;\n}\n", "scales.cpp": "#include \"scales.h\"\n\nvoid init(int T) {\n /* ... */\n}\n\nvoid orderCoins() {\n /* ... */\n int W[] = {1, 2, 3, 4, 5, 6};\n answer(W);\n}", "graderlib.c": "#include \n#include \n#include \n#include \"scales.h\"\n\n#define _MAXN 6\n#define _MAX_ANSWER_CALLS 1\n\nstatic int _realC[_MAXN];\nstatic int _ind[_MAXN];\nstatic int _numQueries;\nstatic int _numAnswerCalls;\nstatic FILE * _f;\nstatic FILE * _of;\n\nstatic int _getNumberOfTests() {\n int T, ret;\n\n _f = stdin;\n _of = stdout;\n\n ret = fscanf(_f, \"%d\", &T);\n assert(ret == 1);\n return T;\n}\n\nstatic void _initNewTest() { \n int i, ret;\n\n for (i = 0; i < _MAXN; i++) {\n ret = fscanf(_f, \"%d\", &_realC[i]);\n assert(ret == 1);\n _realC[i]--;\n _ind[_realC[i]] = i;\n }\n\n _numQueries = 0;\n _numAnswerCalls = 0;\n}\n\nvoid answer(int W[]) {\n int i;\n\n _numAnswerCalls++;\n if (_numAnswerCalls > _MAX_ANSWER_CALLS)\n return;\n\n // W[i] = coin number at position i+1 (1-indexed coin)\n // _realC[i] = coin number at position i (0-indexed)\n int correct = 1;\n for (i = 0; i < 6; i++) {\n if (W[i] != _realC[i] + 1) {\n correct = 0;\n break;\n }\n }\n\n if (correct) {\n fprintf(_of, \"OK %d\\n\", _numQueries);\n } else {\n fprintf(_of, \"WA\\n\");\n }\n}\n\nstatic void _checkQuery(int A, int B, int C, int D) {\n if (D == -1) {\n if (A < 1 || A > 6 || B < 1 || B > 6 || C < 1 || C > 6)\n assert(0);\n if (A == B || B == C || A == C)\n assert(0);\n }\n else {\n if (A < 1 || A > 6 || B < 1 || B > 6 || C < 1 || C > 6 || D < 1 || D > 6)\n assert(0);\n if (A == B || A == C || A == D || B == C || B == D || C == D)\n assert(0);\n }\n}\n\nint getMedian(int A, int B, int C) {\n _numQueries++;\n _checkQuery(A, B, C, -1);\n\n A--; B--; C--;\n\n if (_ind[B] < _ind[A] && _ind[A] < _ind[C])\n return A + 1;\n\n if (_ind[C] < _ind[A] && _ind[A] < _ind[B])\n return A + 1;\n\n if (_ind[A] < _ind[B] && _ind[B] < _ind[C])\n return B + 1;\n\n if (_ind[C] < _ind[B] && _ind[B] < _ind[A])\n return B + 1;\n\n return C + 1;\n}\n\nint getHeaviest(int A, int B, int C) {\n _numQueries++;\n _checkQuery(A, B, C, -1); \n\n A--; B--; C--;\n\n if (_ind[A] > _ind[B] && _ind[A] > _ind[C])\n return A + 1;\n\n if (_ind[B] > _ind[A] && _ind[B] > _ind[C])\n return B + 1;\n\n return C + 1;\n}\n\nint getLightest(int A, int B, int C) {\n _numQueries++;\n _checkQuery(A, B, C, -1);\n\n A--; B--; C--;\n\n if (_ind[A] < _ind[B] && _ind[A] < _ind[C])\n return A + 1;\n \n if (_ind[B] < _ind[A] && _ind[B] < _ind[C])\n return B + 1;\n\n return C + 1;\n}\n\nint getNextLightest(int A, int B, int C, int D) {\n int allLess = 1; \n\n _numQueries++;\n _checkQuery(A, B, C, D);\n\n A--; B--; C--; D--;\n\n if (_ind[A] > _ind[D] || _ind[B] > _ind[D] || _ind[C] > _ind[D])\n allLess = 0;\n\n if (allLess == 1) {\n if (_ind[A] < _ind[B] && _ind[A] < _ind[C])\n return A + 1;\n \n if (_ind[B] < _ind[A] && _ind[B] < _ind[C])\n return B + 1;\n\n return C + 1;\n }\n\n if (_ind[A] > _ind[D]) {\n if ((_ind[A] < _ind[B] || _ind[B] < _ind[D]) && (_ind[A] < _ind[C] || _ind[C] < _ind[D]))\n return A + 1;\n }\n\n if (_ind[B] > _ind[D]) {\n if ((_ind[B] < _ind[A] || _ind[A] < _ind[D]) && (_ind[B] < _ind[C] || _ind[C] < _ind[D]))\n return B + 1;\n }\n\n return C + 1;\n}\n", "scales.h": "#ifndef __SCALES_H__\n#define __SCALES_H__\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nvoid init(int T);\nvoid orderCoins();\nvoid answer(int W[]);\n\nint getMedian(int A, int B, int C);\nint getHeaviest(int A, int B, int C);\nint getLightest(int A, int B, int C);\nint getNextLightest(int A, int B, int C, int D);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __SCALES_H__ */"}}