diff --git "a/prompts/full.jsonl" "b/prompts/full.jsonl" new file mode 100644--- /dev/null +++ "b/prompts/full.jsonl" @@ -0,0 +1,464 @@ +{"id": 2423, "prompt": "### Problem Description\nThe annual \"Rock Jumping\" competition is about to begin!\n\nThis competition takes place in a straight river channel, where some giant rocks are distributed. The organizers have chosen two rocks as the starting point and the endpoint of the competition. Between the start and endpoint, there are $N$ rocks (excluding the starting and endpoint rocks). During the competition, participants will start at the starting point and jump to adjacent rocks step by step until they reach the endpoint.\n\nTo make the competition more challenging, the organizers plan to remove some of the rocks, trying to maximize the shortest jump distance during the competition. Due to budget constraints, the organizers can remove at most $M$ rocks lying between the starting and endpoint (the start and endpoint rocks cannot be removed).\n\n### Input Format\nThe first line of the input file contains three integers $L$, $N$, and $M$, representing the distance between the starting point and the endpoint, the number of rocks between the start and endpoint, and the maximum number of rocks that can be removed, respectively. \n\nThe next $N$ lines each contain an integer $D_i$ ($0 < D_i < L$), where the $i^{th}$ line indicates the distance of the $i^{th}$ rock from the starting point. These rocks are given in ascending order of distance from the starting point, and no two rocks share the same position.\n\n### Output Format\nThe output file contains a single integer, which is the maximum possible value of the shortest jump distance.\n\n### Example\n\n**Data Range and Hints** \nFor $20\\%$ of the data, $0 \\leq M \\leq N \\leq 10$. \nFor $50\\%$ of the data, $0 \\leq M \\leq N \\leq 100$. \nFor $100\\%$ of the data, $0 \\leq M \\leq N \\leq 50,000$, $1 \\leq L \\leq 1,000,000,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2131, "prompt": "### Problem Description\n\nTo celebrate the successful opening of NOI, the organizers have prepared a sushi banquet. Xiao G and Xiao W, as contestants of NOI, are also invited to the sushi banquet. \n\nAt the banquet, the organizers provide $n-1$ different types of sushi, numbered $1, 2, 3, \\ldots, n-1$. The deliciousness of the $i$-th type of sushi is $i+1$ (hence the deliciousness ranges from $2$ to $n$). \n\nNow, Xiao G and Xiao W would like to each choose some types of sushi to taste. They define a tasting plan as **disharmonious** if and only if: there exists a sushi with a deliciousness value $x$ among the types of sushi Xiao G tastes, and there exists a sushi with a deliciousness value $y$ among the types of sushi Xiao W tastes, such that $x$ and $y$ are not coprime. \n\nXiao G and Xiao W now want to count the total number of **harmonious** sushi tasting plans (modulo a given positive integer $p$). Note that it is possible for either person to not taste any sushi. \n\n---\n\n### Input Format\n\nThe first line of the input contains two positive integers $n$ and $p$, separated by a single space, indicating that there are $n$ types of sushi in total, and the total number of harmonious plans should be computed modulo $p$. \n\n---\n\n### Output Format\n\nOutput a single line containing one integer, representing the result of the harmonious plans modulo $p$. \n\n---\n\n### Sample\n\n---\n\n### Constraints and Hints\n\n$2 \\leq n \\leq 500, \\ 0 < p \\leq 1000000000$ \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2502, "prompt": "### Problem Description\nIn a directed graph $ G $, where the length of each edge is $ 1 $, you are given a starting point and an ending point. Your task is to find a path in the graph from the starting point to the ending point that satisfies the following conditions:\n\n1. Every vertex in the path must have outgoing edges pointing to vertices that are directly or indirectly connected to the ending point.\n2. Among paths that satisfy condition 1, the path must be the shortest.\n\nNote: The graph $ G $ may contain duplicate edges and self-loops. It is guaranteed that the ending point has no outgoing edges.\n\nOutput the length of the path that meets the above conditions.\n\n---\n\n### Input Format\nThe first line contains two integers $ n $ and $ m $, separated by a space, representing that the graph has $ n $ vertices and $ m $ edges.\n\nThe next $ m $ lines each contain two integers $ x $ and $ y $, separated by a space, indicating an edge going from vertex $ x $ to vertex $ y $.\n\nThe last line contains two integers $ s $ and $ t $, separated by a space, where $ s $ is the starting point and $ t $ is the ending point.\n\n---\n\n### Output Format\nOutput a single integer representing the length of the shortest path that satisfies the conditions described in the problem. If no such path exists, output $ -1 $.\n\n---\n\n### Example 1\n\n---\n\n### Example 2\n\n---\n\n### Constraints and Hints\n- For $ 30\\% $ of the cases: $ 0 < n \\le 10 $, $ 0 < m \\le 20 $. \n- For $ 60\\% $ of the cases: $ 0 < n \\le 100 $, $ 0 < m \\le 2000 $. \n- For $ 100\\% $ of the cases: $ 0 < n \\le 10000 $, $ 0 < m \\le 200000 $, $ 0 < x, y, s, t \\le n $, $ x,s \\ne t $.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2611, "prompt": "### Problem Description\n\nThe Chun Chun Kindergarten is hosting its annual \"Building Block Competition.\" This year's challenge is to construct a building with a width of $n$. The building can be considered as consisting of $n$ blocks, each with a width of $1$. The final height of the $i$-th block should be $h_i$.\n\nAt the beginning of the construction process, no blocks are present (it can be regarded as $n$ blocks with a height of $0$). During each operation, the children can select a continuous interval $[L, R]$, and increase the height of all blocks from the $L$-th block to the $R$-th block (inclusive) by $1$.\n\nLittle M is a clever child, and she quickly devised the optimal strategy to minimize the number of operations needed to construct the building. However, she is not a fan of executing her plans, so she asked you to implement the strategy and calculate the minimum number of operations required.\n\n### Input Format\n\nThe input contains two lines:\n\n1. The first line contains an integer $n$, representing the width of the building.\n2. The second line contains $n$ integers, where the $i$-th integer is $h_i$.\n\n### Output Format\n\nOutput only one line, the minimum number of operations required to construct the building.\n\n### Example\n\nOne feasible optimal strategy is to successively choose $[1, 5], [1, 3], [2, 3], [3, 3], [5, 5]$.\n\n### Constraints and Tips\n\n- For 30% of the data, $1 \\leq n \\leq 10$.\n- For 60% of the data, $1 \\leq n \\leq 1\\,000$.\n- For 100% of the data, $1 \\leq n \\leq 100\\,000$, $0 \\leq h_i \\leq 10\\,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2503, "prompt": "### Problem Description\nGiven a polynomial equation:\n\n$$a_0 + a_1x + a_2x^2 + \\cdots + a_nx^n = 0$$\n\nFind all integer solutions within the range $[1, m]$ where $n$ and $m$ are positive integers.\n\n### Input Format\nThe input consists of $n + 2$ lines. \n- The first line contains two integers $n$ and $m$, separated by a space. \n- The next $n + 1$ lines each contain one integer, representing the coefficients $a_0, a_1, a_2, \\ldots, a_n$ in order.\n\n### Output Format\n- On the first line, output the number of integer solutions to the equation within the interval $[1, m]$. \n- Then, each subsequent line should output one integer solution within $[1, m]$, listed in increasing order.\n\n### Example 1\n\n#### Example 2\n\n#### Example 3\n\n### Constraints and Hints\n- For $30\\%$ of the test cases: $0 < n \\leq 2$, $|a_i| \\leq 100$, $a_n \\neq 0$, $m < 100$. \n- For $50\\%$ of the test cases: $0 < n \\leq 100$, $|a_i| \\leq 10^{100}$, $a_n \\neq 0$, $m < 100$. \n- For $70\\%$ of the test cases: $0 < n \\leq 100$, $|a_i| \\leq 10^{10000}$, $a_n \\neq 0$, $m < 10^4$. \n- For $100\\%$ of the test cases: $0 < n \\leq 100$, $|a_i| \\leq 10^{10000}$, $a_n \\neq 0$, $m < 10^6$. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2499, "prompt": "### Problem Description\nAn undirected connected graph $G$ consists of $n$ nodes and $n - 1$ edges. The nodes are numbered from $1$ to $n$, and the weight of the node numbered $i$ is $W_i$. The length of each edge is $1$. The **distance** between two nodes $(u, v)$ on the graph is defined as the shortest path distance from node $u$ to node $v$. For a pair of nodes $(u, v)$ on graph $G$, if the distance between them is $2$, then they will generate a **joint weight** equal to $W_v \\times W_u$.\n\nWhat is the **maximum joint weight** among all possible ordered pairs in graph $G$? Additionally, what is the **sum of all joint weights**? \n\n### Input Format\nThe first line contains a single integer $n$. \n\nThe next $n - 1$ lines each contain $2$ positive integers $u, v$, separated by a space, indicating that there is an edge between node $u$ and node $v$. \n\nThe last line contains $n$ positive integers separated by a space, where the $i^{th}$ integer represents the weight $W_i$ of the node numbered $i$ in graph $G$. \n\n### Output Format\nOutput a single line containing 2 integers separated by a space: the maximum joint weight in graph $G$ and the sum of all joint weights. \n**Since the sum of all joint weights might be very large, the result should be taken modulo $10007$.**\n\n### Example\n\n**Input:**\n```\n4\n1 2\n2 3\n1 4\n2 4 3 1\n```\n\n**Output:**\n```\n8 17\n```\n\n### Constraints and Hints\n- For $30\\%$ of the data, $1 < n \\leq 100$.\n- For $60\\%$ of the data, $1 < n \\leq 2000$.\n- For $100\\%$ of the data, $1 < n \\leq 200000$, $0 < W_i \\leq 10000$.\n\nIt is guaranteed that at least one valid ordered pair exists in the graph that can generate a joint weight.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2665, "prompt": "### Problem Description\n\nWe know that a rooted tree can be traversed using Depth First Search (DFS) and Breadth First Search (BFS), yielding its DFS sequence and BFS sequence respectively. The DFS sequence of two different trees can be identical, and their BFS sequence can also be identical. For instance, the DFS sequence of the two trees below is `1 2 4 5 3` and their BFS sequence is `1 2 3 4 5`.\n\n![](https://i.loli.net/2018/06/10/5b1ce8c6521c4.png)\n\nGiven a DFS sequence and a BFS sequence, we want to know the average height of all possible rooted trees that satisfy these sequences. That is, if there are $K$ different rooted trees with the given DFS and BFS sequences, and their heights are $h_1, h_2, \\ldots, h_K$, please output:\n\n$$\n\\frac{h_1 + h_2 + \\ldots + h_K}{K}\n$$\n\n---\n\n### Input Format\n\n- The first line contains a positive integer $n$, representing the number of nodes in the tree.\n- The second line contains $n$ positive integers, which form a permutation of $1 \\ldots n$, representing the DFS sequence of the tree.\n- The third line contains $n$ positive integers, which form a permutation of $1 \\ldots n$, representing the BFS sequence of the tree.\n\nIt is guaranteed that there is at least one tree that satisfies the given DFS and BFS sequences.\n\n---\n\n### Output Format\n\nOutput a single real number, rounded to exactly three decimal places, representing the average height of the trees.\n\n---\n\n### Examples\n\n#### Example Input 1\n```plain\n5\n1 2 4 5 3\n1 2 3 4 5\n```\n\n#### Example Output 1\n```plain\n3.500\n```\n\n#### Example Input and Output 2\nRefer to the files `count.in` and `count.ans` in the additional attachment.\n\n---\n\n### Constraints and Notes\n\n- If the absolute difference between the output and the correct answer does not exceed $0.001$, the test point will be considered passed; otherwise, it will not be scored.\n- For $20\\%$ of the test cases, $n \\leq 10$.\n- For $40\\%$ of the test cases, $n \\leq 100$.\n- For $85\\%$ of the test cases, $n \\leq 2000$.\n- For $100\\%$ of the test cases, $2 \\leq n \\leq 200,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2424, "prompt": "### Problem Description\nThere are two strings $ A $ and $ B $ that only consist of lowercase English letters. The task is to extract $ k $ non-overlapping, non-empty substrings from string $ A $ and concatenate them in the order in which they appear in string $ A $ to form a new string. Determine how many ways it is possible for this new string to be equal to string $ B $.\n\n**Note**: Different positions of substring extraction are considered different solutions.\n\n### Input Format\nThe first line contains three positive integers $ n, m, k $, which represent the length of string $ A $, the length of string $ B $, and the value of $ k $ as mentioned in the problem description. Each pair of integers is separated by a single space. \nThe second line contains a string of length $ n $, representing string $ A $. \nThe third line contains a string of length $ m $, representing string $ B $. \n\n### Output Format\nOutput a single integer in one line, representing the number of solutions. Since the result could be very large, output the result modulo $ 1,000,000,007 $.\n\n### Sample Input and Output\n\n#### Sample 1:\n\n#### Sample 2: \n\n#### Sample 3: \n\n---\n\n### Constraints and Hints\nFor the $ 1^{st} $ dataset: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, k = 1 $; \nFor the $ 2^{nd} $ to $ 3^{rd} $ datasets: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, k = 2 $; \nFor the $ 4^{th} $ to $ 5^{th} $ datasets: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, k = m $; \nFor the $ 1^{st} $ to $ 7^{th} $ datasets: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, 1 \\leq k \\leq m $; \nFor the $ 1^{st} $ to $ 9^{th} $ datasets: $ 1 \\leq n \\leq 1000, 1 \\leq m \\leq 100, 1 \\leq k \\leq m $; \nFor all $ 10 $ datasets: $ 1 \\leq n \\leq 1000, 1 \\leq m \\leq 200, 1 \\leq k \\leq m $.\n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2415, "prompt": "### Problem Statement\n\nXiaoyuan and Xiaoxuan are good friends and classmates who always have endless topics to discuss. During one team-building activity, their classmates arranged themselves in a matrix of $m$ rows and $n$ columns. Xiaoyuan and Xiaoxuan were seated at the two ends of the diagonal of the matrix, making it impossible for them to converse directly. Fortunately, they could communicate by passing a note. The note must be passed through several classmates to reach the other person. Xiaoyuan is seated at the top-left corner of the matrix at coordinate $(1,1)$, while Xiaoxuan is seated at the bottom-right corner at coordinate $(m,n)$. The note passed from Xiaoyuan to Xiaoxuan can only be moved down or to the right, and the note passed from Xiaoxuan to Xiaoyuan can only be moved up or to the left.\n\nDuring the activity, Xiaoyuan wants to send a note to Xiaoxuan, and at the same time, Xiaoxuan wants to reply with a note to Xiaoyuan. Every classmate can help pass the notes, but they will only help once. In other words, if a classmate helps pass the note from Xiaoyuan to Xiaoxuan, they will not help pass the note back from Xiaoxuan to Xiaoyuan, and vice versa.\n\nAnother important detail to note is that every classmate has varying levels of willingness to help, expressed as their kindness level. The kindness levels (note: those of Xiaoyuan and Xiaoxuan are undefined and represented by $0$ in the input) are represented by natural numbers in the range $[0, 100]$, where larger numbers indicate higher kindness levels. Xiaoyuan and Xiaoxuan hope to find the classmates with the highest kindness levels to help pass the notes. Your task is to identify two paths (one for each note) such that the sum of kindness levels of the classmates involved in both paths is maximized.\n\n### Input Format\n\nThe first line contains two integers $m$ and $n$, separated by a space, indicating that the class has a matrix of $m$ rows and $n$ columns.\n\nThe next $m$ lines describe an $m \\times n$ matrix, where the integer in the $i$th row and $j$th column represents the kindness level of the student seated at $(i,j)$. The $n$ integers in each row are separated by a space.\n\n### Output Format\n\nOutput a single integer in one line, representing the maximum possible sum of kindness levels of students involved in the two paths for passing the notes back and forth.\n\n### Example\n\n#### Input:\n```\n4 4\n5 1 2 4\n8 3 6 7\n2 4 7 9\n6 7 4 9\n```\n\n#### Output:\n```\n67\n```\n\n### Constraints and Hints\n\n- For $30\\%$ of the data, $1 \\leq m,n \\leq 10$.\n- For $100\\%$ of the data, $1 \\leq m,n \\leq 50$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2420, "prompt": "### Problem Description\n\nA magic square is a fascinating $N \\times N$ matrix: it consists of the numbers $1, 2, 3, \\ldots, N \\times N$ and satisfies the property that the sum of the numbers in each row, each column, and both diagonals is the same.\n\nWhen $N$ is an odd number, a magic square can be constructed using the following method: \nFirst, write the number $1$ in the middle of the first row. \nThen, fill each successive number $K$ ($K = 2, 3, \\ldots, N \\times N$) as follows:\n\n1. If $(K - 1)$ is in the first row but not in the last column, place $K$ in the last row and in the column immediately to the right of the column containing $(K - 1)$; \n2. If $(K - 1)$ is in the last column but not in the first row, place $K$ in the first column and in the row immediately above the row containing $(K - 1)$; \n3. If $(K - 1)$ is in the last column of the first row, place $K$ directly below $(K - 1)$; \n4. If $(K - 1)$ is neither in the first row nor in the last column, and the position diagonally up and to the right of $(K - 1)$ has not been filled, then place $K$ in that position; otherwise, place $K$ directly below $(K - 1)$.\n\nGiven $N$, construct an $N \\times N$ magic square according to the method described above.\n\n---\n\n### Input Format\n\nThe input consists of a single line containing an integer, which is the size of the magic square.\n\n---\n\n### Output Format\n\nOutput $N$ lines, each containing $N$ integers, representing the magic square constructed using the method described above. Adjacent integers in the same row should be separated by a single space.\n\n---\n\n### Example\n\n```\nInput:\n3\n\nOutput:\n8 1 6\n3 5 7\n4 9 2\n```\n\n---\n\n### Constraints and Notes\n\nFor $100\\%$ of the test cases, $1 \\leq N \\leq 39$, and $N$ is an odd number.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2599, "prompt": "### Problem Description\n\nGiven a polynomial $(ax+by)^k$, find the coefficient of the term $x^ny^m$ after expanding the polynomial.\n\n### Input Format\n\nThe input contains one line with 5 integers: $a$, $b$, $k$, $n$, $m$. Each pair of consecutive integers is separated by a single space.\n\n### Output Format\n\nThe output contains one integer representing the desired coefficient. Since the coefficient can be very large, output it modulo $10,007$.\n\n### Example\n\n### Constraints and Hints\n\n- For $30\\%$ of the test cases, $k \\leq 10$. \n- For $50\\%$ of the test cases, $a = 1, b = 1$. \n- For $100\\%$ of the test cases, $0 \\leq k \\leq 1000$, $0 \\leq n, m \\leq k$, and $n + m = k$, $0 \\leq a, b \\leq 10^6$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2129, "prompt": "### Problem Description\n\nIn the process of implementing programmatic automatic analysis, it is often necessary to determine whether certain constraints can be satisfied simultaneously.\n\nConsider a simplified version of a constraint satisfaction problem: Suppose $x_1, x_2, x_3, \\ldots$ represent variables appearing in a program. You are given $n$ constraints of the form $x_i = x_j$ or $x_i \\neq x_j$. Your task is to decide whether it is possible to assign each variable an appropriate value such that all of the given constraints are satisfied simultaneously. \n\nFor example, consider the following constraints: $x_1 = x_2, \\ x_2 = x_3, \\ x_3 = x_4, \\ x_1 \\neq x_4$. These constraints are clearly contradictory and cannot all be satisfied at the same time. Therefore, this problem should be determined as unsatisfiable. \n\nNow, you are given several such constraint satisfaction problems; for each of them, you need to determine whether they are satisfiable.\n\n---\n\n### Input Format\n\nThe first line of the input file contains a positive integer $t$, representing the number of problems to be evaluated. Note that these problems are independent of each other. \n\nFor each problem: \n- The first line contains a positive integer $n$, representing the number of constraints for the problem. \n- The next $n$ lines each contain three integers $i, j, e$, describing a constraint. Integers are separated by a single space. If $e = 1$, the constraint is $x_i = x_j$; if $e = 0$, the constraint is $x_i \\neq x_j$.\n\n---\n\n### Output Format\n\nThe output file consists of $t$ lines. \n\nThe $k$-th line of the output should contain the string `YES` or `NO` (uppercase and without quotation marks): \n- Output `YES` if the $k$-th problem is satisfiable. \n- Output `NO` if the $k$-th problem is not satisfiable.\n\n---\n\n### Example\n\n#### Input:\n```\n2\n2\n1 2 1\n1 2 0\n2\n1 2 1\n2 1 1\n```\n\n#### Output:\n```\nNO\nYES\n```\n\n#### Explanation:\nIn the first problem, the constraints are $x_1 = x_2$ and $x_1 \\neq x_2$. These two constraints are contradictory, so they cannot be satisfied simultaneously. \nIn the second problem, the constraints are $x_1 = x_2$ and $x_2 = x_1$. These two constraints are equivalent and can be satisfied simultaneously.\n\n---\n\n### Constraints and Hints\n\n- For all test cases: $1 \\leq t \\leq 10$, $1 \\leq n \\leq 10^6$, $1 \\leq i, j \\leq 10^9$. \n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2445, "prompt": "### Problem Statement\n\nOn planet W, there are $n$ countries. To develop their economies, the countries have decided to construct bidirectional roads to ensure connectivity among them. However, the kings of these countries are very stingy and are only willing to build exactly $n - 1$ bidirectional roads.\n\nThe construction cost for each road is equal to the absolute difference between the number of countries at the two ends of the road multiplied by the road's length. For example, as shown in the figure below, the endpoints of the dashed road connect countries with $2$ and $4$ countries respectively. If the road has a length of $1$, its cost would be $1 \\times \\lvert 2 - 4 \\rvert = 2$. In the figure, the numbers inside the circles represent the country indices.\n\n![](https://i.loli.net/2018/06/11/5b1dfb1e69c02.png)\n\nDue to the vast number of countries, there are numerous ways to construct the roads, and calculating the construction costs for each plan manually is infeasible. Hence, the kings decided to seek help designing a program that, given a specific construction plan, computes the total construction cost for it. Your task is to design such a program.\n\n---\n\n### Input Format\n\nThe first line of the input contains a single integer $n$, which represents the number of countries on planet W, numbered from $1$ to $n$.\n\nThe next $n - 1$ lines each describe the construction of one road. The $i$-th line contains three integers $a_i$, $b_i$, and $c_i$, indicating that the $i$-th bidirectional road connects country $a_i$ and country $b_i$, and its length is $c_i$.\n\n---\n\n### Output Format\n\nOutput a single integer representing the total cost required to construct all roads.\n\n---\n\n### Example\n\n**Input**: \n```\n3\n1 2 1\n2 3 2\n```\n\n**Output**: \n```\n1\n```\n\n---\n\n### Constraints and Hints\n\nFor all data, it is guaranteed that $1 \\le a_i, b_i \\le n$ and $0 \\le c_i \\le 10^6$.\n\n| Test Case ID | $n=$ |\n| :-: | :-: |\n| 1 | $2$ |\n| 2 | $10$ |\n| 3 | $100$ |\n| 4 | $200$ |\n| 5 | $500$ |\n| 6 | $600$ |\n| 7 | $800$ |\n| 8 | $1000$ |\n| 9 | $10,000$ |\n| 10 | $20,000$ |\n| 11 | $50,000$ |\n| 12 | $60,000$ |\n| 13 | $80,000$ |\n| 14 | $100,000$ |\n| 15 | $600,000$ |\n| 16 | $700,000$ |\n| 17 | $800,000$ |\n| 18 | $900,000$ |\n| 19 | $1,000,000$ |\n| 20 | $1,000,000$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2609, "prompt": "### Problem Description\nHanhang has two boxes of matches, each containing $n$ matches, and each match has a height. The matches in each box can be arranged into a row, where the heights of matches in the same row are distinct. The distance between the two rows of matches is defined as: \n$$\\sum_{i=1}^{n} (a_i - b_i)^2$$ \nwhere $a_i$ represents the height of the $i$-th match in the first row, and $b_i$ represents the height of the $i$-th match in the second row.\n\nIn each row, adjacent matches can be swapped. Your task is to minimize the distance between the two rows by swapping the positions of matches. Then find the minimal number of swaps required to achieve this minimum distance. **If the number of swaps is too large, output the result modulo 99,999,997.**\n\n### Input Format\nThe input consists of three lines: \n- The first line contains an integer $n$, representing the number of matches in each box. \n- The second line contains $n$ integers separated by spaces, representing the heights of the matches in the first row. \n- The third line contains $n$ integers separated by spaces, representing the heights of the matches in the second row.\n\n### Output Format\nOutput a single integer representing the minimal number of swaps modulo 99,999,997 required to achieve the minimum distance.\n\n### Example 1\nFor the input: \n```\n2\n1 2\n2 1\n```\nThe minimum distance is $0$, and the minimal number of swaps is $1$. For example, swapping the first two matches in the first row or swapping the first two matches in the second row achieves the minimum distance.\n\n### Example 2\nFor the input: \n```\n3\n3 1 2\n3 2 1\n```\nThe minimum distance is $10$, and the minimal number of swaps is $2$. For example, swapping the middle two matches in the first row and swapping the last two matches in the second row achieves the minimum distance.\n\n### Constraints and Hints\n- For 10% of the test cases, $1 \\leq n \\leq 10$. \n- For 30% of the test cases, $1 \\leq n \\leq 100$. \n- For 60% of the test cases, $1 \\leq n \\leq 5,000$. \n- For 100% of the test cases, $1 \\leq n \\leq 100,000$, and $0 \\leq $ match height $ \\leq 2^{31} - 1$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2596, "prompt": "### Problem Description\n\nTo prepare for a unique award ceremony, the organizers are laying rectangular carpets in a rectangular area of the venue (considered as the first quadrant of a Cartesian coordinate plane).\n\nThere are $n$ carpets, numbered from $1$ to $n$. These carpets are laid out in sequence according to their number, parallel to the coordinate axes. A newly placed carpet will cover earlier ones that have already been laid.\n\nAfter all the carpets are placed, the organizers want to determine which carpet is at the top layer at a specific point on the ground.\n\nNote: Points located on the boundaries and the four corners of a rectangular carpet are also considered to be covered.\n\n### Input Format\n\nThe input consists of $n+2$ lines.\n\n- The first line contains a single integer $n$, which represents the total number of carpets.\n- The next $n$ lines describe the information of the carpets. The $(i+1)$-th line contains four positive integers: $a, b, g, k$, separated by a space. These integers describe the bottom-left corner $(a, b)$ of the carpet and its dimensions: $g$ is the length along the $x$-axis, and $k$ is the length along the $y$-axis.\n- The last line ($n+2$-th line) contains two positive integers $x$ and $y$, which represent the coordinates of the point $(x, y)$ on the ground that is to be queried.\n\n### Output Format\n\nThe output consists of a single line with one integer. The integer represents the carpet number of the topmost layer covering the queried point; if no carpet covers the point, output $-1$.\n\n### Example 1\n\nAs shown below, the solid line represents Carpet 1, the dashed line represents Carpet 2, and the double solid line represents Carpet 3. The point $(2, 2)$ is covered by Carpet 3, which is the topmost layer.\n\n![pic1.png](https://img.loj.ac.cn/2021/12/29/1b6a93302ed5e.png)\n\n### Example 2\n\nAs shown above, the solid line represents Carpet 1, the dashed line represents Carpet 2, and the double solid line represents Carpet 3. The point $(4, 5)$ is not covered by any carpet, so the output is `-1`.\n\n### Constraints and Hints\n\n- For $30\\%$ of the data, $n \\leq 2$;\n- For $50\\%$ of the data, $a, b, g, k \\leq 100$;\n- For $100\\%$ of the data: $0 \\leq n \\leq 10^4$, and $0 \\leq a, b, g, k \\leq 10^5$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2594, "prompt": "### Problem Description\nIn city S, there are currently two prisons, imprisoning a total of $N$ criminals numbered $1$ to $N$. Relationships among these criminals are naturally very discordant. Many of them bear grudges against each other, and conflicts may erupt at any time if the conditions are favorable. We use the \"resentment value\" (a positive integer) to represent the hatred level between any two criminals; the higher the resentment value $c$, the greater the grudge between the two criminals. If two criminals with resentment value $c$ are detained in the same prison, they will inevitably clash, causing a conflict with an impact level of $c$.\n\nAt the end of each year, the police department compiles a list of all the conflicts within the prison during the year, ordered from highest to lowest impact level, and submits it to Z, the mayor of city S. Busy with government affairs, Mayor Z only reviews the impact level of the first event on the list. If the impact is particularly high, he may consider replacing the police chief.\n\nAfter studying the relationships among these $N$ criminals in detail, the police chief feels enormous pressure. He plans to reallocate the criminals between the two prisons to minimize the impact level of the largest conflict Mayor Z sees, thus safeguarding his position. Assuming that if two criminals in the same prison harbor resentment towards each other, conflicts will occur at some point during the year. How should the criminals be allocated to ensure Mayor Z sees the smallest conflict impact level? What is this minimum value?\n\n---\n\n### Input Format\nEach line of the input separates two numbers by a space.\n\n- The first line contains two positive integers $N$ and $M$, representing the number of criminals and the number of pairs of criminals with resentment, respectively.\n- The next $M$ lines each contain three positive integers $a_j, b_j, c_j$, indicating that criminal $a_j$ and criminal $b_j$ harbor resentment with a resentment value of $c_j$. The data guarantees that $1 \\leq a_j < b_j \\leq N$, $0 < c_j \\leq 1,000,000,000$, and each pair of criminals appears only once.\n\n---\n\n### Output Format\nOutput consists of $1$ line, representing the impact level of the conflict event seen by the mayor.\n\nIf no conflicts occur within the prisons during the year, output $0$.\n\n---\n\n### Example\nThe resentment values between criminals are shown in the left diagram below. The allocation of criminals is shown in the right diagram. The conflict event with the highest impact level seen by the mayor is $3512$ (triggered by criminals $2$ and $3$). Any other allocation would not yield a better result.\n\n![298.png.jpg](https://i.loli.net/2018/05/22/5b03db0916ac8.jpg)\n\n---\n\n### Data Range and Hints\n- For $30\\%$ of the data, $N \\leq 15$.\n- For $70\\%$ of the data, $N \\leq 2,000$, $M \\leq 50,000$.\n- For $100\\%$ of the data, $N \\leq 20,000$, $M \\leq 100,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2307, "prompt": "### Problem Description\n\"Clone Technique!\" \u2014 Little $P$\n\nThere are $n$ clones of Little $P$ scattered across a plane. The area occupied by a group of clones is defined as the smallest convex polygon that encloses these clones. Little $P$ is limited in ability, and at every moment, some clones will disappear. However, before the next moment, Little $P$ performs:\n\n\"Clone Technique!\"\n\nto make the disappeared clones reappear at their original positions. Little $P$ wants to know the area occupied by the remaining clones each moment after some clones disappear.\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, representing the initial number of clones and the number of moments. \nThe next $n$ lines each contain two integers $x_i$, $y_i$, describing the position of the $i$-th clone. \nThe next $m$ lines each contain the first integer $k$, representing the number of clones that disappear at this moment, followed by $k$ non-negative integers $c_1$, $c_2$, ..., $c_k$, which are used to generate the indices of the disappearing clones. \n\nThe indices of the disappearing clones $p_1$, $p_2$, ..., $p_k$ are calculated as follows:\nLet the twice of the area occupied by the clones in the previous moment be $S$. Then the indices of the disappearing clones are calculated as:\n\n$$\np_i = [(S + c_i) \\bmod n] + 1\n$$\n\nSpecially, at the first moment, we consider $S = -1$, i.e., the indices of the disappearing clones are calculated as:\n\n$$\np_i = [(-1 + c_i) \\bmod n] + 1\n$$\n\n---\n\n### Output Format\nFor each moment, output $m$ lines, each containing a single integer representing twice the area occupied by the remaining clones.\n\n---\n\n### Example\nAs shown in the diagram below: \nThe left image represents the positions of the $6$ clones and the area they occupy. \nThe middle image represents the situation at the first moment, where the indices of the disappearing clones are $1, 3, 6$, and the remaining $3$ clones occupy the region marked by the solid lines within the area, yielding twice the area as $3$.\n\nThe right image represents the situation at the second moment, where the indices of the disappearing clones are calculated as: \n\n$$\n[(0 + 3) \\bmod 6] + 1 = 4\n$$\n\n$$\n[(1 + 3) \\bmod 6] + 1 = 5\n$$\n\nThe remaining $4$ clones occupy the region marked by the solid lines within the area.\n\n![TIM\u56fe\u724720170721203208.png](https://i.loli.net/2017/07/21/5971f489dcfb9.png)\n\n---\n\n### Data Constraints and Hints\nFor all data, it is guaranteed:\n\n- $|x_i| ,|y_i| \\leq 10^8$\n- No two clones have the exact same coordinates.\n- $k \\leq 100$\n- The sum of all $k$ across all moments does not exceed $2 \\times 10^6$.\n- $0 \\leq c_i \\leq 2^{31} - 1$\n- Initially, the area occupied by all clones is greater than $0$.\n- Define the **vertex set** of the area occupied by all $n$ clones as $S$, where $S \\geq 3$. At any moment, there are at least two clones from $S$ that have not disappeared.\n\nDue to the 64-bit operating system's pointer size of 8 bytes, the LOJ platform increases the memory limit to $768 \\mathrm{MB}$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2352, "prompt": "### Problem Description\nIn the study of social networks, graph theory concepts are often used to analyze social phenomena. Consider the following problem: \nIn a social circle with $n$ individuals, there are varying degrees of relationships between people. This relationship network can be represented as an undirected graph with $n$ nodes. If two different individuals know each other, there is an undirected edge between their corresponding nodes, assigned a positive weight $c$, where smaller values of $c$ indicate closer relationships. The shortest path between two nodes $s$ and $t$ is used to measure the closeness of the relationship between individuals $s$ and $t$. It is noteworthy that other nodes on the shortest path provide some form of convenience for the connection between $s$ and $t$, making these nodes somewhat important in their interaction. The importance degree of a node in the social network can be measured by counting the number of shortest paths passing through that node. \n\nConsidering that there might be multiple shortest paths between two nodes $A$ and $B$, we modify the definition of importance degree as follows: \nLet $C_{s,t}$ be the total number of different shortest paths from $s$ to $t$, and $C_{s,t}(v)$ be the number of those shortest paths that pass through a node $v$. The importance degree of node $v$ in the social network is then defined as:\n\n$$ I(v)=\\sum_{s \\ne v,t\\ne v} \\frac{C_{s,t}(v)}{C_{s,t}} $$\n\nTo ensure that $I(v)$ and $C_{s,t}(v)$ are well-defined, we assume that the social network is always represented by a connected undirected graph, meaning every pair of nodes has a finite shortest path in between. Given such a weighted undirected graph, your task is to calculate the importance degree for each node.\n\n### Input Format\nThe first line of input contains two integers $n$ and $m$, representing the number of nodes and edges in the social network. \nThe graph has nodes numbered from $1$ to $n$. \nThe following $m$ lines each describe an undirected edge with three integers $a$, $b$, and $c$, indicating there is an edge connecting node $a$ and node $b$ with a weight of $c$. \nNote that there is at most one edge between any two nodes, and the graph does not contain self-loops (i.e., no edge connects a node to itself).\n\n### Output Format\nThe output consists of $n$ lines, each containing a real number rounded to three decimal places. The $i$-th line contains the importance degree of node $i$ in the social network.\n\n### Sample\nThe social network is illustrated below.\n\n![dd(5).png](https://i.loli.net/2018/02/12/5a81453871c94.png)\n\nFor node $1$, only the shortest paths from node $2$ to node $4$ and from node $4$ to node $2$ pass through node $1$. There are $2$ shortest paths between node $2$ and node $4$. Hence, the importance degree of node $1$ is calculated as $\\frac{1}{2} + \\frac{1}{2} = 1$. Due to the symmetry of the graph, the importance degrees of the other three nodes are also $1$.\n\n### Constraints and Notes\n- For $50\\%$ of the test cases: $n \\leq 10 , m \\leq 45$. \n- For $100\\%$ of the test cases: $n \\leq 100 , m \\leq 4500$, and the weight $c$ of any edge is a positive integer such that $1 \\leqslant c \\leqslant 1000$. \n- It is guaranteed that the given undirected graph is connected, and that the number of shortest paths between any two nodes does not exceed $10^{10}$. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2605, "prompt": "### Problem Description\nFind the smallest positive integer solution $x_0$ to the congruence equation $ax \\equiv 1 \\pmod{b}$.\n\n### Input Format\nThe input consists of a single line containing two positive integers $a$ and $b$, separated by a space.\n\n### Output Format\nThe output consists of a single line containing the smallest positive integer solution $x_0$. It is guaranteed that a solution always exists for the given input.\n\n### Example\n\n### Data Range and Hints\n- For 40% of the test cases, $2 \\leq b \\leq 1\\,000$;\n\n- For 60% of the test cases, $2 \\leq b \\leq 50\\,000\\,000$;\n\n- For 100% of the test cases, $2 \\leq a, b \\leq 2\\,000\\,000\\,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2600, "prompt": "### Problem Description\n\nT is a quality inspector responsible for assessing the quality of a batch of minerals. This batch contains $n$ mineral stones numbered sequentially from $1$ to $n$. Each stone has its own weight $w_i$ and value $v_i$. The mineral assessment process includes the following steps:\n\n1. $m$ intervals $[L_i, R_i]$ are given;\n2. Choose a parameter $W$;\n3. For an interval $[L_i, R_i]$, calculate the inspection value $Y_i$ for the mineral stones in this interval:\n\n$$Y_i=\\sum_j 1 \\cdot \\sum_j v_j, \\quad j \\in [L_i, R_i], w_j \\geq W$$\n\nwhere $j$ is the index of the stones.\n\nThe inspection result $Y$ for the entire batch of minerals is the sum of the inspection values across all intervals, which is:\n\n$$Y=\\sum_{i=1}^m Y_i$$\n\nIf the inspection result deviates too much from the given standard value $S$, another batch of minerals will need to be inspected.\n\nT wants to avoid spending time inspecting another batch of minerals. Therefore, he wants to adjust the value of parameter $W$ such that the inspection result gets as close to the standard value $S$ as possible, i.e., minimize $|S-Y|$. Please help T find this minimum value.\n\n---\n\n### Input Format\n\nThe first line contains three integers $n$, $m$, and $S$, which represent the number of mineral stones, the number of intervals, and the standard value, respectively.\n\nThe next $n$ lines each contain $2$ integers separated by a space: the $i+1$-th line represents the weight $w_i$ and value $v_i$ of the $i$th mineral stone.\n\nThe following $m$ lines each contain $2$ integers separated by a space: the $i+n+1$-th line represents the two endpoints $L_i$ and $R_i$ of the interval $[L_i, R_i]$.\n\n**Note**: Different intervals may overlap or intersect with one another.\n\n---\n\n### Output Format\n\nThe output contains only one line: a single integer representing the minimum value of $|S-Y|$.\n\n---\n\n### Example\n\nWhen $W$ is set to $4$, the inspection values for the three intervals are $20$, $5$, and $0$, respectively. The inspection result for this batch of minerals is $25$. In this case, the minimum deviation from the standard value $S$ is $10$.\n\n---\n\n### Constraints and Hints\n\n- For $10\\%$ of the test cases, $n, m \\leq 10$; \n- For $30\\%$ of the test cases, $n, m \\leq 500$; \n- For $50\\%$ of the test cases, $n, m \\leq 5,000$; \n- For $70\\%$ of the test cases, $n, m \\leq 10,000$; \n- For $100\\%$ of the test cases, $1 \\leq n, m \\leq 200,000$, $0 < w_i, v_i \\leq 10^6$, $0 < S \\leq 10^{12}$, $1 \\leq L_i \\leq R_i \\leq n$. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2353, "prompt": "### Problem Description \nXiao $Y$ recently started working at a voucher trading exchange. This exchange only trades two types of vouchers: $A$ commemorative vouchers (hereafter referred to as $A$ vouchers) and $B$ commemorative vouchers (hereafter referred to as $B$ vouchers). Each customer who owns vouchers has their own account. The number of vouchers can be a real number. \n\nWith daily market fluctuations, the two types of vouchers have their respective values, i.e., the amount in RMB that can be exchanged per unit of voucher on a given day. We record the value of $A$ and $B$ vouchers on the $K$th day as $A_K$ and $B_K$ (RMB/unit voucher). To facilitate customer transactions, the voucher trading exchange provides a very convenient trading method called proportional trading. Proportional trading has two aspects: \n- Selling vouchers: Customers provide a real number $\\text{OP}$ within the range $[0,100]$, representing a selling percentage. This percentage means that $\\text{OP}\\%$ of their $A$ and $\\text{OP}\\%$ of their $B$ vouchers will be sold for RMB at the current value. \n- Buying vouchers: Customers pay $\\text{IP}$ RMB, and the exchange will provide vouchers with a total value of $\\text{IP}$ RMB. Moreover, the proportion of $A$ and $B$ vouchers given to the customer on the $K$th day must be exactly $\\text{Rate}_K$. \n\nFor example, consider the following changes in $A_K$, $B_K$, and $\\text{Rate}_K$ over the next 3 days: \n\n![dd(1).png](https://i.loli.net/2018/02/12/5a8146be1354d.png) \n\nAssume that on the first day, the customer has $100$ RMB but no vouchers. The customer can perform the following operations: \n\n![dd(2).png](https://i.loli.net/2018/02/12/5a8146be23a4c.png) \n\nNote that multiple operations can be performed on the same day. Xiao $Y$, being an economically savvy employee, has measured market trends over a long period and determined the values of $A$ and $B$ vouchers as well as $\\text{Rate}$ over the next $N$ days. He hopes to calculate how much money he can maximize after $N$ days if he starts with $S$ RMB initially. \n\n---\n\n### Input Format \nThe first line contains two positive integers, $N$ and $S$, representing the number of days Xiao $Y$ can forecast and the initial amount of money. \nThe next $N$ lines each contain three real numbers, $A_K$, $B_K$, and $\\text{Rate}_K$, as described in the problem statement. \n\n---\n\n### Output Format \nOutput one real number, $\\text{MaxProfit}$, representing the maximum amount of money that can be obtained at the end of the $N$th day. The answer is considered correct if the absolute error between it and the standard answer is no greater than $10^{-3}$. \n\n---\n\n### Example \n![dd(3).png](https://i.loli.net/2018/02/12/5a8146be2d7a6.png) \n\n---\n\n### Constraints and Tips \n#### Constraints \n- For $40\\%$ of the test cases, $N \\leq 10$. \n- For $60\\%$ of the test cases, $N \\leq 1000$. \n- For $100\\%$ of the test cases: \n - $1 \\leq N \\leq 10^5$ \n - $0 < A_K \\leq 10$ \n - $0 < B_K \\leq 10$ \n - $0 < \\text{Rate}_K \\leq 100$ \n - $\\text{MaxProfit} \\leq 10^9$. \n\n#### Tips \n- The input file may be very large; please use a fast input method. \n- There is always an optimal buy-sell strategy that satisfies: spend all available RMB in each buy operation; sell all vouchers in each sell operation. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2446, "prompt": "### Problem Description\nNOI2011 has begun at Jilin University! To welcome the most outstanding informatics contestants from all over the country, Jilin University decided to host two grand carnival events for the NOI. These events will be held in two different locations. Each carnival may include many activities, but each activity can only be held at one carnival.\n\nNow, the organizer Xiao An has received applications for hosting a total of $n$ activities, where the starting time of the $i$-th activity is $S_i$, and its duration is $T_i$. These activities can be arranged in either of the carnival venues or can be left unarranged.\n\nAfter extensive investigation, Xiao An discovered that if, at a certain time, two carnival venues have simultaneous ongoing activities (excluding the start and end moments of activities), some contestants might feel conflicted about which venue to attend, which would make them unhappy. To avoid such unpleasant scenarios, Xiao An requires that no two activities occur simultaneously at both venues (activities within the same venue can overlap freely).\n\nFurthermore, if one carnival venue has too few activities, its appeal will diminish, leading to a dull atmosphere. Thus, Xiao An wishes to arrange the activities in a reasonable manner so that the maximum number of activities in the carnival with the fewer activities is as large as possible.\n\nIn addition, some activities are especially meaningful and must be held. Xiao An wants to know, given that the $i$-th activity must be held (it can be arranged at either of the two carnival venues), what the maximum number of activities is in the carnival with fewer activities.\n\n---\n\n### Input Format\nThe first line of the input contains an integer $n$, representing the number of activities applied for.\n\nThe next $n$ lines describe all activities, where the $i$-th line contains two integers $S_i$ and $T_i$, denoting that the $i$-th activity starts at time $S_i$ and lasts for $T_i$ units of time.\n\n---\n\n### Output Format\nThe first line of the output contains a single integer, denoting the maximum number of activities in the carnival with fewer activities under optimal arrangements without any restrictions.\n\nThe next $n$ lines each contain one integer, with the $i$-th line representing the maximum number of activities in the carnival with fewer activities under the condition that the $i$-th activity must be arranged (it can be held in either of the two carnivals).\n\n---\n\n### Example\nWithout any restrictions, an optimal arrangement can place activities $1$ and $4$ in one carnival, and activities $3$ and $5$ in the other carnival, while activity $2$ is left unarranged.\n\n---\n\n### Data Constraints and Notes\nFor $10\\%$ of the test cases, $n \\le 10$. \nFor $30\\%$ of the test cases, $n \\le 40$. \nFor all test cases, $1 \\le n \\le 200, 0 \\le S_i \\le 10^9$, $1 \\le T_i \\le 10^9$. \n\nFor a single test case:\n* If the output format is incorrect (e.g., fewer than $n+1$ lines are output), the score is $0$.\n* If the first line in the output file is incorrect and at least one of the subsequent $n$ lines is incorrect, the score is $0$.\n* If the first line in the output file is correct, but at least one of the subsequent $n$ lines is incorrect, the score is $4$.\n* If the first line in the output file is incorrect, but all of the subsequent $n$ lines are correct, the score is $6$.\n* If all $n+1$ lines in the output file are correct, the score is $10$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2318, "prompt": "### Problem Description\n\nXiaoming, who is participating in an archaeological excavation, has obtained a treasure map. This treasure map marks $n$ treasure houses buried deep underground, as well as $m$ roads that can potentially be developed between the treasure houses, and their respective lengths.\n\nXiaoming is determined to personally excavate the treasures from all of the treasure houses. However, each treasure house is located far beneath the ground, meaning that building an access road from the surface to a specific treasure house is very challenging. In contrast, developing roads between treasure houses is relatively easier.\n\nXiaoming\u2019s determination impressed the sponsors of the archaeological excavation. The sponsors have decided to sponsor the development of a single road from the surface to one particular treasure house for free. Xiaoming can decide which treasure house this free road will lead to.\n\nWith this sponsorship, Xiaoming must also determine how to develop the roads between the treasure houses. Any road that has been developed can be used freely without incurring additional costs. Excavating a new road allows Xiaoming and the archaeological team to excavate treasures from all treasure houses that can be reached through that newly developed road. Furthermore, Xiaoming does not wish to develop unnecessary roads, meaning that a road between two treasure houses that have both already been excavated does not need to be developed.\n\nThe cost of developing a new road is calculated as follows:\n\n$$\n\\text{Cost} = \\text{Length of the road} \\times \\text{Number of treasure houses passed from the surface-connected treasure house to the starting treasure house of the new road (inclusive)}.\n$$\n\nWrite a program to help Xiaoming determine which treasure house should be connected to the surface by the sponsor and which roads to develop between treasure houses, so that the total cost of the project is minimized. Output the minimum total cost.\n\n---\n\n### Input Format\n\nThe first line contains two space-separated positive integers, $n$ and $m$, representing the number of treasure houses and the number of potential roads, respectively.\n\nThe next $m$ lines each contain three space-separated positive integers, specifying the two treasure houses connected by a road (numbered $1$ to $n$) and the length $v$ of the road.\n\n---\n\n### Output Format\n\nOutput a single positive integer representing the minimum total cost.\n\n---\n\n### Sample 1\n![treasure1.png](https://img.loj.ac.cn/2021/12/29/7de6a14844bf1.png)\n\n---\n\n### Sample 2\n![treasure2.png](https://img.loj.ac.cn/2021/12/29/984854de117a3.png)\n\n---\n\n### Constraints and Notes\n\n- For $20\\%$ of the test cases:\n - The input forms a tree.\n - $1 \\leq n \\leq 8$, $v \\leq 5000$ and all $v$ are equal.\n \n- For $40\\%$ of the test cases:\n - $1 \\leq n \\leq 8$, $0 \\leq m \\leq 1000$, $v \\leq 5000$ and all $v$ are equal.\n \n- For $70\\%$ of the test cases:\n - $1 \\leq n \\leq 8$, $0 \\leq m \\leq 1000$, $v \\leq 5000$.\n \n- For $100\\%$ of the test cases:\n - $1 \\leq n \\leq 12$, $0 \\leq m \\leq 1000$, $v \\leq 500000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2591, "prompt": "### Problem Description\n\nXiaocheng and Xiaohua are both students who love mathematics. Recently, they have coincidentally become fascinated with Sudoku games. Being competitive, they want to use Sudoku as a way to challenge each other. However, ordinary Sudoku is too simple for them. Therefore, they sought advice from Dr. Z, who came up with his newly invented \"Target-shaped Sudoku\" as the challenge for these two children.\n\nThe grid of Target-shaped Sudoku is the same as that of normal Sudoku. It consists of a $9 \\times 9$ grid containing $9$ smaller $3 \\times 3$ subgrids (separated by bold black lines). In this large $9 \\times 9$ grid, some of the numbers are already given. Using logical reasoning and the given numbers, players need to fill in the other blank cells with numbers from $1$ to $9$. Each number cannot appear more than once in any $3 \\times 3$ subgrid, row, or column.\n\nHowever, there is one difference between Target-shaped Sudoku and normal Sudoku: each cell has a score, and the closer the cell is to the center of the grid, the higher its score (as shown in the diagram below).\n\n![28.png](https://i.loli.net/2018/05/22/5b03d2988a44a.png)\n\nThe detailed score distribution for the cells is as follows: the innermost cell (yellow region) is worth $10$ points. The ring outside the yellow region (red) has cells each worth $9$ points. The outer ring (blue) has cells worth $8$ points each. Another ring outside (brown) has cells worth $7$ points each. Finally, the outermost ring (white) has cells worth $6$ points each, as illustrated in the diagram.\n\nThe competition requires every participant to complete a given Sudoku puzzle (each Sudoku may have multiple valid solutions) and try to achieve the highest possible total score. The total score is calculated as the product of the score of a cell and the number filled in that cell, summed over all cells.\n\nAs shown in the example below, the total score for the Target-shaped Sudoku game filled in is $2829$. According to the game\u2019s rules, the winner is determined by the highest total score.\n\n![29.png](https://i.loli.net/2018/05/22/5b03d2989aa46.png)\n\nAnxious to win, Xiaocheng turns to you, a skilled programmer, for help. He asks you to determine the maximum score that can be achieved for a given Target-shaped Sudoku puzzle.\n\n---\n\n### Input Format\n\nThe input consists of $9$ lines, each containing $9$ integers (each integer in the range $0$\u2013$9$), representing a partially filled Sudoku grid. Blank cells are denoted by $0$. Each pair of numbers within the same line is separated by a single space.\n\n---\n\n### Output Format\n\nOutput a single line.\n\nThe output should be the highest possible score for the given Target-shaped Sudoku puzzle. If the Sudoku puzzle has no solution, output the integer $-1$.\n\n---\n\n### Sample Input 1\n\n```\n\n```\n\n### Sample Output 1\n\n```\n\n```\n\n---\n\n### Sample Input 2\n\n```\n\n```\n\n### Sample Output 2\n\n```\n\n```\n\n---\n\n### Constraints and Hints\n\n- For $40\\%$ of the test cases, the number of non-zero numbers in the Sudoku grid is no less than $30$.\n- For $80\\%$ of the test cases, the number of non-zero numbers in the Sudoku grid is no less than $26$.\n- For $100\\%$ of the test cases, the number of non-zero numbers in the Sudoku grid is no less than $24$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2443, "prompt": "### Problem Description\nThe new Intelligent Vehicle Competition has started at JL University! The competition track can be viewed as being composed of $n$ rectangular regions joined together (as shown in the diagram below). Each rectangle has edges parallel to the coordinate axes, and the $i$-th rectangle's bottom-left and top-right corner coordinates are $(x_{i,1}, y_{i,1})$ and $(x_{i,2}, y_{i,2})$, respectively.\n\nIt is guaranteed that $x_{i,1} < x_{i,2} = x_{i+1,1}$, and $y_{i,1} < y_{i,2}$. Two adjacent rectangles will always overlap along an edge (as shown by the dotted lines in the diagram), allowing the intelligent vehicle to traverse between rectangles through this shared area.\n\n![](https://i.loli.net/2018/06/10/5b1d382b37cb5.png)\n\nThe participants are required to design an algorithm for their intelligent vehicle such that it can travel from a given starting point $S$ to a given endpoint $T$ in the shortest possible time, without leaving the track. Assume that the vehicle moves at a constant speed $v$ and turning does not consume any time. Can you calculate the shortest time needed for the vehicle to complete the race?\n\n### Input Format\nThe first line contains a positive integer $n$, indicating the number of rectangles that make up the track.\n\nThe next $n$ lines describe the rectangles. The $i$-th line contains $4$ integers: $x_{i,1}, y_{i,1}, x_{i,2}, y_{i,2}$, which represent the bottom-left and top-right corner coordinates of the $i$-th rectangle as $(x_{i,1}, y_{i,1})$ and $(x_{i,2}, y_{i,2})$.\n\nThe next line contains two integers $x_S$ and $y_S$, indicating the coordinates of the starting point.\n\nThe next line contains two integers $x_T$ and $y_T$, indicating the coordinates of the endpoint.\n\nThe final line contains a real number $v$ ($1 \\leq v \\leq 10$), representing the speed of the intelligent vehicle.\n\n### Output Format\nOutput a single real number, accurate to at least six decimal places, representing the minimum time required for the intelligent vehicle to complete the race.\n\nFor each test case, if the absolute difference between your output and the reference solution is no greater than $10^{-6}$, you will receive full points for that test case; otherwise, you will receive zero points.\n\n### Example\n\n#### Input\n```\n2\n0 0 2 3\n2 1 5 4\n1 2\n4 3\n5\n```\n\n#### Output\n```\n0.728738\n```\n\n### Constraints and Hints\n- For $10\\%$ of the cases, $n \\leq 1$.\n- For $30\\%$ of the cases, $n \\leq 5$.\n- For $60\\%$ of the cases, $n \\leq 200$.\n- For $100\\%$ of the cases, $n \\leq 2000$.\n\nAll coordinates are integers, and their absolute values do not exceed $40000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2593, "prompt": "### Problem Description\nOn his birthday, Xiao Ming received a Turtle Board Game as a gift from his dad.\n\nThe turtle game board consists of a row of $N$ cells, each containing a score (non-negative integer). The first cell on the board is the unique starting point, and the $N$th cell is the endpoint. The game requires the player to control a turtle piece that starts at the first cell and moves all the way to the last cell.\n\nThe game features $M$ crawling cards, divided into $4$ different types (not all $4$ types of cards need to be present among the $M$ cards, as shown in the examples). Each type of card is marked with one of the numbers $1$, $2$, $3$, or $4$, indicating that the turtle piece will crawl forward by the corresponding number of cells when using that card. In the game, the player must select one unused crawling card from all available crawling cards each time, controlling the turtle piece to move forward by the number of cells indicated on the card. Each card can only be used once.\n\nThe turtle piece automatically obtains the score of the starting cell and, in subsequent crawling, gains the score of each cell it reaches. The player's final score is the total score collected by the turtle piece as it moves from the start to the endpoint.\n\nClearly, different sequences of using the crawling cards will result in different final scores. Xiao Ming wants to find a sequence of card usage that maximizes his final score.\n\nNow, given the scores of all cells on the board and all the crawling cards, can you help Xiao Ming calculate the maximum score he can achieve?\n\n---\n\n### Input Format\nEach line in the input file separates two numbers with a single space.\n\n- The first line contains $2$ positive integers $N$ and $M$, representing the number of cells on the board and the number of crawling cards, respectively.\n- The second line contains $N$ non-negative integers, $a_1, a_2, \\cdots\\cdots, a_N$, where $a_i$ represents the score in the $i$th cell on the board.\n- The third line contains $M$ integers, $b_1, b_2, \\cdots\\cdots, b_M$, representing the numbers on the $M$ crawling cards.\n\nThe input guarantees that exactly all $M$ crawling cards are used and the turtle piece arrives at the endpoint, i.e., $N \u2212 1 = \\sum\\limits_{i=1}^M{b_i}$.\n\n---\n\n### Output Format\nThe output consists of exactly $1$ line, containing $1$ integer, which represents the maximum score Xiao Ming can achieve.\n\n---\n\n### Example 1\nXiao Ming uses the crawling cards in the order $1, 1, 3, 1, 2$ and achieves a score of $6+10+14+8+18+17=73$.\n\nNote that since the starting point is $1$, Xiao Ming automatically gains the score of the first cell, $6$.\n\n---\n\n### Example 2\n\n---\n\n### Constraints and Notes\n- For $30\\%$ of cases: $N \\leq 30$, $M \\leq 12$;\n- For $50\\%$ of cases: $N \\leq 120$, $M \\leq 50$, and no more than $20$ cards for each of the $4$ types;\n- For $100\\%$ of cases: $1 \\leq N \\leq 350$, $1 \\leq M \\leq 120$, and no more than $40$ cards for each of the $4$ types; $0 \\leq a_i \\leq 100$, $1 \\leq i \\leq N$; $1 \\leq b_i \\leq 4$, $1 \\leq i \\leq M$.\n\nThe input guarantees $N \u2212 1 = \\sum\\limits_{i=1}^M{b_i}$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2951, "prompt": "### Problem Statement\n\nIn the land of netizens, there are $n$ different denominations of currency, where the denomination of the $i$-th type of currency is $a[i]$. You may assume that there is an infinite number of each type of currency. To simplify notation, the currency system with $n$ types and denomination array $a[1 \\dots n]$ is written as $(n,a)$.\n\nIn a complete currency system, every non-negative integer amount $x$ should be representable. That is, for every non-negative integer $x$, there exist $n$ non-negative integers $t[i]$ such that the sum of $a[i] \\times t[i]$ equals $x$. However, in the land of netizens, the currency system may be incomplete, meaning there might be some amounts $x$ that cannot be represented in that system. For example, in the currency system $n = 3$, $a = [2, 5, 9]$, amounts $1, 3$ cannot be represented.\n\nTwo currency systems $(n,a)$ and $(m,b)$ are considered equivalent if and only if, for any non-negative integer $x$, it is either representable in both currency systems or unrepresentable in both.\n\nThe netizens want to simplify their currency system. They are looking for a currency system $(m,b)$ that is equivalent to the original currency system $(n,a)$, with $m$ being as small as possible. Your task is to assist them in finding the smallest $m$.\n\n---\n\n### Input Format\n\nThe input file name is `money.in`. \nThe first line of the input contains an integer $T$, representing the number of test cases. \nFor each test case, the first line contains a positive integer $n$. \nThe following line contains $n$ positive integers $a[i]$, separated by spaces.\n\n---\n\n### Output Format\n\nThe output file name is `money.out`. \nThe output file contains $T$ lines. For each test case, output one line with a single positive integer, representing the smallest $m$ among all currency systems $(m,b)$ that are equivalent to $(n,a)$.\n\n---\n\n### Example\n\n#### Input:\n```\n2\n3\n2 5 9\n5\n1 2 3 4 5\n```\n\n#### Output:\n```\n2\n5\n```\n\n#### Explanation:\n\nFor the first test case, the currency system $(2, [3,10])$ is equivalent to the given currency system $(n,a)$. It can be verified that there does not exist $m < 2$ that results in an equivalent currency system. Thus, the answer is $2$.\n\nFor the second test case, it can be verified that there does not exist $m < n$ resulting in an equivalent currency system. Thus, the answer is $5$.\n\n---\n\n### Constraints & Notes\n\n| Test Point ID | $n$ | $a[i]$ |\n| :-----------: | :-------: | :-----------------: |\n| $1\\sim 3$ | $=2$ | $\\leq 10^3$ |\n| $4\\sim 6$ | $=3$ | $\\leq 10^3$ |\n| $7,\\ 8$ | $=4$ | $\\leq 10^3$ |\n| $9,\\ 10$ | $=5$ | $\\leq 10^3$ |\n| $11\\sim 13$ | $\\leq 13$ | $\\leq 16$ |\n| $14\\sim 16$ | $\\leq 25$ | $\\leq 40$ |\n| $17\\sim 20$ | $\\leq 100$| $\\leq 2.5 \\times 10^4$ |\n\nFor all test cases, $1 \\leq T \\leq 20$, $n,a[i] \\geq 1$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2249, "prompt": "### Problem Description\nThis summer, NOI celebrates its 30th anniversary in SZ City. OIers from $n$ cities across the country will depart and travel to SZ City to participate in this grand event.\n\nThe cities across the country form a rooted tree with SZ City as the root. Each city is connected to its parent via a road. For convenience, we number the $n$ cities with integers from $1$ to $n$, where SZ City is numbered as $1$. For any city $v$ other than SZ City, its parent city $f_v$ and the length of the road connecting to its parent city $s_v$ are given.\n\nTo travel from city $v$ to SZ City, an OIer can follow these steps: choose an ancestor city $a$, pay the ticket price, and use public transport to reach $a$. Then choose an ancestor city $b$ of $a$, pay the ticket price again, and travel to $b$. Repeat this process until reaching SZ City.\n\nFor any city $v$, there is a distance limit $l_v$ for the transportation method. For an ancestor $a$ of city $v$, if the total distance of all roads between $v$ and $a$ exceeds $l_v$, then the OIer cannot reach $a$ in a single trip. Otherwise, $v$ can reach $a$ in one ticket purchase. Additionally, for each city $v$, two non-negative integers $p_v$ and $q_v$ are given as ticket price parameters. If the total distance between city $v$ and city $a$ is $d$, the ticket price for traveling from $v$ to $a$ is calculated as $dp_v+q_v$.\n\nOIers in every city want to minimize their total ticket expenses when they travel to SZ City. Your task is to determine the minimum total ticket cost for the OIers in each city.\n\n---\n\n### Input Format\nThe first line contains two non-negative integers $n$ and $t$, representing the number of cities and the type of data (the meaning of $t$ will be explained later). \nThe second to $n$th lines of the input describe cities other than SZ City. Line $v$ contains five non-negative integers $f_v, s_v, p_v, q_v, l_v$, which represent the parent city of city $v$, the length of the road to the parent city, the two ticket price parameters, and the transportation distance limit, respectively.\n\n**Note**: The input does not contain SZ City numbered $1$. Lines $2$ to $n$ describe cities $2$ to $n$.\n\n---\n\n### Output Format\nThe output should contain $n-1$ lines, each with a single integer. Line $v$ corresponds to the minimum ticket cost required for traveling from city $v+1$ to SZ City.\n\nSimilarly, **note**: The output does not contain SZ City numbered $1$.\n\n---\n\n### Example\n\n---\n\n### Constraints and Notes\nFor all data:\n- $n \\leq 2 \\times 10^5$ \n- $0 \\leq p_v \\leq 10^6$ \n- $0 \\leq q_v \\leq 10^{12}$ \n- $1 \\leq f_v < v$ \n- $0 < s_v \\leq l_v \\leq 2 \\times 10^{11}$ \n- The total road distance from any city to SZ City does not exceed $2 \\times 10^{11}$.\n\nThe input parameter $t$ represents the type of data: \n- When $t = 0$ or $2$, for all cities $v$, $f_v = v-1$, which means all cities form a chain leading to SZ City. \n- When $t = 0$ or $1$, for all cities $v$, $l_v = 2 \\times 10^{11}$, meaning there is no distance restriction, and every city can reach all its ancestors. \n- When $t = 3$, the data has no special properties.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2361, "prompt": "### Problem Description\n\nThe combination number represents the number of ways to choose $ m $ items from $ n $ items. For example, selecting two items from the set $ (1, 2, 3) $ can yield three choices: $ (1, 2) $, $ (1, 3) $, $ (2, 3) $.\n\nAccording to the definition of combination numbers, the general formula for calculating combinations can be expressed as:\n\n$$ C_n ^ m = \\frac{n!}{m!(n - m)!} $$\n\nwhere $ n! = 1 \\times 2 \\times \\cdots \\times n $.\n\nXiaocong wants to find out, given $ n $, $ m $, and $ k $, how many pairs of $ (i, j) $ for all $ 0 \\leq i \\leq n $ and $ 0 \\leq j \\leq \\min(i, m) $ satisfy that $ C_i ^ j $ is a multiple of $ k $.\n\n### Input Format\n\nThe first line contains two integers $ t $ and $ k $, where $ t $ represents the number of test datasets for this test case, and $ k $ represents the significance as described in the \"Problem Description.\"\n\nThe next $ t $ lines each contain two integers $ n $ and $ m $, where $ n $ and $ m $ are described in the \"Problem Description.\"\n\n### Output Format\n\nFor $ t $ lines, each line contains one integer representing the count of pairs $ (i, j) $ for all $ 0 \\leq i \\leq n $ and $ 0 \\leq j \\leq \\min(i, m) $ that satisfy $ C_i ^ j $ being a multiple of $ k $.\n\n### Sample 1\n\n### Sample 2\n\n### Constraints and Hints\n\n$ 3 \\leq n, m \\leq 2000, 2 \\leq k \\leq 21, 1 \\leq t \\leq 10000 $\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2245, "prompt": "### Problem Description\n\nTo inherit the true essence of calligraphy, Little E is determined to visit a hermit who resides deep in the magical forest.\n\nThe magical forest can be visualized as an undirected graph containing $N$ nodes and $M$ edges, where nodes are numbered $1, \\ldots, N$, and edges are numbered $1, \\ldots, M$. Initially, Little E starts at node $1$, while the hermit resides at node $N$. Little E must traverse the magical forest to reach the hermit.\n\nThe magical forest is inhabited by monsters. Whenever someone passes through an edge, the monsters on the edge attack them. Fortunately, two types of guardian spirits, type $A$ and type $B$, live at node $1$. Little E can harness their power to achieve her goal.\n\nAs long as Little E carries enough guardian spirits, the monsters will not launch an attack. Specifically, every edge $E_i$ in the undirected graph has two weights: $A_i$ and $B_i$. If Little E carries at least $A_i$ type $A$ guardian spirits and at least $B_i$ type $B$ guardian spirits, the monsters on this edge will not attack anyone passing through the edge. Only if no monster attacks Little E on any edge during her journey through the magical forest can she successfully reach the hermit.\n\nSince carrying guardian spirits is a cumbersome task, Little E wants to know the minimum total number of guardian spirits she needs to carry to successfully visit the hermit. The total number of guardian spirits is the sum of the number of type $A$ guardian spirits and type $B$ guardian spirits.\n\n---\n\n### Input Format\n\nThe first line contains two integers, $N$ and $M$, representing the undirected graph with $N$ nodes and $M$ edges. \n\nThe next $M$ lines, each containing four positive integers $X_i, Y_i, A_i, B_i$, describe the $i$-th undirected edge. Here $X_i$ and $Y_i$ are the labels of the two endpoints of the edge, and $A_i$ and $B_i$ are as described above. \n\n**Note**: The input data may contain duplicated edges and self-loops.\n\n---\n\n### Output Format\n\nOutput a single integer on one line: \nIf Little E can successfully visit the hermit, output the minimum total number of guardian spirits she needs to carry. \nIf it is impossible for Little E to visit the hermit, output ``-1`` (without quotes).\n\n---\n\n### Example 1\n\nIf Little E follows the path $1 \\rightarrow 2 \\rightarrow 4$, she needs to carry $19 + 15 = 34$ guardian spirits. \nIf Little E takes the path $1 \\rightarrow 3 \\rightarrow 4$, she needs to carry $17 + 17 = 34$ guardian spirits. \nIf Little E follows the path $1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4$, she needs to carry $19 + 17 = 36$ guardian spirits. \nIf Little E takes the path $1 \\rightarrow 3 \\rightarrow 2 \\rightarrow 4$, she needs to carry $17 + 15 = 32$ guardian spirits. \nTherefore, the minimum number of guardian spirits Little E needs to carry is $32$. \n\n#### Input:\n```\n4 5\n1 2 19 15\n1 3 17 17\n2 3 19 17\n2 4 15 15\n3 4 17 15\n```\n\n#### Output:\n```\n32\n```\n\n---\n\n### Example 2\n\nLittle E cannot travel from node $1$ to node $3$, so the output is ``-1``.\n\n#### Input:\n```\n3 2\n1 2 1 1\n2 2 2 2\n```\n\n#### Output:\n```\n-1\n```\n\n---\n\n### Constraints and Hints\n\n- For all datasets, $2 \\leq N \\leq 50000$, $0 \\leq M \\leq 100000$, $1 \\leq A_i, B_i \\leq 50000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2444, "prompt": "### Problem Description\nAli loves collecting all kinds of quirky and strange items, and recently he found an old-fashioned typewriter. This typewriter has only $28$ keys, printed with $26$ lowercase English letters and the letters ```B``` and ```P```. After studying the typewriter, Ali discovered how it works: \n- When a lowercase letter is input, the typewriter adds this letter to a groove (the groove must contain at least one letter before pressing ```P```). \n- When the ```B``` key is pressed, the last letter in the groove disappears. \n- When the ```P``` key is pressed, the typewriter prints all the letters in the groove onto the paper and starts a new line, but the letters in the groove remain unchanged (it is guaranteed that the groove contains at least one letter). \n\nFor example, if Ali inputs ```aPaPBbP```, the characters printed on the paper are as follows: \n```plain\na \naa \nab\n``` \n\nWe number the strings printed on the paper sequentially from $1$ to $n$. The typewriter has a very interesting feature: it hides a numeric keypad. When two numbers $(x, y)$ are input on the keypad (where $1 \\leq x, y \\leq n$), the typewriter displays the number of times the $x$-th printed string occurs within the $y$-th printed string.\n\nAli was excited when he discovered this feature, so he wants to write a program that can replicate it. Can you help him?\n\n### Input Format\nThe first line contains a string that represents the sequence of characters Ali inputs. \nThe second line contains an integer $m$, which represents the number of queries. \nThe next $m$ lines describe the queries input through the numeric keypad. Each line contains two integers $x$ and $y$, representing the $i$-th query $(x, y)$.\n\n### Output Format\nOutput $m$ lines, where the $i$-th line contains an integer representing the answer to the $i$-th query.\n\n### Example\n\n#### Input\n```plain\naPaPBbP\n2\n1 2\n1 3\n```\n\n#### Output\n```plain\n1\n1\n```\n\n### Constraints and Hints\nThe range and characteristics of all test data are as follows:\n\n| Test Case ID | Scale of $n$ | Scale of $m$ | String Length | Total Input Length (Number of characters in the first input line) | \n| :----------: | :---------------: | :---------------: | :----------------------------------: | :--------------------------------------------------------------: | \n| 1 | $ 1 \\leq n \\leq 100$ | $ 1 \\leq m \\leq 1000$ | - | $\\leq 100$ | \n| 2 | $ 1 \\leq n \\leq 100$ | $ 1 \\leq m \\leq 1000$ | - | $\\leq 100$ | \n| 3 | $ 1 \\leq n \\leq 1000$ | $ 1 \\leq m \\leq 10^4$ | Maximum individual length $\\leq 1000$, total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 4 | $ 1 \\leq n \\leq 1000$ | $ 1 \\leq m \\leq 10^4$ | Maximum individual length $\\leq 1000$, total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 5 | $ 1 \\leq n \\leq 10^4$ | $ 1 \\leq m \\leq 10^5$ | Total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 6 | $ 1 \\leq n \\leq 10^4$ | $ 1 \\leq m \\leq 10^5$ | Total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 7 | $ 1 \\leq n \\leq 10^4$ | $ 1 \\leq m \\leq 10^5$ | Total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 8 | $ 1 \\leq n \\leq 10^5$ | $ 1 \\leq m \\leq 10^5$ | - | $\\leq 10^5$ | \n| 9 | $ 1 \\leq n \\leq 10^5$ | $ 1 \\leq m \\leq 10^5$ | - | $\\leq 10^5$ | \n| 10 | $ 1 \\leq n \\leq 10^5$ | $ 1 \\leq m \\leq 10^5$ | - | $\\leq 10^5$ | \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2955, "prompt": "### Problem Description\nThere are $n$ cities in Country Z, connected by $n-1$ bidirectional roads. Each bidirectional road connects two cities, ensuring that any two cities are reachable through one or more roads.\n\nThe Minister of Defense, Little Z, needs to station the army in these cities, subject to the following requirements:\n- A city can be stationed with an army or left unstated.\n- For any two cities directly connected by roads, at least one of them must be stationed with the army.\n- Stationing the army in a city incurs a cost. The cost of stationing in city $i$ is $p_i$.\n\nLittle Z quickly comes up with a plan to minimize the total cost of stationing the army. However, the king has proposed $m$ specific requirements, each specifying whether certain cities should or should not have armies stationed. Little Z needs to respond to each requirement. Specifically, for the $j$th requirement, if it is possible to satisfy the above stationing conditions under this requirement (without considering any other requirements), the minimum cost of the stationing plan subject to this requirement must be provided. If the $j$th requirement cannot be fulfilled, output $-1$. Please help Little Z solve this problem.\n\n### Input Format\nThe input file is named `defense.in`. \nThe first line contains two positive integers $n, m$ and a string $\\text{type}$, representing the number of cities, the number of requirements, and the data type. $\\text{type}$ is a string formed by an uppercase letter `A`, `B`, or `C` followed by a digit $1$, $2$, or $3$. It can help in partial scoring. You may not need to use this parameter. The exact meaning of this parameter is described in the \"Data Range and Hints\" section. \nThe second line contains $n$ integers $p_i$, representing the cost of stationing an army in city $i$. \nThe next $n-1$ lines each contain two positive integers $u, v$, representing a bidirectional road between cities $u$ and $v$. \nThe following $m$ lines each contain four integers $a, x, b, y$ ($a \\neq b$), representing the $j$th requirement. In the $j$th requirement, city $a$ must have $x$ armies stationed, and city $b$ must have $y$ armies stationed. The values of $x$ and $y$ can only be $0$ or $1$: if $x = 0$, city $a$ cannot have an army stationed; if $x = 1$, city $a$ must have an army stationed. Similarly, if $y = 0$, city $b$ cannot have an army stationed; if $y = 1$, city $b$ must have an army stationed.\n\nIn the input file, adjacent data elements in each line are separated by a single space.\n\n### Output Format\nThe output file is named `defense.out`. \nOutput $m$ lines, each containing one integer. The $j$th line represents the minimum cost of stationing the army while satisfying the king's $j$th requirement. If the king's $j$th requirement cannot be satisfied, output $-1$.\n\n### Example\nFor the first requirement, the minimum cost is incurred when armies are stationed in cities $4$ and $5$.\n\nFor the second requirement, the minimum cost is incurred when armies are stationed in cities $1$, $2$, and $3$.\n\nThe third requirement cannot be satisfied because neither city $1$ nor city $5$ has an army stationed, violating the condition that at least one of the two directly connected cities must have an army stationed.\n\n#### Data Range and Hints\nFor all data, $n = m \\leq 10^5$ and $1 \\leq p_i \\leq 10^5$.\n\n\n\n| Test Point Number | $\\text{type}$ | $n=$ |\n|:-:|:-:|:-:|\n| $1,2$ | A3 | $10$ |\n| $3,4$ | C3 | $10$ |\n| $5,6$ | A3 | $100$ |\n| $7$ | C3 | $100$ |\n| $8,9$ | A3 | $2\\times 10^3$ |\n| $10,11$ | C3 | $2\\times 10^3$ |\n| $12,13$ | A1 | $10^5$ |\n| $14\\sim 16$ | A2 | $10^5$ |\n| $17$ | A3 | $10^5$ |\n| $18,19$ | B1 | $10^5$ |\n| $20,21$ | C1 | $10^5$ |\n| $22$ | C2 | $10^5$ |\n| $23\\sim 25$ | C3 | $10^5$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3007, "prompt": "### Problem Description\n\nThere are $n$ students waiting to take a shuttle bus from RDFZ (The High School Affiliated to Renmin University of China) to Renmin University. The $i$-th student arrives at the bus stop at time $t_i$ (in minutes). There is only one shuttle bus operating, but the bus has an unlimited capacity. The shuttle bus travels from RDFZ to Renmin University and returns to RDFZ to pick up more students, which takes a total of $m$ minutes per round trip (the boarding and alighting times are negligible). The shuttle bus must transport all the students to Renmin University.\n\nKai Kai is curious\u2014if he can schedule the shuttle bus departure times freely, what is the minimum total waiting time for all the students?\n\nNote: The shuttle bus can depart immediately after returning to RDFZ.\n\n### Input Format\n\nThe input file is named `bus.in`.\n\nThe first line contains two positive integers, $n$ and $m$, separated by a space, representing the number of students and the time it takes for a shuttle bus round trip, respectively. \nThe second line contains $n$ non-negative integers, separated by spaces. The $i$-th integer $t_i$ represents the arrival time of the $i$-th student at the bus stop.\n\n### Output Format\n\nThe output file is named `bus.out`.\n\nOutput a single integer on one line, representing the minimum total waiting time for all students (in minutes).\n\n### Example 1\n\n#### Input\n```\n5 1\n3 4 4 3 5\n```\n\n#### Output\n```\n0\n```\n\n#### Explanation\n\n- Students 1 and 4 arrive at minute 3, wait 0 minutes, and board the shuttle bus at minute 3. The shuttle bus returns at minute 4.\n- Students 2 and 3 arrive at minute 4, wait 0 minutes, and board the shuttle bus at minute 4. The shuttle bus returns at minute 5.\n- Student 5 arrives at minute 5, waits 0 minutes, and boards the shuttle bus at minute 5.\n\nThus, all students are transported to Renmin University, achieving a total waiting time of $0$.\n\n---\n\n### Example 2\n\n#### Input\n```\n5 5\n11 13 1 5 5\n```\n\n#### Output\n```\n4\n```\n\n#### Explanation\n\n- Student 3 arrives at minute 1, waits 0 minutes, and boards the shuttle bus at minute 1. The shuttle bus returns at minute 6.\n- Students 4 and 5 arrive at minute 5, wait 1 minute, and board the shuttle bus at minute 6. The shuttle bus returns at minute 11.\n- Student 1 arrives at minute 11, waits 2 minutes; Student 2 arrives at minute 13, and waits 0 minutes. Both board the shuttle bus at minute 13.\n\nThus, all students are transported to Renmin University, achieving a total waiting time of $4$. \nIt can be proven that no arrangement yields a total waiting time smaller than $4$.\n\n---\n\n### See attached files for `bus3.in` and `bus3.ans`.\n\n---\n\n### Constraints and Hints\n\n- For $10\\%$ of the test cases, $n \\leq 10$, $m = 1$, $0 \\leq t_i \\leq 100$. \n- For $30\\%$ of the test cases, $n \\leq 20$, $m \\leq 2$, $0 \\leq t_i \\leq 100$. \n- For $50\\%$ of the test cases, $n \\leq 500$, $m \\leq 100$, $0 \\leq t_i \\leq 10^4$. \n- For an additional $20\\%$ of the test cases, $n \\leq 500$, $m \\leq 10$, $0 \\leq t_i \\leq 4 \\times 10^6$. \n- For $100\\%$ of the test cases, $n \\leq 500$, $m \\leq 100$, $0 \\leq t_i \\leq 4 \\times 10^6$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2953, "prompt": "### Problem Description\n\nXiao Y is an OIer who loves traveling. She has arrived in Country X and plans to visit all its cities.\n\nXiao Y learned that Country X has $n$ cities connected by $m$ bidirectional roads. Each road connects two cities. There are no multiple roads between the same pair of cities, and no road connects a city to itself. Additionally, it is guaranteed that from any city, Xiao Y can reach every other city using these roads, meaning the cities form a connected graph. Xiao Y can only travel between cities using these roads.\n\nXiao Y's travel plan is as follows: She starts from any city of her choice and begins her journey. At each step, she can either choose a road connecting the current city to another unvisited city or return along the same road she came from to the previous city. When Xiao Y returns to the starting city, she may choose to end her travel or continue exploring. Importantly, Xiao Y requires her travel plan to visit every city exactly once.\n\nTo make her travel more meaningful, Xiao Y decides to record the city number every time she enters a new city, including the starting city. This results in a sequence of length $n$. She hopes this sequence will have the smallest lexicographical order possible. Can you help her?\n\nFor two sequences $A$ and $B$ of length $n$, sequence $A$ is said to have smaller lexicographical order than sequence $B$ if and only if there exists a positive integer $x$ such that the following conditions are satisfied:\n\n- For any integer $1 \\le i < x$, the $i$-th element $A_i$ of sequence $A$ is equal to the $i$-th element $B_i$ of sequence $B$.\n- The $x$-th element $A_x$ of sequence $A$ is smaller than the $x$-th element $B_x$ of sequence $B$.\n\n---\n\n### Input Format\n\nThe input file name is `travel.in`. \nThe input file contains $m+1$ lines. \n\nThe first line contains two integers $n$ and $m$, separated by a space. \nThe following $m$ lines each contain two integers $u$ and $v$, indicating that there is a road between city $u$ and city $v$. The two integers are separated by a space.\n\n---\n\n### Output Format\n\nThe output file name is `travel.out`. \nThe output file contains a single line with $n$ integers, representing the sequence with the smallest lexicographical order. Adjacent integers are separated by a space.\n\n---\n\n### Example 1\n\nInput:\n```\n4 4\n1 2\n2 3\n3 4\n4 1\n```\n\nOutput:\n```\n1 2 3 4\n```\n\n---\n\n### Example 2\n\nInput:\n```\n3 3\n1 2\n1 3\n2 3\n```\n\nOutput:\n```\n1 2 3\n```\n\n---\n\n### Constraints and Notes\n\nFor all test cases, $1 \\le n \\le 5 \\times 10^3$, and $m = n-1$ or $m = n$. It is guaranteed that $1 \\le u, v \\le n$.\n\nFor different test points, the scale of the data is defined as follows:\n\n\n| Test Point | $n=$ | $m=$ | Special Properties |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 3$ | $10$ | $m=n-1$ | None |\n| $4,5$ | $100$ | $m=n-1$ | None |\n| $6 \\sim 8$ | $10^3$ | $m=n-1$ | Each city is connected to at most two other cities |\n| $9,10$ | $10^3$ | $m=n-1$ | None |\n| $11 \\sim 13$ | $5 \\times 10^3$ | $m=n-1$ | Each city is connected to at most three other cities |\n| $14,15$ | $5 \\times 10^3$ | $m=n-1$ | None |\n| $16,17$ | $10$ | $m=n$ | None |\n| $18,19$ | $100$ | $m=n$ | None |\n| $20 \\sim 22$ | $10^3$ | $m=n$ | Each city is connected to at most two other cities |\n| $23 \\sim 25$ | $5 \\times 10^3$ | $m=n$ | None |\n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2606, "prompt": "### Problem Description\n\nDuring college, it is often necessary to rent classrooms. Whether for faculty-organized events or small group discussions, applications need to be made to the university to reserve classrooms. Classrooms vary in size and function, and the application process may differ depending on the applicant's identity.\n\nGiven the vast amount of classroom rental information, we naturally hope to address this problem programmatically.\n\nWe need to process the classroom rental data for the next $n$ days. On the $i$-th day, the school has $r_i$ classrooms available for rental. There are a total of $m$ requests, and each request is described by three positive integers $d_j$, $s_j$, $t_j$, which indicate that a requester needs to rent $d_j$ classrooms per day from day $s_j$ to day $t_j$ (both inclusive).\n\nAssume that requesters have no specific requirements regarding the size or location of the classrooms. In other words, for each request, we only need to provide $d_j$ classrooms per day, regardless of which specific classrooms are provided or whether they are the same classrooms each day.\n\nThe principle for renting classrooms is *first come, first served*. That is, we process the requests in the given order, allocating classrooms for each request one by one. If at any point we encounter a request that cannot be fully satisfied, we terminate the allocation process and notify the corresponding requester to modify their request. \"Cannot be fully satisfied\" means that on at least one day from day $s_j$ to day $t_j$, the number of remaining classrooms is less than $d_j$.\n\nYour task is to determine whether all requests can be fully satisfied. If not, identify the requester whose order needs to be modified.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of days and the total number of requests, respectively.\n\nThe second line contains $n$ positive integers, where the $i$-th number $r_i$ represents the number of classrooms available for rental on day $i$.\n\nThe following $m$ lines each contain three positive integers $d_j$, $s_j$, $t_j$, where $d_j$ indicates the number of classrooms needed per day, and $s_j$ and $t_j$ denote the start and end days of the rental period, respectively. Each pair of numbers in a line are separated by a single space. Both the days and requests are indexed starting from $1$.\n\n---\n\n### Output Format\n\nIf all requests can be fully satisfied, output a single line containing the integer $0$.\n\nOtherwise (if a request cannot be fully satisfied), output two lines: \n- The first line contains the negative integer $-1$. \n- The second line contains the index of the requester whose order needs to be modified.\n\n---\n\n### Sample\n\n#### Input\n```\n4 2\n4 3 2 3\n4 1 1\n3 2 4\n```\n\n#### Output\n```\n-1\n2\n```\n\n#### Explanation\nAfter fulfilling the 1st request, the remaining number of classrooms over the 4 days is $0$, $3$, $2$, $3$. For the 2nd request, which requires 3 classrooms daily from day 2 to day 4, the remaining classrooms on day 3 are only $2$, making it impossible to fully meet the request. Allocation stops, and the 2nd requester is notified to modify their request.\n\n---\n\n### Constraints and Notes\n\n- For 10% of test cases, $1 \\leq n, m \\leq 10^1$; \n- For 30% of test cases, $1 \\leq n, m \\leq 10^3$; \n- For 70% of test cases, $1 \\leq n, m \\leq 10^5$; \n- For 100% of test cases, $1 \\leq n, m \\leq 10^6$, $0 \\leq r_i, d_j \\leq 10^9$, $1 \\leq s_j \\leq t_j \\leq n$. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2358, "prompt": "### Problem Description\n\nLittle Nan has a cute set of toy figurines, each with a unique profession.\n\nOne day, these toy figurines hid Little Nan's glasses. She noticed that the toy figurines were arranged in a circle, with some facing inward and others facing outward, as shown in the following diagram:\n\n![](https://img.loj.ac.cn/2019/05/13/5cd9702499831.png)\n\nAt this point, the `singer` told Little Nan a riddle: \"The glasses are hidden with the toy figurine who is the 3rd toy figurine to my left, 1st toy figurine to their right, and 2nd toy figurine to their left.\"\n\nLittle Nan discovered that the direction the toy figurines are facing is crucial, as inward- and outward-facing toy figurines have opposite left and right directions. Specifically, a toy figurine facing inward has its left side in the clockwise direction, and its right side in the counter-clockwise direction. On the other hand, a toy figurine facing outward has its left side in the counter-clockwise direction and its right side in the clockwise direction.\n\nLittle Nan carefully identified and counted: \n\n- `singer` faces inward, and the 3rd toy figurine to the left is `archer`. \n- `archer` faces outward, and the 1st toy figurine to the right is `thinker`. \n- `thinker` faces outward, and the 2nd toy figurine to the left is `writer`.\n\nThus, the glasses are hidden with `writer`!\n\nAlthough she managed to retrieve her glasses successfully, Little Nan is still worried. If there are more toy figurines next time or if the riddle is longer, she might not be able to find the glasses. Hence, Little Nan hopes you can write a program to help her solve similar riddles. These riddles can specifically be described as follows:\n\nThere are $n$ toy figurines arranged in a circle. Their professions and directions are given. The first toy figurine tells Little Nan a riddle consisting of $m$ instructions. The $i^{th}$ instruction will take the form of \"count $s_i$ toy figurines to the left/right.\" You need to output the profession of the toy figurine reached by sequentially following all these instructions.\n\n---\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $m$, representing the number of toy figurines and the number of instructions, respectively.\n\nThe following $n$ lines each contain an integer and a string, specifying the direction and profession of each toy figurine in counter-clockwise order. Here, `0` indicates the toy figurine is facing inward, and `1` indicates the toy figurine is facing outward. No other values will appear. The string has a length of up to 10 characters, is composed of lowercase alphabets only, is non-empty, and each string is unique. The integer and string are separated by a single space.\n\nThe next $m$ lines each contain two integers $a_i$ and $s_i$, representing the $i^{th}$ instruction. Specifically, if $a_i = 0$, count $s_i$ toy figurines to the left; if $a_i = 1$, count $s_i$ toy figurines to the right. No other values for $a_i$ will appear. $1 \\leq s_i < n$.\n\n---\n\n### Output Format\n\nOutput a single string representing the profession of the toy figurine reached after sequentially following $m$ instructions starting from the first toy figurine.\n\n---\n\n### Example 1\n\nThis dataset corresponds to the example described in the \"Problem Description.\"\n\n### Example 2\n\n---\n\n### Constraints and Hints\n\n$1 \\leq n, m \\leq 100000$\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2422, "prompt": "### Problem Description\n\nNiuNiu has recently become obsessed with a card game called \"Fight the Landlord\". It is a game played with 54 poker cards: spades, hearts, clubs, diamonds ranging from $A$ to $K$, plus two jokers (small and big). In this game, the ranking of the cards is determined by their numeric values as follows: $3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < J < Q < K < A < 2 < \\text{small joker} < \\text{big joker}$, and card suits have no impact on card ranking. \n\nIn each game, a hand consists of $n$ cards. Players can play cards according to specific card patterns until they run out of cards. The player who plays all their cards first wins the game. Now, NiuNiu wants to know for several sets of hands how many moves are needed to play all the cards. \n\nPlease note that in this problem the types of card patterns allowed are slightly different from the standard \"Fight the Landlord\". The specific rules are as follows:\n\n| Card Pattern | Description |\n|--------------|-------------|\n| Single | One card. |\n| Pair | Two cards with the same numeric value. |\n| Triplet | Three cards with the same numeric value. |\n| Bomb | Four cards with the same numeric value, e.g., four $A$s. |\n| Rocket | The pair of jokers (small joker and big joker). |\n| Three-with-One | Three cards with the same numeric value + one single card, e.g., three 3s + single 4. |\n| Three-with-Two | Three cards with the same numeric value + one pair, e.g., three 3s + pair of 4s. |\n| Single Straight | Five or more consecutive single cards (excluding 2 and the two jokers), e.g., single 7 + single 8 + single 9 + single 10 + single $J$. |\n| Pair Straight | Three or more consecutive pairs (excluding 2 and the two jokers), e.g., pair of 3s + pair of 4s + pair of 5s. |\n| Triple Straight | Two or more consecutive triplets (excluding 2 and the two jokers), e.g., three 3s + three 4s + three 5s. |\n| Four-with-Two | Four cards with the same numeric value + any two single cards (or any two pairs), e.g., four 5s + single 3 + single 8 or four 4s + pair of 5s + pair of 7s. |\n\nAdditionally, for straight patterns (Single Straight, Pair Straight, Triple Straight), the suits of the cards are not required to be the same.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $T$ and $N$, separated by a space, representing the number of card hands and the number of cards in each hand.\n\nNext come $T$ groups of data. Each group contains $N$ lines, and each line consists of a pair of non-negative integers $A_i, B_i$ separated by a space, representing a card. Here:\n- $A_i$ represents the numeric value of the card,\n- $B_i$ represents the suit of the card. \n\nIn particular:\n- $1$ represents numeric $A$, \n- $11$ represents numeric $J$, \n- $12$ represents numeric $Q$, \n- $13$ represents numeric $K$. \n\nFor the suits:\n- Spades, hearts, clubs, diamonds are represented by $1, 2, 3, 4$ respectively. \n- The small joker is represented by `0 1`, and the big joker is represented by `0 2`.\n\n---\n\n### Output Format\n\nOutput $T$ lines. Each line contains an integer, indicating the minimum number of moves needed to play all cards in the $i$-th hand.\n\n---\n\n### Example 1\n\n\n\n---\n\n### Example 2\n\n\n\n---\n\n### Constraints and Hints\n\n| Test Case | $T$ | $n$ |\n|-----------|-----|-----|\n| $1 \\sim 6$ | $T=100$ | $n \\leq 4$ |\n| $7 \\sim 12$ | $T=100$ | $n = \\text{Test Case Number} + 3$ |\n| $13 \\sim 20$ | $T=10$ | $n = \\text{Test Case Number} + 3$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2083, "prompt": "### Problem Description\n\nIf a string can be divided into the form $\\text{AABB}$, where $\\text{A}$ and $\\text{B}$ are any **non-empty** substrings, we consider such a division of the string as excellent. \nFor example, for the string $ \\texttt{aabaabaa} $, if we let $\\text{A}=\\texttt{aab}$ and $\\text{B}=\\texttt{a}$, we find one way to divide the string into $\\text{AABB}$.\n\nA string may have no excellent division, or it may have more than one excellent division. \nFor instance, letting $\\text{A}=\\texttt{a}$ and $\\text{B}=\\texttt{baa}$ also expresses the above string as $\\text{AABB}$. However, the string $\\texttt{abaabaa}$ has no excellent division.\n\nGiven a string $S$ of length $n$, we need to calculate, among all substrings of $S$ and all their division methods, the total number of excellent divisions. Here, a substring is defined as a consecutive segment within the string.\n\nThe following points are noteworthy:\n\n1. Identical substrings appearing at different positions are considered distinct, and their excellent divisions each contribute to the total count.\n2. In one division, it is allowed to have $\\text{A}=\\text{B}$. For example, the string $\\texttt{cccc}$ has an excellent division where $\\text{A}=\\text{B}=\\texttt{c}$.\n3. The string itself is also considered one of its substrings.\n\n---\n\n### Input Format\nThe input file contains multiple test cases. \nThe first line of the input file contains a single integer $T$, representing the number of test cases. \nIn the next $T$ lines, each line contains a string $S$ composed solely of lowercase English letters, as described above.\n\n---\n\n### Output Format\nOutput $T$ lines, each containing an integer representing the total number of excellent divisions across all substrings of string $S$.\n\n---\n\n### Example\nUse $S[i, j]$ to denote the substring starting at the $i$-th character and ending at the $j$-th character of string $S$ (indexed starting from $1$).\n\n#### Example Explanation:\n\n**First Test Case:** \nThere are three substrings with excellent divisions: \n$S[1,4]=\\texttt{aabb}$, excellent division: $\\text{A}=\\texttt{a}$, $\\text{B}=\\texttt{b}$; \n$S[3,6]=\\texttt{bbbb}$, excellent division: $\\text{A}=\\texttt{b}$, $\\text{B}=\\texttt{b}$; \n$S[1,6]=\\texttt{aabbbb}$, excellent division: $\\text{A}=\\texttt{a}$, $\\text{B}=\\texttt{bb}$. \nOther substrings have no excellent divisions, so the answer for the first test case is $3$. \n\n**Second Test Case:** \nThere are two types, totaling four substrings with excellent divisions: \nFor the substrings $S[1,4]=S[2,5]=S[3,6]=\\texttt{cccc}$, their excellent division is the same: $\\text{A}=\\texttt{c}$, $\\text{B}=\\texttt{c}$, but because these substrings appear at different positions, they are counted separately, contributing three to the total; \nFor the substring $S[1,6]=\\texttt{cccccc}$, it has two excellent divisions: $\\text{A}=\\texttt{c}$, $\\text{B}=\\texttt{cc}$ and $\\text{A}=\\texttt{cc}$, $\\text{B}=\\texttt{c}$. Both contribute to the total. \nThus, the answer for the second test case is $3+2=5$. \n\n**Third Test Case:** \n$S[1,8]$ and $S[4,11]$ each have two excellent divisions. $S[1,8]$ is the example given in the problem description. \nThus, the answer for the third test case is $2+2=4$. \n\n**Fourth Test Case:** \nThe substrings $S[1,4]$, $S[6,11]$, $S[7,12]$, $S[2,11]$, $S[1,8]$ each have one excellent division, and $S[3,14]$ has two excellent divisions. \nThus, the answer for the fourth test case is $5+2=7$. \n\n---\n\n### Constraints and Notes\nFor all test cases, $1 \\leq T \\leq 10$, $n \\leq 30000$. \n\nSpecific constraints for each test case are as follows: \n\n| Test Case | $n\\le$ | Special Property | \n|:-:|:-:|:-:| \n| $1,~2$ | $300$ | All characters in $S$ are the same | \n| $3,~4$ | $2000$ | All characters in $S$ are the same | \n| $5,~6$ | $10$ | No special constraints | \n| $7,~8$ | $20$ | No special constraints | \n| $9,~10$ | $30$ | No special constraints | \n| $11,~12$ | $50$ | No special constraints | \n| $13,~14$ | $100$ | No special constraints | \n| $15$ | $200$ | No special constraints | \n| $16$ | $300$ | No special constraints | \n| $17$ | $500$ | No special constraints | \n| $18$ | $1000$ | No special constraints | \n| $19$ | $2000$ | No special constraints | \n| $20$ | $30000$ | No special constraints | \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2664, "prompt": "### Problem Description\nThe inner product of two $d$-dimensional vectors $A=[a_1, a_2 ,...,a_d]$ and $B=[b_1 ,b_2 ,...,b_d]$ is the sum of the products of their corresponding dimensions, defined as:\n$$\n(A, B) = \\displaystyle \\sum_{i=1}^d{a_i b_i} = a_1b_1 + a_2b_2 + \\ldots + a_d b_d\n$$\nGiven $n$ $d$-dimensional vectors $x_1, \\ldots, x_n$, Little Meow-Meow wants to know whether there exist two vectors whose inner product is a multiple of $k$. Please help her solve this problem.\n\n### Input Format\nThe first line contains $3$ positive integers $n, d, k$, representing the number of vectors, the dimension of each vector, and the multiple to check respectively.\n\nThe next $n$ lines each contain $d$ non-negative integers, where the $i$-th line's $j$-th integer represents the $j$-th dimension weight of vector $[x_i]$, denoted as $x_{i,j}$.\n\n### Output Format\nThe output contains two integers separated by a space.\n\nIf there exist two vectors $x_p, x_q$ such that their inner product is a multiple of $k$, output the indices $p$ and $q$ (where $p < q$). If there are multiple pairs of vectors satisfying this condition, output any pair.\n\nIf no such pair of vectors exists, output two $-1$.\n\n### Example\nIf\n$(x_1, x_2) = 1$, \n$(x_1, x_3) = 1$, \n$(x_2, x_3) = 2$, \n\nan example solution could look like:\n```\n- Example output not explicitly provided in the initial translation -\n```\n\n### Constraints and Hints\n| Test Case ID | $n$ | $d$ | $k$ | $x_i$ |\n| :-: | :-: | :-: | :-: | :-: |\n| $1$ | $2$ | $20$ | $2$ | $\\leq 10$ |\n| $2$ | $5$ | $20$ | $2$ | $\\leq 10$ |\n| $3$ | $10$ | $20$ | $3$ | $\\leq 10$ |\n| $4$ | $20$ | $20$ | $2$ | $\\leq 100$ |\n| $5$ | $50$ | $20$ | $3$ | $\\leq 100$ |\n| $6$ | $50$ | $50$ | $2$ | $\\leq 1000$ |\n| $7$ | $50$ | $50$ | $3$ | $\\leq 3000000$ |\n| $8$ | $80$ | $80$ | $2$ | $\\leq 2000000$ |\n| $9$ | $100$ | $100$ | $3$ | $\\leq 3000000$ |\n| $10$ | $500$ | $100$ | $3$ | $\\leq 3000000$ |\n| $11$ | $1000$ | $100$ | $2$ | $\\leq 2000000$ |\n| $12$ | $1000$ | $100$ | $3$ | $\\leq 3000000$ |\n| $13$ | $10000$ | $100$ | $2$ | $< 10$ |\n| $14$ | $10000$ | $100$ | $3$ | $< 10$ |\n| $15$ | $15000$ | $100$ | $2$ | $< 10$ |\n| $16$ | $18000$ | $100$ | $2$ | $< 10$ |\n| $17$ | $20000$ | $100$ | $2$ | $< 10$ |\n| $18$ | $50000$ | $30$ | $3$ | $< 10$ |\n| $19$ | $80000$ | $30$ | $3$ | $< 10$ |\n| $20$ | $100000$ | $30$ | $3$ | $< 10$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2416, "prompt": "### Problem Description\n\nTom has recently been studying an interesting sorting problem. As shown below, with the help of two stacks, $S_1$ and $S_2$, Tom wants to use the following four operations to sort an input sequence in ascending order.\n\n![Illustration](https://img.loj.ac.cn/2022/06/09/65db667c2656e.png)\n\n1. Operation $a$: Push the first element into stack $S_1$.\n2. Operation $b$: Pop the top element from stack $S_1$ into the output sequence.\n3. Operation $c$: Push the first element into stack $S_2$.\n4. Operation $d$: Pop the top element from stack $S_2$ into the output sequence.\n\nIf a permutation $P$ of $1\\sim n$ can be sorted into $(1, 2, \\dots, n-1, n)$ in ascending order via a series of valid operations, Tom calls $P$ a \"double-stack sortable permutation.\" For example, $(1, 3, 2, 4)$ is a \"double-stack sortable sequence,\" while $(2, 3, 4, 1)$ is not. The figure below illustrates an example of sorting $(1, 3, 2, 4)$ using the operation sequence $\\texttt{a,c,c,b,a,d,d,b}$.\n\n![Example Illustration](https://img.loj.ac.cn/2022/06/09/5e3b49af0ae9d.png)\n\nOf course, there could be multiple operation sequences for sorting such permutations. For instance, for the sequence $(1, 3, 2, 4)$, the sequence $\\texttt{a,b,a,a,b,b,a,b}$ is another feasible operation sequence. Tom wants to know the lexicographically smallest operation sequence among all valid ones.\n\n---\n\n### Input Format\n\nThe first line contains an integer $n$. \nThe second line contains $n$ positive integers separated by spaces, forming a permutation of $1\\sim n$. \n\n---\n\n### Output Format\n\nOutput a single line: \n- If the input permutation is not a \"double-stack sortable permutation,\" output `0`.\n- Otherwise, output the lexicographically smallest operation sequence, with each operation separated by a single space and no trailing spaces at the end of the line.\n\n---\n\n### Example 1\n\n#### Input:\n```\n4\n1 3 2 4\n```\n\n#### Output:\n```\na c c b a d d b\n```\n\n---\n\n### Example 2\n\n#### Input:\n```\n4\n2 3 4 1\n```\n\n#### Output:\n```\n0\n```\n\n---\n\n### Example 3\n\n#### Input:\n```\n4\n1 2 3 4\n```\n\n#### Output:\n```\na b a b a b a b\n```\n\n---\n\n### Constraints and Hints\n- For $30\\%$ of the test cases, $n \\leq 10$.\n- For $50\\%$ of the test cases, $n \\leq 50$.\n- For $100\\%$ of the test cases, $n \\leq 1000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2613, "prompt": "### Problem Description\n\nLittle B has recently become obsessed with the \"Huarong Dao\" puzzle. However, it usually takes him a long time to complete it. Therefore, he thought about programming to solve the puzzle: given an initial state of the board, determine whether the puzzle is unsolvable, and if solvable, calculate the minimum time needed to solve it.\n\nThe variant of the puzzle played by Little B differs slightly from the classic Huarong Dao game. The rules are as follows:\n\n1. There is an $n \\times m$ grid, consisting of $n \\times m$ cells. Among them, exactly one cell is empty, while the remaining $n \\times m - 1$ cells each contain a piece. Each piece occupies exactly a $1 \\times 1$ cell.\n2. Some pieces are fixed and cannot be moved, while other pieces are movable.\n3. Any movable piece that is adjacent (sharing one edge) to the empty cell can move into the empty cell. The objective of the game is to move a specific movable piece to a designated target position.\n\nGiven the board layout, the game can be played $q$ times. For each game, the board's fixed pieces remain unchanged, but the initial position of the empty cell, the initial position of the specified movable piece, and the target position of that piece may vary. In the $i$-th game, the empty cell starts at position $(\\mathit{EX}_i, \\mathit{EY}_i)$, the specified movable piece starts at $(\\mathit{SX}_i, \\mathit{SY}_i)$, and the target position for that piece is $(\\mathit{TX}_i, \\mathit{TY}_i)$.\n\nAssuming Little B can perform one move operation per second and that other operations take negligible time, determine the minimum time required for each game, or conclude that the game is unsolvable.\n\n---\n\n### Input Format\n\nThe first line of input contains $3$ integers, separated by spaces, representing $n$, $m$, and $q$, respectively.\n\nThe next $n$ lines describe the $n \\times m$ grid. Each line contains $m$ integers, separated by spaces. Each integer describes the state of a cell:\n- $0$: The piece in the cell is fixed and cannot be moved.\n- $1$: The piece in the cell is movable, or the cell is empty.\n\nThe subsequent $q$ lines each contain $6$ integers, separated by spaces. For the $i$-th game, these integers are $\\mathit{EX}_i$, $\\mathit{EY}_i$, $\\mathit{SX}_i$, $\\mathit{SY}_i$, $\\mathit{TX}_i$, $\\mathit{TY}_i$, representing:\n- Initial position of the empty cell: $(\\mathit{EX}_i, \\mathit{EY}_i)$,\n- Initial position of the specified movable piece: $(\\mathit{SX}_i, \\mathit{SY}_i)$,\n- Target position of the specified movable piece: $(\\mathit{TX}_i, \\mathit{TY}_i)$.\n\n---\n\n### Output Format\n\nThe output consists of $q$ lines. Each line contains a single integer:\n- The minimum time required to complete the game.\n- Or `-1` if the game is unsolvable.\n\n---\n\n### Example\n\nThe cells marked with \"X\" on the board are fixed. The red cell represents the target position, and circles represent the movable pieces. The green circle denotes the specified piece that needs to be moved to the red target.\n\n#### Game 1:\nThe empty cell starts at position $(3, 2)$ (as shown in the diagram), and the goal is to move the specified piece starting at position $(1, 2)$ (green circle) to the target position $(2, 2)$ (red cell).\n\nThe movement steps are as follows:\n\n![puzzle1.png](https://img.loj.ac.cn/2021/12/29/a3e5253055667.png)\n\n#### Game 2:\nThe empty cell starts at position $(1, 2)$ (as shown in the diagram), and the goal is to move the specified piece starting at position $(2, 2)$ (green circle) to the target position $(3, 2)$.\n\n![puzzle2.png](https://img.loj.ac.cn/2021/12/29/20f5e38dae017.png)\n\nTo move the specified piece to the target position, the empty cell would need to occupy the target position first. However, for the empty cell to reach the target position, it would need to swap places with the piece currently occupying the target position. This creates a dependency loop, making the game unsolvable.\n\n---\n\n### Constraints and Hints\n\n- For $30\\%$ of the data: $1 \\leq n, m \\leq 10$, and $q = 1$,\n- For $60\\%$ of the data: $1 \\leq n, m \\leq 30$, and $q \\leq 10$,\n- For $100\\%$ of the data: $1 \\leq n, m \\leq 30$, and $q \\leq 500$,\n- It is guaranteed that $(\\mathit{EX}_i, \\mathit{EY}_i) \\neq (\\mathit{SX}_i, \\mathit{SY}_i)$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2442, "prompt": "### Problem Description\nFarmer Dongdong has been struggling with his income recently. While worrying about how to earn more money, he overheard some children next door discussing the problem of rabbit reproduction. \n\nThe problem is as follows: At the beginning of the first month, there is a pair of newborn baby rabbits. After two months of growth, this pair of rabbits starts producing one pair of baby rabbits at the beginning of each month starting from the third month. Newly born rabbits will also reach maturity in two months, after which they will start producing one pair of rabbits each month. How many rabbits will there be by the $n$-th month? \n\nYou, being clever, might have already realized that the number of rabbits in the $n$-th month is the $n$-th Fibonacci number. Dongdong doesn't understand what Fibonacci numbers are, but he also observed the pattern: the number of rabbits in month $i+2$ equals the sum of the rabbit count in month $i$ and month $i+1$. The number of rabbits in the first few months is:\n\n$$ 1, 1, 2, 3, 5, 8, 13, 21, 34 \\dots $$\n\nDongdong noticed that the number of rabbits grows faster and faster as the months progress, and he optimistically believes raising rabbits will make him rich. Thus, Dongdong started raising rabbits by purchasing one pair of baby rabbits at the beginning of the first month. \n\nEvery day, Dongdong feeds the rabbits. The rabbits eat in a peculiar way: every $k$ pairs of rabbits form a feeding circle, and the leftover pairs (less than $k$) also form a circle. Starting from the third month, if any feeding circle consists of only one pair of rabbits, then that pair of rabbits will quickly die. Assume that the deceased are always the newborn rabbits. As a result, the number of rabbits for each month can still be computed. For example, when $k=7$, the number of rabbits in the first few months is:\n\n$$ 1, 1, 2, 3, 5, 7, 12, 19, 31, 49, 80 \\dots $$\n\nGiven $n$, can you help Dongdong calculate how many **pairs** of rabbits he will have in the $n$-th month? Since the answer could be very large, you only need to tell Dongdong the remainder of the number of rabbit pairs in the $n$-th month divided by $p$. \n\n### Input Format\nThe input consists of a single line containing three positive integers $n$, $k$, $p$. \n\n### Output Format\nOutput a single line containing an integer, which is the remainder of the number of rabbit pairs in the $n$-th month divided by $p$. \n\n### Sample 1\n\n```\nInput: \n10 5 100 \nOutput: \n55 \n```\n\n### Sample 2\n\n```\nInput: \n50 7 1000 \nOutput: \n265 \n```\n\n### Data Range and Hints\n\n| Test Case ID | $n$ | $k,p$ |\n| :-: | :-: | :-: |\n| 1 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 2 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 3 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 4 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 5 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 6 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 7 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 8 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 9 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 10 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 11 | $1 \\leq n \\leq 80$ | $2 \\leq k,p \\leq 10,000$ |\n| 12 | $1 \\leq n \\leq 1000$ | $2 \\leq k,p \\leq 10,000$ |\n| 13 | $1 \\leq n \\leq 1000$ | $2 \\leq k,p \\leq 10,000$ |\n| 14 | $1 \\leq n \\leq 10^6$ | $2 \\leq k,p \\leq 10^6$ |\n| 15 | $1 \\leq n \\leq 10^6$ | $2 \\leq k,p \\leq 10^6$ |\n| 16 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k,p \\leq 1000$ |\n| 17 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k,p \\leq 1000$ |\n| 18 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k \\leq 10^6,2 \\leq p \\leq 10^9$ |\n| 19 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k \\leq 10^6,2 \\leq p \\leq 10^9$ |\n| 20 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k \\leq 10^6,2 \\leq p \\leq 10^9$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2360, "prompt": "### Problem Description\nFor NiuNiu, who has just entered university, his first challenge is how to choose suitable courses based on the actual situation.\n\nAmong the available courses, there are $2n$ classes scheduled in $n$ time slots. In the $i$-th time slot ($1 \\leq i \\leq n$), two identical classes are held simultaneously at different locations. NiuNiu is pre-assigned to classroom $c_i$, and the other class is held in classroom $d_i$. \nWithout submitting any applications, students are required to follow the class schedule and attend all $n$ classes in sequential order. If a student wants to switch to classroom $d_i$ for the $i$-th class, they need to submit an application. If the application is approved, the student can attend the class in classroom $d_i$; otherwise, they will attend the class in classroom $c_i$. \nDue to the high demand for classroom changes, applications may not necessarily be approved. After calculation, NiuNiu finds that the probability of the application for switching the $i$-th class being approved is a known real number $k_i$. The application probabilities for different classes are independent of each other. \nThe university stipulates that all applications must be submitted once before the academic term begins, and each person can select up to $m$ classes for which they will apply for changes. This means NiuNiu must decide once whether to apply for each class change, without being able to adjust the decision based on the outcome of prior applications. NiuNiu can apply to switch the $m$ most desired classes or choose not to use up to $m$ opportunities, or even decide not to apply for any class. \n\nBecause different classes might be held in different classrooms, NiuNiu needs to travel from one classroom to another between classes. \nNiuNiu's university has $v$ classrooms and $e$ roads. Each road connects two classrooms and is bidirectional. Due to varying road lengths and congestion levels, traveling via different roads may consume different levels of physical energy. When the $i$-th ($1 \\leq i \\leq n - 1$) class ends, NiuNiu will start from that class's classroom and choose the least physically exhaustive path to travel to the next class's classroom. \n\nNow NiuNiu wants to determine which classes he should apply for to minimize the expected total physical energy expenditure from traveling between classrooms. Please help him calculate this minimum value.\n\n---\n\n### Input Format\nThe first line contains four integers $n$, $m$, $v$, $e$, where: \n- $n$ represents the number of time slots in the semester. \n- $m$ represents the maximum number of classes NiuNiu can apply for a change in classrooms. \n- $v$ represents the number of classrooms in NiuNiu's university. \n- $e$ represents the number of roads in NiuNiu's university. \n\nThe second line contains $n$ positive integers, where the $i$-th ($1 \\leq i \\leq n$) integer represents $c_i$, the classroom NiuNiu is initially scheduled for in the $i$-th time slot. Ensure that $1 \\leq c_i \\leq v$. \n\nThe third line contains $n$ positive integers, where the $i$-th ($1 \\leq i \\leq n$) integer represents $d_i$, the alternate classroom for the same class in the $i$-th time slot. Ensure that $1 \\leq d_i \\leq v$. \n\nThe fourth line contains $n$ real numbers, where the $i$-th ($1 \\leq i \\leq n$) real number represents $k_i$, the probability that NiuNiu's application to switch to classroom $d_i$ during the $i$-th time slot is approved. Ensure that $0 \\leq k_i \\leq 1$. \n\nThe following $e$ lines each contain three integers $a_j, b_j, w_j$, representing a bidirectional road connecting classroom $a_j$ and classroom $b_j$. Traveling along this road costs $w_j$ physical energy. Ensure that $1 \\leq a_j, b_j \\leq v$ and $1 \\leq w_j \\leq 100$. \n\nGuarantees: \n- $1 \\leq n \\leq 2000$, $0 \\leq m \\leq 2000$, $1 \\leq v \\leq 300$, $0 \\leq e \\leq 90000$. \n- It is guaranteed that it is possible to travel between any two classrooms using the university's roads. \n- The input real numbers will have at most $3$ decimal places.\n\n---\n\n### Output Format\nOutput a single line containing a real number, rounded to exactly two decimal places, representing the answer. Your output must match the standard output format exactly to be considered correct. \n\nFor the testing data, it is guaranteed that the absolute difference between the rounded answer and the accurate answer will not exceed $4 \\times 10^{-3}$. (If you are unfamiliar with floating-point errors, you can understand this as: for most algorithms, you can normally use floating-point types without requiring special handling.)\n\n---\n\n### Sample\n\n---\n\n### Data Constraints and Hints\n$1 \\leq n, m \\leq 2000, 1 \\leq v \\leq 300, 1 \\leq e \\leq 90000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2246, "prompt": "### Problem Description\n\nRecently, the zoo director discovered that more and more lazy animals were appearing in the zoo. For example, penguins only know how to act cute and beg tourists for food. In order to rectify the bad habits in the zoo and encourage the animals to earn their food through their true talents, the director decided to open an algorithm class for the animals to learn programming.\n\nOne day, the director explained the KMP algorithm: \nDirector: \"For a string $S$, with a length of $L$, we can calculate an array named $\\textrm{next}$ in $O(L)$ time. Has anyone reviewed the meaning of the $\\textrm{next}$ array?\" \nPanda: \"For the substring formed by the first $i$ characters of $S$, the length of the longest string (excluding itself) that is both a prefix and a suffix of the substring is denoted as $\\textrm{next}_i$.\" \nDirector: \"Very good! Can you give an example?\" \nPanda: \"For instance, if $S$ is `abcababc`, then $\\textrm{next}_5=2$, because the first five characters of $S$ are `abcab`, and `ab` is both a prefix and a suffix, and there is no longer string satisfying this property. Similarly, we can obtain $\\textrm{next}_1 = \\textrm{next}_2 = \\textrm{next}_3 = 0,\\ \\textrm{next}_4 = \\textrm{next}_6 = 1,\\ \\textrm{next}_7 = 2,\\ \\textrm{next}_8 = 3$.\" \n\nThe director praised Panda for his thorough preparation. Then, the director explained in detail how to calculate the $\\textrm{next}$ array in $O(L)$ time.\n\nBefore the class ended, the director raised a question: \"The KMP algorithm can only calculate the $\\textrm{next}$ array. Now I want to calculate an even more powerful $\\textrm{num}$ array \u2014 for the substring formed by the first $i$ characters of $S$, count the number of strings that are both prefixes and suffixes of this substring, ensuring those prefixes and suffixes do not overlap. Denote this count as $\\textrm{num}_i$. For example, if $S$ is `aaaaa`, then $\\textrm{num}_4 = 2$, because the first four characters of $S$ are `aaaa`, where both `a` and `aa` satisfy the property of being prefixes and suffixes, and they do not overlap. However, `aaa` satisfies the property but overlaps, so it is not counted. Similarly, $\\textrm{num}_1 = 0,\\ \\textrm{num}_2 = \\textrm{num}_3 = 1,\\ \\textrm{num}_5 = 2$.\"\n\nFinally, the director announced a reward: the first student to solve the problem would receive a box of chocolate. Upon hearing this, the penguin, who had been sleeping during the lecture, woke up immediately. However, the penguin doesn't know how to solve the problem, so he is asking for help from you, the tourist visiting the zoo. Can you help the penguin write a program to calculate the $\\textrm{num}$ array?\n\nSpecifically, to avoid excessive output, you do not need to explicitly output $\\textrm{num}_i$ for each $i$. Instead, you only need to output $\\prod_{i=1}^L (\\textrm{num}_i+1) \\mod 1,000,000,007$.\n\n---\n\n### Input Format\n\nThe first line contains a positive integer $n$, indicating the number of test cases. \nThe subsequent $n$ lines each describe a test case. \nEach test case contains only one string $S$, as defined in the problem description. The data ensures that $S$ only contains lowercase letters. The input file will not contain extra blank lines, and there will be no trailing spaces at the end of lines.\n\n---\n\n### Output Format\n\nThe output contains $n$ lines, each describing the result of one test case. The order of the results should correspond to the order of the input data. \nFor each test case, output a single integer, which represents the result of the test case modulo $1,000,000,007$. The output file should not contain any extra blank lines.\n\n---\n\n### Example\n\n#### Input\n```\n2\naaaaa\nabcababc\n```\n\n#### Output\n```\n6\n36\n```\n\n---\n\n### Constraints and Hints\n\nFor all data, $n \\leq 5, L \\leq 10^6$.\n\n| Test Case No. | Constraints |\n|:-------------:|:-----------:|\n| $1$ | $n \\leq 5, L \\leq 50$ |\n| $2$ | $n \\leq 5, L \\leq 200$ |\n| $3$ | $n \\leq 5, L \\leq 200$ |\n| $4$ | $n \\leq 5, L \\leq 10,000$ |\n| $5$ | $n \\leq 5, L \\leq 10,000$ |\n| $6$ | $n \\leq 5, L \\leq 100,000$ |\n| $7$ | $n \\leq 5, L \\leq 200,000$ |\n| $8$ | $n \\leq 5, L \\leq 500,000$ |\n| $9$ | $n \\leq 5, L \\leq 1,000,000$ |\n| $10$ | $n \\leq 5, L \\leq 1,000,000$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2314, "prompt": "### Problem Description\n\nXiao Kai has two types of gold coins, each with a positive integer denomination, and the two denominations are coprime. He has an unlimited number of each denomination. Without providing change, there are some items whose value cannot be paid exactly using these two types of coins. Xiao Kai wants to know the maximum value of an item that cannot be paid exactly without providing change. \n**Note**: It is guaranteed that there exist items Xiao Kai cannot pay for exactly.\n\n### Input Format\n\nThe input consists of just one line, containing two positive integers $a$ and $b$ separated by a space, representing the denominations of Xiao Kai's gold coins.\n\n### Output Format\n\nThe output consists of just one line, containing one positive integer $N$, which represents the maximum value of an item that Xiao Kai cannot pay exactly for without providing change.\n\n### Example\n\nXiao Kai has an unlimited number of coins with denominations 3 and 7. Without providing change, he cannot pay exactly for items with values $1, 2, 4, 5, 8, 11$. The most expensive item he cannot pay exactly for is valued at $11$. \nFor example, any value greater than $11$ can be paid exactly: \n- $ 12 = 3 \\times 4 + 7 \\times 0$\n- $ 13 = 3 \\times 2 + 7 \\times 1$\n- $ 14 = 3 \\times 0 + 7 \\times 2$\n- $ 15 = 3 \\times 5 + 7 \\times 0$\n\n### Constraints and Hints\n\n- For $30\\%$ of the test cases: $ 1 \\le a, b \\le 50$\n- For $60\\%$ of the test cases: $1 \\le a, b \\le 10,000$\n- For $100\\%$ of the test cases: $1 \\le a, b \\le 1,000,000,000$ \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2602, "prompt": "### Problem Description\n\nIn the 16th century, French diplomat Blaise de Vigen\u00e8re designed a polyalphabetic cipher encryption algorithm called the Vigen\u00e8re Cipher. The Vigen\u00e8re Cipher is simple to use for both encryption and decryption while being relatively difficult to crack, which made it widely adopted by the Confederate Army during the American Civil War.\n\nIn cryptography, the information to be encrypted is called the plaintext, denoted as $M$. The encrypted information is called the ciphertext, denoted as $C$. A key is a parameter used as input in the algorithm to convert plaintext into ciphertext or decrypt ciphertext back into plaintext. The key is denoted as $K$ and is a string, $K = k_1k_2 \\dots k_n$. When the plaintext $M = m_1m_2 \\dots m_n$, the corresponding ciphertext $C = c_1c_2 \\dots c_n$ is obtained, where $c_i = m_i \\mathbin{\u00ae} k_i$. The operation $\u00ae$ follows the rules in the table below:\n\n![vigenere.png](https://img.loj.ac.cn/2021/12/29/96f91ff36955b.png)\n\nIn Vigen\u00e8re encryption, the following rules are observed:\n\n1. The $\u00ae$ operation ignores the case of the letters involved in the operation but preserves the case format of the letters in the plaintext $M$.\n2. If the length of the plaintext $M$ exceeds the length of the key $K$, the key $K$ is repeated cyclically.\n\nFor example, given plaintext $M = \\texttt{Helloworld}$ and key $K = \\texttt{abc}$, the ciphertext $C = \\texttt{Hfnlpyosnd}$.\n\n| Plaintext | H | e | l | l | o | w | o | r | l | d |\n|-----------|:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|\n| Key | a | b | c | a | b | c | a | b | c | a |\n| Ciphertext| H | f | n | l | p | y | o | s | n | d |\n\n### Input Format\n\nThe first line contains a string representing the key $K$. The length of $K$ does not exceed $100$, and it consists only of uppercase and lowercase letters.\n\nThe second line contains a string representing the encrypted ciphertext. The length of the ciphertext does not exceed $1,000$, and it consists only of uppercase and lowercase letters.\n\n### Output Format\n\nOutput one line, a string representing the plaintext corresponding to the given key and ciphertext.\n\n### Example\n\n#### Input:\n```\nabc\nHfnlpyosnd\n```\n\n#### Output:\n```\nHelloworld\n```\n\n### Constraints and Notes\n\nFor 100% of the test cases, the length of the input key does not exceed $100$ and the length of the input ciphertext does not exceed $1,000$. Both the key and ciphertext consist only of uppercase and lowercase letters.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2674, "prompt": "### Problem Description\n\nTo welcome students from all over the country, the city of CZ is hosting a grand food festival.\n\nAs someone who loves to try new dishes, Little M naturally doesn't want to miss out on this feast. He quickly tried all the dishes at the food festival. However, the urge to taste new things is insatiable. Even though all the dishes are tasty and the chefs cook them quickly, Little M still finds it unbearable to not have dishes on his table that are already served at someone else's. Thus, Little M started studying the order of cooking, in an attempt to arrange a sequence that minimizes the waiting time for students.\n\nLittle M noticed that there are $n$ different dishes available at the food festival. Each time a student orders, they can choose **one dish** among the $n$ types. There are $m$ chefs preparing these dishes. After all students have placed their orders, the cooking tasks for the dishes are assigned to the chefs. Each chef then begins cooking simultaneously. **The chefs must cook the dishes in the specified order, and they can only cook one serving at a time.**\n\nAdditionally, Little M discovered another interesting thing: while all $m$ chefs can prepare all $n$ types of dishes, **the time taken to prepare the same dish may vary from chef to chef**. The dishes are numbered as $1, 2, \\ldots, n$, and the chefs are numbered as $1, 2, \\ldots , m$. The time taken by the $j$th chef to prepare the $i$th type of dish is denoted as $t_{i,j}$.\n\nLittle M believes that the waiting time for each student is defined as **the total time, starting from when all chefs begin cooking, to when their ordered dish is completed**. In other words, if a dish ordered by a student is the $k$th dish prepared by a chef, their waiting time is the sum of the times for the chef to prepare their first $k$ dishes in sequence. The **total waiting time** is defined as the sum of the waiting times for all students.\n\nNow, Little M has obtained the dish order information from all the students\u2014$p_i$ students have ordered the $i$th type of dish ($i = 1, 2, \\ldots , n$). He wants to know the minimum possible **total waiting time**.\n\n---\n\n### Input Format\n\nThe first line of the input file contains two positive integers $n$ and $m$, representing the number of dish types and the number of chefs. \n\nThe second line contains $n$ positive integers, where the $i$th number is $p_i$, representing the number of students who have ordered the $i$th type of dish.\n\nThe next $n$ lines each contain $m$ non-negative integers. The $i$th line contains $m$ numbers, where the $j$th number is $t_{i,j}$, representing the time taken by the $j$th chef to prepare the $i$th dish.\n\nAdjacent numbers in each line are separated by a single space, and there are no trailing spaces at the end of each line.\n\n---\n\n### Output Format\n\nThe output contains only one line with a single integer, representing the minimum total waiting time.\n\n---\n\n### Example\n\nChef $1$ first cooks $1$ serving of dish $2$, then cooks $2$ servings of dish $1$. The three students who ordered these dishes have waiting times of $3, 3+5=8, 3+5+5=13$, respectively. \n\nChef $2$ first cooks $1$ serving of dish $1$, then cooks $1$ serving of dish $3$. The two students who ordered these dishes have waiting times of $7, 7+9=16$, respectively. \n\nThe total waiting time is $3+8+13+7+16=47$. \n\nAlthough dish $1$ and dish $3$ are cooked faster by chef $1$, if all servings of these dishes were cooked by chef $1$, the total waiting time would be longer. By assigning $1$ serving of dish $1$ and $1$ serving of dish $3$ to chef $2$, this arrangement ensures chef $2$ doesn't remain idle, reducing the total waiting time.\n\nIt can be proven that no better serving arrangement exists than the above.\n\n---\n\n### Constraints and Hints\n\nFor $100\\%$ of the data, $n \\leq 40$, $m \\leq 100$, $p \\leq 800$, and $t_{i,j} \\leq 1000$ (where $p = \\sum{p_i}$, representing the total number of students ordering dishes).\n\nThe values of $n$, $m$, and $p$ for each test case are as follows:\n\n| Test Case | $n$ | $m$ | $p$ |\n| :-: | :-: | :-: | :-: |\n| 1 | $n=5$ | $m=5$ | $p=10$ |\n| 2 | $n=40$ | $m=1$ | $p=400$ |\n| 3 | $n=40$ | $m=2$ | $p=300$ |\n| 4 | $n=40$ | $m=40$ | $p=40$ |\n| 5 | $n=5$ | $m=40$ | $p=100$ |\n| 6 | $n=10$ | $m=50$ | $p=200$ |\n| 7 | $n=20$ | $m=60$ | $p=400$ |\n| 8 | $n=40$ | $m=80$ | $p=600$ |\n| 9 | $n=40$ | $m=100$ | $p=800$ |\n| 10 | $n=40$ | $m=100$ | $p=800$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2319, "prompt": "### Problem Description\n\nSylvia is a girl who loves learning.\n\nRecently, Sylvia participated in her school\u2019s military training. As we all know, military training often involves standing in a square formation. Sylvia\u2019s square formation consists of $n \\times m$ students, with $n$ rows and $m$ columns.\n\nFor ease of management, the instructor numbered the students from $1$ to $n \\times m$ at the beginning of training, in front-to-back, left-to-right order (as shown in the example below). Specifically, initially, the student in row $i$ and column $j$ has the number $(i \u2212 1) \\times m + j$.\n\nHowever, during formation exercises, it sometimes happens that a student leaves the team due to various reasons. Over the course of a day, a total of $q$ such departure events occur. Each student departure event can be described using a pair $(x, y)$ ($1 \\leq x \\leq n, 1 \\leq y \\leq m)$, indicating that the student at row $x$ and column $y$ left the formation.\n\nWhen a student leaves the formation, a vacancy appears. To maintain the integrity of the formation, the instructor issues two sequential commands:\n\n1. **Align to the left**: At this point, the first column remains unchanged, and all other students shift left to fill the vacancy. After this command, the vacancy will be in row $x$, column $m$.\n\n2. **Align forward**: At this point, the first row remains unchanged, and all other students shift upward to fill the vacancy. After this command, the vacancy will be in row $n$, column $m$.\n\nThe instructor specifies that two or more students cannot leave at the same time. This means that each student can only leave the formation after the previously departed student has returned to fill the vacancy. Thus, at the moment when each departing student is about to return, there is only one vacancy in the square formation, located in row $n$, column $m$. The departing student naturally fills this position.\n\nSince standing in formation is really boring, Sylvia wants to calculate the number of each departing student for every single departure event.\n\n**Note**: The numbering of each student does not change due to departure events. After such events, the numbering of students in the formation may become disordered.\n\n---\n\n### Input Format\n\nThe input consists of $q+1$ lines:\n\n- The first line contains three positive integers $n$, $m$, and $q$, separated by spaces, indicating the size of the square formation with $n$ rows and $m$ columns, and the occurrence of a total of $q$ events.\n- The next $q$ lines describe the $q$ events in chronological order. Each line consists of two integers $x, y$, separated by a space, indicating that the student in row $x$, column $y$ is the one leaving the formation in this event.\n\n---\n\n### Output Format\n\nFor each event, output a single integer on a separate line, indicating the number of the departing student for that event.\n\n---\n\n### Example\n\n$$\\large\\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}\\Rightarrow\\begin{bmatrix}&2\\\\3&4\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&\\\\3&4\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}$$\n\n$$\\large\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}$$\n\n$$\\large\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&1\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&1\\\\3&4\\end{bmatrix}$$\n\nThe process of rearranging the formation for each event is illustrated in the diagram above.\n\nFor the first event, student number $1$ leaves the formation, resulting in the vacancy being in the first row and first column. All students then align to the left, with student number $2$ moving one step left to fill the vacancy, which then moves to the first row and second column. All students then align forward, with student number $4$ moving one step upward, and the vacancy moves to the second row and second column. Finally, student number $1$ returns to fill the vacancy.\n\n---\n\n### Data Constraints and Notes\n\n\n\n| Test Case ID | $n$ | $m$ | $q$ | Other Constraints |\n|:-:|:-:|:-:|:-:|:-:|\n| $1\\sim 6$ | $\\le 1000$ | $\\le 1000$ | $\\le 500$ | None |\n| $7\\sim 10$ | $\\le 5 \\times 10^{4}$ | $\\le 5 \\times 10^{4}$ | $\\le 500$ | None |\n| $11,12$ | $=1$ | $\\le 10^{5}$ | $\\le 10^{5}$ | All events $x=1$ |\n| $13,14$ | $=1$ | $\\le 3\\times 10^{5}$ | $\\le 3\\times 10^{5}$ | All events $x=1$ |\n| $15,16$ | $\\le 3 \\times 10^{5}$ | $\\le 3\\times 10^{5}$ | $\\le 3\\times 10^{5}$ | All events $x=1$ |\n| $17,18$ | $\\le 10^{5}$ | $\\le 10^{5}$ | $\\le 10^{5}$ | None |\n| $19,20$ | $\\le 3 \\times 10^{5}$ | $\\le 3 \\times 10^{5}$ | $\\le 3 \\times 10^{5}$ | None |\n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2302, "prompt": "### Problem Description\nDr. P abstracts his computational tasks as operations on an integer.\n\nSpecifically, there is an integer $x$, which initially has a value of $0$.\n\nThen, there are $n$ operations, each being one of the two types below:\n\n- `1 a b`: Add the integer $a\\cdot 2^b$ to $x$, where $a$ is an integer, and $b$ is a non-negative integer.\n\n- `2 k`: Query the value of the $2^k$ bit in the binary representation of $x$ (i.e., whether this bit is $1$ or $0$, with $1$ representing $2^k$).\n\nIt is guaranteed that, at any time, $x \\geqslant 0$.\n\n### Input Format\nThe first line of input contains four positive integers $n,t_1,t_2,t_3$, where the meaning of $n$ is described above, and $t_1$, $t_2$, $t_3$ correspond to the subtasks.\n\nThe next $n$ lines each describe one operation, with the format and meaning detailed above.\n\n### Output Format\nFor each query operation, output one line representing the result of the query ($0$ or $1$). There is no output for addition operations.\n\nAcross all test cases, $1 \\leqslant t_1 \\leqslant 3$, $1 \\leqslant t_2 \\leqslant 4$, $1 \\leqslant t_3 \\leqslant 2$. The specific constraints for different values of $t_1$, $t_2$, and $t_3$ are as follows:\n\n- For test cases where $t_1 = 1$, $a = 1$.\n- For test cases where $t_1 = 2$, $|a| = 1$.\n- For test cases where $t_1 = 3$, $|a| \\leqslant 10^9$.\n- For test cases where $t_2 = 1$, $0 \\leqslant b, k \\leqslant 30$.\n- For test cases where $t_2 = 2$, $0 \\leqslant b, k \\leqslant 100$.\n- For test cases where $t_2 = 3$, $0 \\leqslant b, k \\leqslant n$.\n- For test cases where $t_2 = 4$, $0 \\leqslant b, k \\leqslant 30n$.\n- For test cases where $t_3 = 1$, all query operations occur after all modification operations.\n- For test cases where $t_3 = 2$, there is no guarantee on the order of query operations and modification operations.\n\nThis problem consists of 25 test cases, each worth 4 points. The data range for each test case is described below:\n\n| Test Case Number | $n \\leq$ | $t_1$ | $t_2$ | $t_3$ |\n|:-:|:-:|:-:|:-:|:-:|\n| $1$ | $10$ | $3$ | $1$ | $2$ |\n| $2$ | $100$ | $3$ | $2$ | $2$ |\n| $3$ | $2000$ | $3$ | $2$ | $2$ |\n| $4$ | $4000$ | $1$ | $3$ | $2$ |\n| $5$ | $6000$ | $3$ | $3$ | $1$ |\n| $6$ | $8000$ | $2$ | $3$ | $2$ |\n| $7$ | $9000$ | $3$ | $4$ | $2$ |\n| $8$ | $10000$ | $3$ | $3$ | $2$ |\n| $9$ | $30000$ | $3$ | $4$ | $2$ |\n| $10$ | $50000$ | $3$ | $4$ | $1$ |\n| $11$ | $60000$ | $3$ | $3$ | $2$ |\n| $12$ | $65000$ | $2$ | $4$ | $2$ |\n| $13$ | $70000$ | $3$ | $4$ | $2$ |\n| $14$ | $200000$ | $3$ | $4$ | $2$ |\n| $15$ | $300000$ | $2$ | $4$ | $2$ |\n| $16$ | $400000$ | $3$ | $4$ | $2$ |\n| $17$ | $500000$ | $3$ | $3$ | $2$ |\n| $18$ | $600000$ | $3$ | $4$ | $2$ |\n| $19$ | $700000$ | $3$ | $4$ | $2$ |\n| $20$ | $800000$ | $1$ | $4$ | $2$ |\n| $21$ | $900000$ | $2$ | $4$ | $2$ |\n| $22$ | $930000$ | $3$ | $3$ | $2$ |\n| $23$ | $960000$ | $3$ | $4$ | $1$ |\n| $24$ | $990000$ | $3$ | $3$ | $2$ |\n| $25$ | $1000000$ | $3$ | $4$ | $2$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2603, "prompt": "### Problem Description\nOn the occasion of the National Day in the Kingdom of H, the king invited $n$ ministers to participate in a prize-winning game. First, he asked each minister to write an integer on their left and right hands. The king also wrote an integer on his left and right hands. Then, the $n$ ministers were arranged in a line, with the king standing at the front of the queue. Once the lineup was complete, all the ministers would receive a certain number of gold coins as a reward. The number of coins each minister receives is calculated as follows: **\"The product of all the integers on the left hands of the people standing in front of that minister in the queue\" divided by **\"the integer on the minister's right hand,\" rounded down.**\n\nThe king wanted to ensure that no single minister ended up receiving too much of a reward. Therefore, he sought your help in rearranging the lineup of the ministers to minimize the maximum reward received by any minister. **Note that the king's position is fixed at the front of the lineup.**\n\n### Input Format\nThe first line contains an integer $n$ denoting the number of ministers.\n\nThe second line contains two integers $a$ and $b$, separated by a space, representing the numbers written on the king's left and right hands, respectively.\n\nThe following $n$ lines each contain two integers $a$ and $b$, separated by a space, representing the two integers on the left and right hands of each minister.\n\n### Output Format\nOutput a single integer: the minimum possible value of the maximum reward received by any minister after rearranging the lineup.\n\n### Example\n- In the arrangement with ministers 1, 2, 3, the maximum reward is $2$;\n- In the arrangement with ministers 1, 3, 2, the maximum reward is $2$;\n- In the arrangement with ministers 2, 1, 3, the maximum reward is $2$;\n- In the arrangement with ministers 2, 3, 1, the maximum reward is $9$;\n- In the arrangement with ministers 3, 1, 2, the maximum reward is $2$;\n- In the arrangement with ministers 3, 2, 1, the maximum reward is $9$.\n\nThus, the minimum possible value of the maximum reward is $2$. The output is $2$.\n\n### Constraints and Notes\n- For 20% of the test cases: $1 \\leq n \\leq 10$, $0 < a, b < 8$;\n- For 40% of the test cases: $1 \\leq n \\leq 20$, $0 < a, b < 8$;\n- For 60% of the test cases: $1 \\leq n \\leq 100$;\n- For 60% of the test cases, the answer is guaranteed to not exceed $10^9$;\n- For 100% of the test cases: $1 \\leq n \\leq 1,000$, $0 < a, b < 10,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2612, "prompt": "### Problem Description\nGardener Dongdong has planted a row of flowers, each with its own height. As the flowers grow larger, they become more cramped. Dongdong has decided to remove some of the flowers from this row to leave the remaining ones with space to grow. At the same time, Dongdong wants the arrangement of the remaining flowers to look aesthetically pleasing.\n\nSpecifically, the heights of Dongdong's flowers can be represented as a sequence of integers $h_1, h_2, \\dots, h_n$. Suppose that after removing some flowers, the heights of the remaining flowers are $g_1, g_2, \\dots, g_m$. Dongdong wants at least one of the following two conditions to be satisfied:\n\n* For all integers $i$, $g_{2i} > g_{2i-1}$ and $g_{2i} > g_{2i+1}$;\n* For all integers $i$, $g_{2i} < g_{2i-1}$ and $g_{2i} < g_{2i+1}$.\n\nNote that in the case where $m = 1$, both of the conditions above are simultaneously satisfied. When $m > 1$, at most one of the conditions can be satisfied.\n\nPlease determine the maximum number of flowers that Dongdong can leave in place.\n\n---\n\n### Input Format\nThe first line contains a single integer $n$, representing the initial number of flowers.\n\nThe second line contains $n$ integers, $h_1, h_2, \\dots, h_n$, representing the heights of each flower.\n\n---\n\n### Output Format\nOutput a single integer $m$, representing the maximum number of flowers that can be left in place.\n\n---\n\n### Example\nThere are multiple ways to leave exactly $3$ flowers remaining. For instance, keeping the $1^\\text{st}$, $4^\\text{th}$, and $5^\\text{th}$ flowers, with heights $5$, $1$, and $2$ respectively, satisfies condition $B$.\n\n---\n\n### Constraints and Hints\nFor $15\\%$ of the test cases, $n \\leq 10$;\n\nFor $25\\%$ of the test cases, $n \\leq 25$;\n\nFor $55\\%$ of the test cases, $n \\leq 1,000$, $h_i \\leq 1,000$;\n\nFor $80\\%$ of the test cases, $n \\leq 100,000$, $h_i \\leq 10^6$, where all $h_i$ are randomly generated under a uniform distribution across arbitrary intervals;\n\nFor $100\\%$ of the test cases, $1 \\leq n \\leq 2,000,000$, $0 \\leq h_i \\leq 10^9$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2084, "prompt": "### Problem Description\n\nThe King of Fleas and the King of Crickets are playing a game.\n\nThey are arranging their armies on a grid with $n$ rows and $m$ columns. Among these, $c$ cells $(0 \\leq c \\leq n \\cdot m)$ have a cricket placed on them, and each of the other cells has a flea.\n\nWe consider two fleas occupying adjacent cells (sharing an edge) as **neighbors**.\n\nWe consider two fleas to be **connected** if and only if they are neighbors, or there exists another flea that is connected to both of them.\n\nNow, the King of Crickets wishes to replace some (zero, one, or more) fleas with crickets such that after this replacement, there exist at least two fleas that are not connected.\n\n\"left\"\n\"right\"\n\nFor example, we use the image \"flea\" to represent a flea and the image \"cricket\" to represent a cricket. The left diagram demonstrates a scenario where $n=4$, $m=4$, and $c=2$.\n\nIn this scenario, the King of Crickets can achieve his goal by replacing the fleas at the cells in the second row, second column, and the third row, third column with crickets, as shown in the right diagram. There is no better solution, though there may be other ways to replace two fleas. \n\nYour task is to determine whether it is possible for the King of Crickets to achieve his goal. If it is possible, you need to minimize the number of fleas replaced.\n\n---\n\n### Input Format\n\nThe input consists of multiple test cases.\n\nThe first line of the input contains a single integer $T$, representing the number of test cases.\n\nFor each of the next $T$ test cases:\n\n- The first line contains three integers $n$, $m$, and $c$.\n- The next $c$ lines each contain two integers $x, y$, where $x$ and $y$ denote the row and column indices of a cell occupied by a cricket. Each cricket is described only once in the input. \n- Consecutive integers on the same line are separated by a single space.\n\n---\n\n### Output Format\n\nFor each test case, output a single line containing the answer.\n\n- If it is impossible for the King of Crickets to achieve his goal, output `-1`.\n- Otherwise, output the minimum number of fleas that must be replaced.\n\n---\n\n### Examples\n\n**Example 1 (First Case)** \nThis case corresponds to the situation described in the problem description. \n\n**Example 2 (Second Case)** \nThe King of Crickets can achieve his goal by replacing the flea at the second row, second column with a cricket such that there exist two fleas that are not connected. There is no better solution in this case.\n\n**Example 3 (Third Case)** \nInitially, there are already two fleas that are not connected, so no replacement is necessary.\n\n**Example 4 (Fourth Case)** \nSince there is at most one flea, it is impossible to make two fleas unconnected no matter how replacements are made.\n\n---\n\n### Constraints and Notes\n\nFor all test cases:\n\n- $1 \\leq n, m \\leq 10^9$\n- $0 \\leq c \\leq \\min(n \\cdot m, 10^5)$\n- $1 \\leq x \\leq n$\n- $1 \\leq y \\leq m$\n- $1 \\leq T \\leq 20$\n\nLet $\\sum c$ denote the total sum of $c$ values across all $T$ test cases in a single dataset. It is guaranteed that $\\sum c \\leq 10^5$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2589, "prompt": "### Problem Description\n\nDr. Hanks is a renowned expert in the BT (Bio-Tech) field, and his son\u2019s name is Hankson. Now, after returning home from school, Hankson is pondering an interesting problem.\n\nToday in class, the teacher explained how to calculate the greatest common divisor (GCD) and least common multiple (LCM) of two positive integers $c_1$ and $c_2$. Now, Hankson believes he has fully mastered this knowledge and has started thinking about a reverse problem concerning \"finding the GCD\" and \"finding the LCM.\" The problem is as follows: Given four positive integers $a_0, a_1, b_0, b_1$, suppose there exists some unknown positive integer $x$ that satisfies the following conditions:\n\n1. The greatest common divisor of $x$ and $a_0$ is $a_1$;\n2. The least common multiple of $x$ and $b_0$ is $b_1$.\n\nHankson's \"reverse problem\" is to find all integers $x$ that satisfy these conditions. However, after a bit of thought, he realizes that such $x$ may not be unique, or may not even exist. Therefore, he\u2019s shifted focus to determine how many such integers $x$ satisfy the conditions. Your task is to help him write a program to solve this problem.\n\n---\n\n### Input Format\n\nThe first line contains a positive integer $n$, representing the number of test cases. \nThe next $n$ lines each contain a group of four positive integers $a_0, a_1, b_0, b_1$, with each pair of integers separated by a space. \nThe input data guarantees that $a_0$ is divisible by $a_1$ and $b_1$ is divisible by $b_0$.\n\n---\n\n### Output Format\n\nOutput a total of $n$ lines. The result for each test case should occupy one line and be a single integer. \nFor each group of input data: \n- If no such $x$ exists, output `0`. \n- If there are $k$ integers $x$ that satisfy the conditions, output $k$.\n\n---\n\n### Example\n\n#### Input:\n```plaintext\n2\n36 9 24 288\n48 24 1776 1776\n```\n\n#### Output:\n```plaintext\n6\n2\n```\n\n#### Explanation: \n- For the first test case, the possible values of $x$ are $9, 18, 36, 72, 144, 288$, for a total of $6$ values. \n- For the second test case, the possible values of $x$ are $48$ and $1776$, for a total of $2$ values.\n\n---\n\n### Constraints and Hints\n\n- For $50\\%$ of the test cases, it is guaranteed that $a_0, a_1, b_0, b_1 \\leq 10^4$ and $n \\leq 100$. \n- For $100\\%$ of the test cases, it is guaranteed that $1 \\leq a_0, a_1, b_0, b_1 \\leq 2 \\times 10^9$ and $n \\leq 2000$. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2363, "prompt": "### Problem Description\nKiana has recently become obsessed with a magical game. \nIn simple terms, the game takes place on a 2D plane. A slingshot is located at $ (0, 0) $, and each time, Kiana can use it to shoot a bird into the first quadrant. The birds follow flight trajectories in the form of $ y = ax^2 + bx $, where $ a $ and $ b $ are parameters specified by Kiana, and $ a $ must satisfy $ a < 0 $. When a bird falls back to the ground (i.e., the $ x $-axis), it instantly disappears.\n\nIn a certain level of the game, there are $ n $ pigs located in the first quadrant, with the $ i $-th pig positioned at $ (x_i, y_i) $. If a bird's flight trajectory passes through $ (x_i, y_i) $, the $ i $-th pig will be eliminated, and the bird will continue to fly along its original trajectory. If the bird\u2019s trajectory doesn\u2019t pass through $ (x_i, y_i) $, then the bird's flight has no effect on the $ i $-th pig. \nFor example, if two pigs are located at $ (1, 3) $ and $ (3, 3) $, Kiana can choose to shoot a bird with the flight trajectory $ y = -x^2 + 4x $, and both pigs will be eliminated by this bird. \nThe goal of the game is to eliminate all pigs with as few birds as possible.\n\nEach level of this magical game is quite challenging, so Kiana has entered some mysterious instructions to make it easier for herself to complete the game. These instructions are specified in the \"Input Format\" section below. \nIt is assumed that there are $ T $ levels in this game, and Kiana wants to figure out, for each level, how many birds are needed at minimum to eliminate all the pigs. Since Kiana isn\u2019t good at calculations, she asks you to solve this for her.\n\n### Input Format\nThe first line contains a positive integer $ T $, representing the total number of game levels.\n\nThe following input consists of information for these $ T $ levels. For each level, the first line contains two non-negative integers $ n $ and $ m $, representing the number of pigs and the type of mysterious instructions entered by Kiana for that level, respectively.\n\nThe next $ n $ lines contain two positive real numbers $ (x_i, y_i) $, indicating that the $ i $-th pig is located at $ (x_i, y_i) $. It is guaranteed that no two pigs in the same level have the exact same coordinates.\n\n- If $ m = 0 $, it means Kiana entered an instruction with no effect. \n- If $ m = 1 $, this level satisfies: at most $ \\lceil \\frac{n}{3} + 1 \\rceil $ birds are required to eliminate all the pigs. \n- If $ m = 2 $, this level satisfies: there must exist an optimal solution where at least one bird eliminates at least $ \\lfloor \\frac{n}{3} \\rfloor $ pigs.\n\nThe constraints guarantee that $ 1 \\leq n \\leq 18 $, $ 0 \\leq m \\leq 2 $, $ 0 < x_i, y_i < 10 $, and all real numbers in the input are preserved to two decimal places.\n\nIn the above notation, $ \\lceil x \\rceil $ and $ \\lfloor x \\rfloor $ represent the ceiling and floor functions of $ x $, respectively.\n\n### Output Format\nFor each level, output a single line.\n\nEach line contains a positive integer representing the minimum number of birds required to eliminate all the pigs in the corresponding level.\n\n### Sample 1\nIn this example, there are two levels.\n\nFor the first level, the situation is the same as described in the \"Problem Description\": there are $ 2 $ pigs located at $ (1.00, 3.00) $ and $ (3.00, 3.00) $, which can be eliminated by shooting one bird on the trajectory $ y = -x^2 + 4x $.\n\nIn the second level, there are $ 5 $ pigs, but upon observation, it is found that all their coordinates lie on the parabola $ y = -x^2 + 6x $, so Kiana only needs to shoot one bird to eliminate all the pigs.\n\n### Sample 2\n\n(additional examples can be added here for demonstration consistency)\n\n### Sample 3\n\n(additional examples can be added here for demonstration consistency)\n\n### Constraints and Hints\n\n| Test Point Index | $n\\leqslant$ | $m=$ | $T\\leqslant$ |\n| :----------: | :----------: | :----------: | :----------: |\n| $1$ | $2$ | $0$ | $10$ |\n| $2$ | $2$ | $0$ | $30$ |\n| $3$ | $3$ | $0$ | $10$ |\n| $4$ | $3$ | $0$ | $30$ |\n| $5$ | $4$ | $0$ | $10$ |\n| $6$ | $4$ | $0$ | $30$ |\n| $7$ | $5$ | $0$ | $10$ |\n| $8$ | $6$ | $0$ | $10$ |\n| $9$ | $7$ | $0$ | $10$ |\n| $10$ | $8$ | $0$ | $10$ |\n| $11$ | $9$ | $0$ | $30$ |\n| $12$ | $10$ | $0$ | $30$ |\n| $13$ | $12$ | $1$ | $30$ |\n| $14$ | $12$ | $2$ | $30$ |\n| $15$ | $15$ | $0$ | $15$ |\n| $16$ | $15$ | $1$ | $15$ |\n| $17$ | $15$ | $2$ | $15$ |\n| $18$ | $18$ | $0$ | $5$ |\n| $19$ | $18$ | $1$ | $5$ |\n| $20$ | $18$ | $2$ | $5$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2425, "prompt": "### Problem Description\n\nIn the year $2044$, humanity has entered the space age.\n\nCountry L has $n$ planets and $n - 1$ bidirectional space routes. Each space route connects two planets and these $n - 1$ space routes form a connected graph of all the planets in Country L.\n\nA logistics company managed by Xiao P has received numerous transportation plans. Each transportation plan specifies that a logistics spaceship needs to travel from planet $u_i$ to planet $v_i$ along the fastest space route. Clearly, traveling through a space route costs time. For space route $j$, the time required for any spaceship to traverse it is $t_j$, and there is no interference between different spaceships.\n\nTo foster technological innovation, the king of Country L allows Xiao P's logistics company to participate in the construction of space routes. Specifically, Xiao P is permitted to upgrade one of the space routes into a wormhole. A wormhole allows spaceships to traverse it without consuming any time.\n\nBefore the construction of the wormhole is completed, Xiao P\u2019s logistics company has already pre-scheduled $m$ transportation plans. Once the wormhole is complete, these $m$ transportation plans will begin simultaneously, with all spaceships departing at the same time. Xiao P's logistics company\u2019s phase of work is considered complete when all $m$ transportation plans are finished.\n\nIf Xiao P is free to choose which space route to upgrade to a wormhole, determine the minimum time required for Xiao P\u2019s logistics company to complete this phase of work.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of planets in Country L and the number of transportation plans pre-scheduled by Xiao P's company. The planets are numbered from $1$ to $n$.\n\nThe next $n - 1$ lines describe the construction details of the space routes. Each of these lines contains three integers $a_i$, $b_i$, and $t_i$, indicating that the $i$-th bidirectional space route is built between planets $a_i$ and $b_i$, and the time required for any spaceship to traverse it is $t_i$.\n\nThe subsequent $m$ lines describe the transportation plans. Each line contains two positive integers $u_j$ and $v_j$, indicating that the $j$-th transportation plan involves traveling from planet $u_j$ to planet $v_j$.\n\n---\n\n### Output Format\n\nOutput a single line containing one integer, which represents the minimum time required for Xiao P\u2019s logistics company to complete this phase of work.\n\n---\n\n### Example\n\n---\n\n### Data Range and Hints\n\nFor $100\\%$ of the test cases: \n$100 \\leq n \\leq 300,000$, \n$1 \\leq m \\leq 300,000$, \n$1 \\leq a_i, b_i, u_i, v_i \\leq n$, \n$0 \\leq t_i \\leq 10^3$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2501, "prompt": "### Problem Description\n\nWith the increasing popularity of smartphones, the demand for wireless networks is growing rapidly. A city has decided to cover public places within the city with wireless networks.\n\nAssume the city layout is a grid formed by exactly $129$ east-west streets and $129$ north-south streets, with a distance of $1$ between adjacent parallel streets. The east-west streets are numbered from $0, 1, 2, \\ldots, 128$ from north to south, and the north-south streets are numbered $0, 1, 2, \\ldots, 128$ from west to east. \nThe intersections of the east-west and north-south streets are designated as junctions, and it is specified that the intersection of the north-south street with number $x$ and the east-west street with number $y$ has coordinates $(x, y)$. At some of these junctions, there exist a certain number of public places. \n\nDue to budget constraints, the city can only install one large wireless transmitter. The coverage of this wireless transmitter is a square of side length $2d$ centered at the installation point. The coverage includes the boundaries of the square. \nFor example, the figure below illustrates the coverage area of a wireless transmitter with $d = 1$. \n\n![wireless.png](https://img.loj.ac.cn/2019/02/24/5c72325da31df.png)\n\nThe local government needs to install a wireless transmitter with a propagation parameter of $d$, and seeks your help to determine the best possible junction for installation, such that the maximum number of public places are covered.\n\n### Input Format\n\nThe first line contains an integer $d$, representing the propagation radius of the wireless transmitter. \n\nThe second line contains an integer $n$, representing the number of junctions with public places. \n\nThe next $n$ lines each contain three integers $x, y, k$, separated by a space, which respectively represent the coordinates $(x, y)$ of a junction and the number of public places at that junction. The same coordinates will only be provided once.\n\n### Output Format\n\nOutput a single line containing two integers, separated by a space, representing the number of installation site plans that can cover the maximum number of public places and the maximum number of public places that can be covered.\n\n### Example\n\n#### Input\n```\n1\n3\n1 1 5\n2 2 8\n4 4 3\n```\n\n#### Output\n```\n4 13\n```\n\n### Data Constraints and Hints\n\n$1 \\leq d \\leq 20$, $1 \\leq n \\leq 20$, $0 \\leq x \\leq 128$, $0 \\leq y \\leq 128$, $0 < k \\leq 1000000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 3758, "prompt": "### Problem Description\n\nDongdong has a rectangular piece of land where he grows energy plants that can harness solar energy. After these plants collect energy, Dongdong uses an energy collection machine to gather all the energy collected by the plants.\n\nDongdong has planted the energy plants in a very neat arrangement. There are $n$ columns in total, and each column has $m$ plants. The horizontal and vertical spacing between the plants is uniform. Therefore, each plant can be represented by a coordinate $(x, y)$, where $x$ ranges from $1$ to $n$ and $y$ ranges from $1$ to $m$, representing the $y$-th plant in column $x$.\n\nBecause the energy collection machine is large and inconvenient to move, Dongdong placed it at a corner of the land with coordinates $(0, 0)$.\n\nDuring energy collection, there is a certain amount of energy loss. If a plant connected to the energy collection machine has $k$ plants located along the line segment between the plant and the machine, the energy loss is calculated as $2k + 1$. For example, when the energy collection machine gathers energy from the plant at coordinate $(2, 4)$, there is $1$ plant $(1, 2)$ located along the line segment, resulting in an energy loss of $3$. Note that if there are no plants along the line segment between a plant and the energy collection machine, the energy loss is $1$. The goal is to calculate the total energy loss.\n\nBelow is an example of energy collection where $n = 5$ and $m = 4$, with a total of $20$ plants. The energy loss caused by the machine collecting energy from each plant is labeled on each plant.\n\n![1654079504639.png](https://img.loj.ac.cn/2022/06/01/da7540f14de33.png)\n\nIn this example, the total energy loss is $36$.\n\n---\n\n### Input Format\n\nA single line contains two integers $n$ and $m$.\n\n---\n\n### Output Format\n\nA single integer representing the total energy loss.\n\n---\n\n### Example 1\n\n```\nInput:\n5 4\n\nOutput:\n36\n```\n\n---\n\n### Example 2\n\n```\nInput:\n3 3\n\nOutput:\n18\n```\n\n---\n\n### Constraints and Notes\n\n- For $10\\%$ of the test cases: $n, m \\leq 10$.\n- For $50\\%$ of the test cases: $n, m \\leq 100$.\n- For $80\\%$ of the test cases: $n, m \\leq 10^3$.\n- For $90\\%$ of the test cases: $n, m \\leq 10^4$.\n- For $100\\%$ of the test cases: $1 \\leq n, m \\leq 10^5$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2317, "prompt": "### Problem Description\nThere is a large piece of cheese with a height of $h$. Its length and width can be considered infinite. Inside the cheese, there are many spherical cavities with the **same radius**. We can establish a spatial coordinate system in the cheese. In this coordinate system, the bottom surface of the cheese is at $z = 0$, and the top surface of the cheese is at $z = h$.\n\nNow, on the bottom surface of the cheese, there is a small mouse named Jerry who knows the coordinates of the centers of all the cavities inside the cheese. If two cavities are tangent or intersect, Jerry can travel from one cavity to the other. Specifically:\n\n- If a cavity is tangent to or intersects the bottom surface, Jerry can travel from the bottom surface of the cheese into the cavity.\n- If a cavity is tangent to or intersects the top surface, Jerry can travel from the cavity to the top surface of the cheese.\n\nJerry, located on the bottom surface of the cheese, wants to know whether he can reach the top surface using the existing cavities, **without damaging the cheese**.\n\nThe distance between two points $P_1(x_1,y_1,z_1)$ and $P_2(x_2,y_2,z_2)$ in space is calculated using the following distance formula:\n\n$$\n\\operatorname{dist}(P_1,P_2)=\\sqrt{(x_1-x_2)^2+(y_1-y_2)^2+(z_1-z_2)^2}\n$$\n\n### Input Format\nThe input file contains multiple test cases.\n\n- The first line of the input file contains a positive integer $T$, representing the number of test cases in the file.\n\n- For the next $T$ sets of data, each test case is formatted as follows:\n - The first line of each test case contains three positive integers $n, h,$ and $r$, separated by spaces. These represent the number of cavities in the cheese, the height of the cheese, and the radius of the cavities, respectively.\n - The following $n$ lines each contain three integers $x, y, z$, separated by spaces, representing the coordinates of the centers of the spherical cavities $(x, y, z)$.\n\n### Output Format\nThe output file contains $T$ lines, corresponding to the answers for the $T$ test cases. If Jerry can travel from the bottom surface to the top surface in the $i$-th test case, output \u201cYes\u201d. Otherwise, output \u201cNo\u201d. (Exclude quotation marks.)\n\n### Sample\n![cheese.png](https://img.loj.ac.cn/2021/12/29/5940a76e8e720.png)\n\n### Constraints and Notes\n- For $20\\%$ of the data, $n = 1,$ $1 \\le h , r \\le 10^4$, and the absolute value of the coordinates does not exceed $10^4$.\n- For $40\\%$ of the data, $1 \\le n \\le 8,$ $1 \\le h , r \\le 10^4$, and the absolute value of the coordinates does not exceed $10^4$.\n- For $80\\%$ of the data, $1 \\le n \\le 1000,$ $1 \\le h , r \\le 10^4$, and the absolute value of the coordinates does not exceed $10^4$.\n- For $100\\%$ of the data, $1 \\le n \\le 1000,$ $1 \\le h , r \\le 10^9,$ $T \\le 20$, and the absolute value of the coordinates does not exceed $10^9$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2673, "prompt": "### Problem Description\n\nThe vacation has started, and Xiao Z feels incredibly bored staying at home. He decides to go to the amusement park alone. Upon entering the park, Xiao Z takes a look at the park's map and realizes he can abstract the amusement park as an **undirected connected graph with $n$ attractions and $m$ roads, where this graph contains at most one cycle (i.e., $m$ can only equal $n$ or $n-1$)**.\n\nThe entrance, where Xiao Z currently stands, is also considered one of the attractions. Xiao Z doesn\u2019t know which attractions would be fun, so he decides to start from his current position and randomly visit one of the attractions connected by a road. He also decides **not to revisit any attraction (including the starting point)** that he has already visited. Being playful, Xiao Z will continue exploring until there are no unvisited attractions adjacent to his current position.\n\nThe attractions visited by Xiao Z in order form a non-repeating path, and he wants to know the **expected length** of this path.\n\nXiao Z has sketched a map of the amusement park and brought it home, but he forgot to label which attraction is the entrance. Therefore, he assumes that every attraction is equally likely to be the starting point (i.e., all attractions have an equal probability of being the starting point). Additionally, whenever he chooses the next attraction to visit, he does so by **equally and randomly selecting** one of the **unvisited adjacent attractions**.\n\n---\n\n### Input Format\n\nThe input consists of the following:\n\nThe first line contains two integers, $n$ and $m$, representing the number of attractions and roads, respectively.\n\nThe next $m$ lines each contain three integers, $X_i$, $Y_i$, $W_i$, which denote a road connecting attractions $X_i$ and $Y_i$ with a length of $W_i$. All attractions are labeled from $1$ to $n$, and there is at most one road between any two attractions.\n\n---\n\n### Output Format\n\nOutput a single line containing a real number, which is the expected length of the path.\n\n---\n\n### Example\n\nIn the example, there are a total of $6$ possible paths:\n\n| Path | Length | Probability |\n|:-------------:|:------:|:-----------:|\n| $1 \\rightarrow 4$ | $8$ | $\\frac{1}{4}$ |\n| $2 \\rightarrow 1$ | $3$ | $\\frac{1}{8}$ |\n| $2 \\rightarrow 4$ | $5$ | $\\frac{1}{8}$ |\n| $3 \\rightarrow 1$ | $4$ | $\\frac{1}{8}$ |\n| $3 \\rightarrow 4$ | $4$ | $\\frac{1}{8}$ |\n| $4 \\rightarrow 1$ | $8$ | $\\frac{1}{4}$ |\n\nThus, the expected length is: \n$$ \\text{Expected Length} = \\frac{8}{4} + \\frac{3}{8} + \\frac{5}{8} + \\frac{4}{8} + \\frac{4}{8} + \\frac{8}{4} = 6.00 $$\n\n---\n\n### Constraints and Notes\n\nFor $100\\%$ of the test cases, $1 \\leq W_i \\leq 100$.\n\n| Test Case ID | $n$ | $m$ | Description |\n|:------------:|:-----:|:-----:|:-----------------------------------------------:|\n| 1 | $n=10$ | $m=n-1$ | The graph forms a linear chain. |\n| 2 | $n=100$ | $m=n-1$ | Only node $1$ has a degree greater than $2$. |\n| 3 | $n=1000$ | $m=n-1$ | - |\n| 4 | $n=100000$ | $m=n-1$ | - |\n| 5 | $n=100000$ | $m=n-1$ | - |\n| 6 | $n=10$ | $m=n$ | - |\n| 7 | $n=100$ | $m=n$ | The number of nodes in the cycle $\\leq 5$. |\n| 8 | $n=1000$ | $m=n$ | The number of nodes in the cycle $\\leq 10$. |\n| 9 | $n=100000$ | $m=n$ | The number of nodes in the cycle $\\leq 15$. |\n| 10 | $n=100000$ | $m=n$ | The number of nodes in the cycle $\\leq 20$. |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2610, "prompt": "### Problem Description\n\nCountry A has $n$ cities, numbered from $1$ to $n$, connected by $m$ bidirectional roads. Each road has a weight limit for vehicles, referred to as the weight limit. There are $q$ freight trucks transporting goods, and the drivers want to know the maximum weight of goods each truck can carry without exceeding the weight limit of the roads.\n\n### Input Format\n\nThe first line of the input contains two integers $n$ and $m$ separated by a space, indicating that Country A has $n$ cities and $m$ roads.\n\nThe next $m$ lines each contain three integers $x$, $y$, and $z$, separated by spaces, indicating that there is a road between City $x$ and City $y$ with a weight limit of $z$. Note that $x \\neq y$, and there may be multiple roads between two cities.\n\nThe next line contains a single integer $q$, indicating that there are $q$ freight trucks requiring transportation.\n\nThe following $q$ lines each contain two integers $x$ and $y$, separated by a space, indicating that a truck needs to transport goods from City $x$ to City $y$. Note that $x \\neq y$.\n\n### Output Format\n\nThe output comprises $q$ lines, each containing a single integer. For each truck, output the maximum weight it can carry. If the truck cannot reach its destination, output $-1$.\n\n### Example\n\n**Input:**\n```\n5 6\n1 2 10\n2 3 20\n3 4 30\n4 5 40\n1 3 15\n3 5 25\n2\n1 5\n2 4\n```\n\n**Output:**\n```\n25\n20\n```\n\n### Constraints and Hints\n\n- For 30% of the data, $0 < n < 1\\,000$, $0 < m < 10\\,000$, $0 < q < 1\\,000$;\n- For 60% of the data, $0 < n < 1\\,000$, $0 < m < 50\\,000$, $0 < q < 1\\,000$;\n- For 100% of the data, $0 < n < 10\\,000$, $0 < m < 50\\,000$, $0 < q < 30\\,000$, $0 \\leq z \\leq 100\\,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2669, "prompt": "### Problem Description\n\nLittle T plans to open a food delivery restaurant in city C. The delivery time to a certain location is proportional to the shortest path distance between the restaurant and that location. Little T wants to choose a location for the restaurant such that the maximum distance to the furthest customer is minimized.\n\nThe customers of the restaurant are distributed across $N$ buildings in city C. These $N$ buildings are connected by exactly $N$ bidirectional roads, and no two roads connect the same pair of buildings. Furthermore, there exists at least one path, formed by bidirectional roads, between any two buildings. The food delivery restaurant can be located in any building or at any point along any road (the location on the road does not necessarily need to have integer distances from the endpoints of the road).\n\nGiven the map of city C (the road layout and their lengths), please determine the optimal location for the restaurant and output the distance to the furthest customer.\n\n---\n\n### Input Format\n\nThe first line contains an integer $N$, representing the number of buildings and roads in city C.\n\nThe next $N$ lines each contain three integers $A_i$, $B_i$, and $L_i$ ($1 \\leq i \\leq N; L_i > 0$), describing a road that connects building $A_i$ and building $B_i$ with a length of $L_i$.\n\n---\n\n### Output Format\n\nOutput a real number rounded to exactly one decimal place, representing the distance to the furthest customer from the optimal restaurant location.\n\n**Note**: Your result must have exactly one decimal place. Solutions with incorrect decimal formatting will not receive points.\n\n---\n\n### Sample 1\n\n![](https://i.loli.net/2018/06/10/5b1d07c4dc6a4.png)\n\nAs shown in the figure, the optimal location is at building $1$. The distances to the $4$ buildings are $0$, $1$, $2$, and $2$ respectively.\n\n---\n\n### Sample 2\n\n![](https://i.loli.net/2018/06/10/5b1d081843770.png)\n\n---\n\n### Sample 3\n\nRefer to the attached files `foodshop.in` and `foodshop.ans`.\n\n---\n\n### Constraints and Hints\n\n- For $10\\%$ of the test cases, $N \\leq 80$, and $L_i = 1$;\n- For $30\\%$ of the test cases, $N \\leq 600$, and $L_i \\leq 100$;\n- For $60\\%$ of the test cases, $N \\leq 2000$, and $L_i \\leq 10^9$;\n- For $100\\%$ of the test cases, $N \\leq 10^5$, and $L_i \\leq 10^9$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2304, "prompt": "## Problem Description\n\nJiulian is a fun-loving girl.\n\nSummer vacation has finally arrived, and Jiulian decided to invite her friends for swimming. She plans to carve out a rectangular area in the sea near her private beach as the swimming zone. However, the sea is full of various dangers: some areas are too deep, while others have poisonous jellyfish. She wants the selected swimming area to be completely safe.\n\nAfter preliminary analysis, the sea area can be viewed as a rectangular grid of $N$ meters in width and $1001$ meters in height. The bottom edge of this rectangular grid corresponds to her private beach. Each square of size $1 \\:\\textrm{m}\\times 1\\:\\textrm{m}$ represents a unit of marine area. She asked her father to measure whether each unit of the marine area is safe tomorrow. Upon obtaining this information, what she needs to do is select the swimming zone.\n\nHer ideal swimming zone must satisfy the following criteria:\n* It must ensure safety: every unit in the swimming zone must be safe.\n* It must be rectangular, i.e., the swimming zone must be a subgrid of size $a\\times b$.\n* It must be adjacent to the beach: the bottom boundary of the swimming zone must be adjacent to the bottom edge of the grid.\n\nFor example, when $N = 5$, if the measurement results are as follows (since $1001$ is too large, only the bottom three rows are displayed, with the remaining areas assumed to be dangerous):\n\n\"Screen\n\nShe can select a $1\\times 4$ swimming area in the bottom row or a $3\\times 1$ swimming area in the third column. Note that she cannot select a $1\\times 5$ swimming area in the top row since it does not touch the beach.\n\nTo make the swimming experience enjoyable for her friends, she wants the swimming area's size to be as large as possible. Therefore, she would select the $1\\times 4$ swimming area in the bottom row as the final option.\n\nAlthough she will only know whether each unit is safe tomorrow, she wants to estimate the probability of the swimming area's size being __exactly__ $K$ now. Based on a simple estimate, she assumes each unit has an independent probability $q$ of being safe and a probability $1 - q$ of being unsafe. She wants you to calculate the value of this probability.\n\n## Input Format\n\nA single line containing four positive integers $N, K, x, y$, where $1 \\leq x < y < 998244353$. The value of $q$ is $\\frac{x}{y}$.\n\n## Output Format\n\nPrint a single integer\u2014representing the result modulo $998244353$.\n\nSpecifically, let the result be expressed as the irreducible fraction $\\frac{a}{b}$, where $a$ and $b$ are coprime. Output the integer $x$ such that $bx \\equiv a \\mod 998244353$ and $0 \\leq x < 998244353$. It can be proven that such an integer $x$ is unique.\n\n## Example\n\n*(No examples provided in the question.)*\n\n## Hints and Constraints\n\n#### Hint\n\n$x^{p-1} \\equiv 1 \\pmod p$, where $p$ is a prime and $x \\in [1, p)$.\n\n#### Subtasks\n\n| Test Case Index | $N$ | $K$ |\n|:-:|:-:|:-:|\n| 1,2 | $=1$ | $\\leq 1000$ |\n| 3 | $\\leq 10$ | $\\leq 8$ |\n| 4 | $\\leq 10$ | $\\leq 9$ |\n| 5 | $\\leq 10$ | $\\leq 10$ |\n| 6 | $\\leq 1000$ | $\\leq 7$ |\n| 7 | $\\leq 1000$ | $\\leq 8$ |\n| 8 | $\\leq 1000$ | $\\leq 9$ |\n| 9,10,11 | $\\leq 1000$ | $\\leq 100$ |\n| 12,13,14 | $\\leq 1000$ | $\\leq 1000$ |\n| 15,16 | $\\leq 10^9$ | $\\leq 10$ |\n| 17,18 | $\\leq 10^9$ | $\\leq 100$ |\n| 19,20 | $\\leq 10^9$ | $\\leq 1000$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2316, "prompt": "### Problem Description\n\nCeci loves visiting parks. A park can be represented as a directed graph with $N$ nodes and $M$ edges, without self-loops or multiple edges between any two nodes. Node $1$ is the entry to the park, and node $N$ is the exit. Each edge has a non-negative weight, which represents the time Ceci needs to spend traversing that edge. \n\nCeci visits the park every day. She always starts at node $1$ and exits at node $N$.\n\nCeci enjoys exploring new paths and doesn't want her routes to be exactly the same on different days. Additionally, as a diligent student, Ceci doesn\u2019t want to spend too much time walking in the park. If the shortest path from node $1$ to node $N$ has a length of $d$, Ceci will only consider routes with a length no greater than $d + K$. \n\nCeci wants to know how many such valid routes exist. Can you help her with the answer?\n\nTo avoid outputting excessively large numbers, output the answer modulo $P$.\n\nIf there are infinitely many valid routes, output $\u22121$.\n\n---\n\n### Input Format\n\nThe first line contains an integer $T$, representing the number of test cases. \n\nFor the next $T$ test cases: \n\n- The first line contains four integers $N, M, K, P$, separated by spaces.\n- The next $M$ lines each contain three integers $a_i, b_i, c_i$, indicating a directed edge from node $a_i$ to node $b_i$ with a weight of $c_i$. Each pair of integers is separated by a space.\n\n---\n\n### Output Format\n\nThe output should contain $T$ lines, each containing one integer representing the answer.\n\n---\n\n### Example\n\nFor the first test case, the shortest path has a length of $3$. \n\nThe three valid paths are: \n\n$1 - 5, 1 - 2 - 4 - 5, 1 - 2 - 3 - 5$. \n\n---\n\n### Sample Input \n\n``` \n1 \n5 6 0 100 \n1 2 1 \n2 3 1 \n2 4 1 \n3 5 1 \n4 5 1 \n1 5 3 \n```\n\n### Sample Output \n\n``` \n3 \n```\n\n---\n\n### Constraints and Hints\n\nFor different test cases, the maximum scale of each parameter can be **no larger than** the following:\n\n| Test Case Index | $T$ | $N$ | $M$ | $K$ | Edge with weight $0$ exists? |\n|:---------------:|:---:|:---:|:---:|:---:|:----------------------------:|\n| $1$ | $5$ | $5$ | $10$| $0$ | No |\n| $2$ | $5$ | $1000$ | $2000$ | $0$ | No |\n| $3$ | $5$ | $1000$ | $2000$ | $50$ | No |\n| $4$ | $5$ | $1000$ | $2000$ | $50$ | No |\n| $5$ | $5$ | $1000$ | $2000$ | $50$ | No |\n| $6$ | $5$ | $1000$ | $2000$ | $50$ | Yes |\n| $7$ | $5$ | $100000$ | $200000$ | $0$| No |\n| $8$ | $3$ | $100000$ | $200000$ | $50$| No |\n| $9$ | $3$ | $100000$ | $200000$ | $50$| Yes |\n| $10$ | $3$ | $100000$ | $200000$ | $50$| Yes |\n\nFor $100\\%$ of the data: \n\n$1 \\le P \\le 10^9, 1 \\le a_i, b_i \\le N, 0 \\le c_i \\le 1000$. \n\nThe data guarantees that there is at least one valid route.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2592, "prompt": "### Problem Description\n\nXiao Chen has a machine translation software installed on his computer, which he often uses to translate English articles.\n\nThe principle behind this translation software is quite simple. It works sequentially, translating each English word into its corresponding Chinese meaning. When processing each English word, the software first looks up its Chinese meaning in the memory. If the translation exists in the memory, it uses that for the translation. If not, the software searches for the word's meaning in the dictionary stored on external memory, translates the word, and then stores the word and its meaning in the memory for future lookups and translations.\n\nAssume the memory has $M$ slots, each capable of storing a word and its translation. Every time the software needs to store a new word in memory:\n1. If the current number of words in memory does not exceed $M\u22121$, the software will store the new word in an unused memory slot.\n2. If the memory already holds $M$ words, the software will evict the earliest-stored word to free up a slot and then store the new word.\n\nAssume the length of an English article is $N$ words. Given this article, how many times will the translation software need to look up the dictionary stored on external memory? Assume that the memory is empty at the beginning of the translation process.\n\n---\n\n### Input Format\n\nThe input consists of 2 lines, with numbers separated by a single space:\n\n1. The first line contains two positive integers $M$ and $N$, representing the memory capacity and the length of the article, respectively.\n2. The second line contains $N$ non-negative integers in article order, where each number (not exceeding $1,000$) represents an English word. Two words are the same if and only if they correspond to the same non-negative integer.\n\n---\n\n### Output Format\n\nThe output consists of a single integer, representing the number of times the software needs to look up the dictionary.\n\n---\n\n### Example 1\n\nKey steps of dictionary lookups and memory updates are given below; each line shows the memory state after processing a word, with the initial state denoted as \"empty\":\n\n- `empty`: The memory starts empty.\n1. `$1$`: Lookup word `$1$` and add it to memory.\n2. `$1$ $2$`: Lookup word `$2$` and add it to memory.\n3. `$1$ $2$`: Find word `$1$` in memory.\n4. `$1$ $2$ $5$`: Lookup word `$5$` and add it to memory.\n5. `$2$ $5$ $4$`: Lookup word `$4$` and replace word `$1$` in memory.\n6. `$2$ $5$ $4$`: Find word `$4$` in memory.\n7. `$5$ $4$ $1$`: Lookup word `$1$` and replace word `$2$` in memory.\n\nTotal dictionary lookups: `$5$`.\n\n---\n\n### Example 2\n\n_(No example text provided in original prompt.)_\n\n---\n\n### Data Range and Hints\n\n- For $10\\%$ of the test cases, $M=1$, and $N \\leq 5$.\n- For $100\\%$ of the test cases, $0 < M \\leq 100$ and $0 < N \\leq 1,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2597, "prompt": "### Problem Description\n\nAlong the riverside of Lijiang, there are $n$ uniquely styled inns, numbered from $1$ to $n$ according to their positions.\n\nEach inn is decorated using one of $k$ different color tones (numbered $0$ through $k-1$), and each inn has its own coffee shop with a minimum spending requirement.\n\nTwo tourists traveling to Lijiang share a preference for the same color tone, but they also want to try two different inns. Therefore, they decide to each stay in a different inn but with the same color tone.\n\nIn the evening, they plan to visit a coffee shop for coffee. The coffee shop must be located somewhere between the two inns (inclusive of the inns they stay in), and its minimum spending requirement must not exceed $p$.\n\nThey are curious about how many valid accommodation combinations exist such that the above evening coffee conditions are satisfied.\n\n---\n\n### Input Format\n\nThe input consists of $n+1$ lines.\n\n- The first line contains three integers $n$, $k$, and $p$, separated by a space, representing the number of inns, the total number of color tones, and the maximum acceptable minimum spending for the coffee shop, respectively. \n\n- The next $n$ lines each contain two integers, separated by a space. For the $i$-th line, the first integer represents the decoration color tone of Inn $i$, and the second integer represents the minimum spending required for the coffee shop in Inn $i$.\n\n---\n\n### Output Format\n\nThe output consists of a single line with one integer, representing the total number of valid accommodation combinations.\n\n---\n\n### Example\n\n![hotel.png](https://img.loj.ac.cn/2021/12/29/729407abe93ec.png)\n\nThe two tourists must stay in inns decorated with the **same color tone**, and all valid accommodation combinations include:\n- Stay in Inns $1$ and $3$,\n- Stay in Inns $2$ and $4$,\n- Stay in Inns $2$ and $5$,\n- Stay in Inns $4$ and $5$.\n\nHowever, if choosing Inns $4$ and $5$, the coffee shops between these two inns have a minimum spending requirement of $4$, but the maximum acceptable spending is $3$, which does not meet the condition. Thus, only the first three combinations satisfy the conditions.\n\n---\n\n### Constraints and Hints\n\n- For $25\\%$ of the test cases, $n \\leq 100$.\n- For $40\\%$ of the test cases, $n \\leq 1,000$.\n- For $80\\%$ of the test cases, $n \\leq 200,000$, with $0 < k \\leq 50$.\n\n\n- For $100\\%$ of the test cases, $2 \\leq n \\leq 2 \\times 10^6$, $0 < k \\leq 10^4$, $0 \\leq p \\leq 100$, $0 \\leq$ coffee shop minimum spending requirement $\\leq 100$.\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2723, "prompt": "### Problem Description\n\nJiulian is a girl who loves creating problems.\n\nAfter this year\u2019s World Final ended, Jiulian became particularly fond of computational geometry. She decided to create a computational geometry problem for the NOI exam \u2014 a problem with only the name and its association with computational geometry.\n\nFirstly, Jiulian provides a rooted tree $T$ with $n\\ (n \\geq 2)$ nodes, where the root node is labeled as $1$. A leaf node is defined as any node (excluding the root) with a degree of exactly $1$. The figure below shows an example tree $T$, where the set of leaf nodes is $\\{3, 4, 5\\}$.\n\n![polygon1.png](https://img.loj.ac.cn/2019/07/01/5d19932673391.png)\n\nNext, Jiulian constructs a sequence $A$ using this tree:\n- Starting from the root node, perform a depth-first traversal of the entire tree in such a way that children nodes are accessed in ascending order of their labels. This yields the DFS sequence for tree $T$.\n- Then, arrange all the leaf nodes according to their appearance order in the DFS sequence, yielding sequence $A$.\n\nFurthermore, based on sequence $A$, Jiulian defines the distance $d(u, v)$ between two leaf nodes $u$ and $v$: Suppose $u$ is the $i$-th element and $v$ is the $j$-th element in $A$, then $d(u, v) = \\min(|i \u2212 j|, |A| \u2212 |i \u2212 j|)$, where $|A|$ is the length of sequence $A$, i.e., the number of leaf nodes in tree $T$, and $i, j$ represent appearance positions starting from $1$.\n\nIn the example above, sequence $A$ is $\\{4, 5, 3\\}$. Distances between leaf nodes are $d(3, 5) = d(3, 4) = d(4, 5) = 1$, where the positions of $3, 4, 5$ are $3, 1, 2$, respectively.\n\nFinally, Jiulian provides a parameter $K$. Using tree $T$ and sequence $A$, we can construct an **undirected graph $G$ without duplicate edges and self-loops**, consisting of $n$ nodes. For any two different nodes $u, v$, an edge exists between them if at least one of the following conditions is satisfied:\n- There is an edge connecting $u$ and $v$ in tree $T$.\n- Both $u, v$ are leaf nodes and $d(u, v) \\leq K$.\n\nFor $K = 1$ or $2$, the graph $G$ constructed from the example above looks as follows:\n\n![polygon2.png](https://img.loj.ac.cn/2019/07/01/5d19933b911fe.png)\n\nNow, Jiulian wants you to calculate how many different Hamiltonian cycles exist in $G$. The answer may be very large, so please output the result modulo $998244353$.\n\nAdditional definitions:\n- A Hamiltonian cycle $H$ in an undirected graph $G$ without duplicate edges and self-loops is a subset of its edges such that:\n - Every node has exactly two distinct adjacent edges in $H$.\n - Any two nodes can be directly or indirectly connected by edges in $H$.\n- Two Hamiltonian cycles $H_1, H_2$ in an undirected graph $G$ are considered different if there exists an edge $e$ such that $e$ is in $H_1$ but not in $H_2$.\n\n---\n\n### Input Format\nRead from the file `polygon.in`.\n\nThe first line contains two integers $n$ and $K$, representing the number of nodes in the tree $T$ and the parameter $K$ provided by Jiulian.\n\nThe second line contains $n \u2212 1$ integers $f_i\\ (1 \\leq f_i \\leq i)$, where $f_i$ denotes an edge $(f_i, i + 1)$ in tree $T$.\n\n---\n\n### Output Format\nWrite to the file `polygon.out`.\n\nOutput a single integer, representing the number of Hamiltonian cycles modulo $998244353$.\n\n---\n\n### Example\nThis example corresponds exactly to the example from the problem statement. The two Hamiltonian cycles traverse the nodes in the following orders: $(1, 2, 4, 5, 3)$ and $(1, 2, 5, 4, 3)$.\n\n---\n\n### Constraints and Hints\nThe scale and characteristics of the test cases are listed below:\n\n| ID | $n$ | $K$ | Special Properties | ID | $n$ | $K$ | Special Properties |\n| :--: | :---------: | :-----: | :----------------: | :--: | :---------: | :-----: | :----------------: |\n| $1$ | $\\leq 5$ | $\\leq 3$| None | $11$ | $\\leq 1000$ | $\\leq 2$| A |\n| $2$ | $\\leq 10$ | $\\leq 3$| None | $12$ | $\\leq 1000$ | $\\leq 2$| A |\n| $3$ | $\\leq 15$ | $\\leq 3$| None | $13$ | $\\leq 1000$ | $\\leq 2$| A |\n| $4$ | $\\leq 20$ | $\\leq 3$| None | $14$ | $\\leq 1000$ | $\\leq 2$| None |\n| $5$ | $\\leq 1000$ | $=1$ | A | $15$ | $\\leq 1000$ | $\\leq 2$| None |\n| $6$ | $\\leq 1000$ | $=1$ | A | $16$ | $\\leq 1000$ | $\\leq 2$| None |\n| $7$ | $\\leq 1000$ | $=1$ | A | $17$ | $\\leq 1000$ | $\\leq 3$| A |\n| $8$ | $\\leq 1000$ | $=1$ | None | $18$ | $\\leq 1000$ | $\\leq 3$| A |\n| $9$ | $\\leq 1000$ | $=1$ | None | $19$ | $\\leq 1000$ | $\\leq 3$| None |\n| $10$ | $\\leq 1000$ | $=1$ | None | $20$ | $\\leq 1000$ | $\\leq 3$| None |\n\nProperty A guarantees that every node in the tree has at most two children.\n\nFor all test cases, it is guaranteed that $1 \\leq f_i \\leq i, 2 \\leq n \\leq 1000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2672, "prompt": "### Problem Description\n\nLittle Q, who is about to enter the second grade, bought a new type of educational toy \u2014 a Magic Chessboard. It is an $N \\times M$ grid chessboard, where each cell contains a positive integer. The chessboard guardian resides in the cell located at the $X$th row and $Y$th column (both rows and columns are 1-based indexed) and will never move. The chessboard guardian can perform two types of operations:\n\n- (a) **Query**: The guardian randomly extends outwards from their current position to form a rectangular area of arbitrary size and asks you for the greatest common divisor (GCD) of all numbers within this rectangular region.\n- (b) **Modify**: The guardian chooses any rectangular region on the chessboard and increments all the numbers within this region by a given integer.\n\nThe instruction manual for the game includes the statement: \"Smart kids, if you answer 19,930,324 consecutive queries correctly, you'll receive a surprise!\" Little Q is eager to get that surprise but often makes mistakes due to carelessness, making it difficult to achieve this goal. Thus, Little Q is asking for your help to write a program that can answer the guardian's queries with $100\\%$ accuracy.\n\nTo simplify the problem, your program only needs to handle $T$ operations from the chessboard guardian. It is guaranteed that at any time, all numbers on the chessboard will be positive integers not exceeding $2^{62} - 1$.\n\n---\n\n### Input Format\n\nThe input consists of the following information:\n\n1. The first line contains two positive integers $N$ and $M$, representing the dimensions of the chessboard.\n2. The second line contains two positive integers $X$ and $Y$, indicating the chessboard guardian's position.\n3. The third line contains a single positive integer $T$, representing the number of operations performed by the chessboard guardian.\n4. The next $N$ lines each contain $M$ positive integers, representing the initial numbers on the chessboard.\n5. The next $T$ lines describe the $T$ operations in chronological order. Each line starts with a number $0$ or $1$:\n - If the line begins with $0$, it represents a **query** operation. Four non-negative integers $x_1, y_1, x_2, y_2$ follow, describing the queried rectangular region. The region is defined relative to the guardian's position as follows:\n - Extend upwards by $x_1$ rows.\n - Extend downwards by $x_2$ rows.\n - Extend leftwards by $y_1$ columns.\n - Extend rightwards by $y_2$ columns.\n - If the line begins with $1$, it represents a **modify** operation. Four positive integers $x_1, y_1, x_2, y_2$ and an integer $c$ follow, where:\n - $x_1$ and $x_2$ are the upper and lower row boundaries of the rectangular region.\n - $y_1$ and $y_2$ are the left and right column boundaries of the rectangular region.\n - Add $c$ to all numbers within this rectangular region. Note that $c$ can be negative.\n\n---\n\n### Output Format\n\nFor each **query** operation, output a single number on a separate line, which represents the GCD of all numbers within the queried region.\n\n---\n\n### Example\n\n| Initial State | After First Operation | After Second Operation | After Third Operation | After Fourth Operation |\n|:---------------------:|:---------------------:|:-----------------------:|:---------------------:|:-----------------------:|\n| 6 12
18 24 | **6** 12
**18** 24 | **12** **18**
18 24 | 12 18
**24** **30** | **12** **18**
**24** **30** |\n\nFor the first and fourth operations (query operations), the bolded region indicates the queried area.\n\nFor the second and third operations (modify operations), the bolded region indicates the modified area.\n\n---\n\n### Constraints and Hints\n\n1. The test data is categorized into three groups: A, B, and C:\n - Group A comprises $20\\%$ of the data and satisfies $N \\leq 100$, $M \\leq 100$, $T \\leq 20,000$.\n - Group B comprises $40\\%$ of the data and satisfies $N = 1$, $M \\leq 500,000$, $T \\leq 100,000$.\n - Group C comprises $40\\%$ of the data and satisfies $N \\times M \\leq 500,000$, $T \\leq 100,000$.\n2. For each group, $50\\%$ of the test cases involve modification operations that affect only a single cell (i.e., $x_1 = x_2$ and $y_1 = y_2$).\n3. The input data is guaranteed to satisfy all the conditions described in the problem statement.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2720, "prompt": "### Problem Description\n\nThe highly skilled individual, A, has been appointed as the problem setter for ION2018 and now faces the challenge of naming the problems.\n\nA has been chosen as the problem setter for ION2018 and has carefully crafted a top-quality problem. However, all aspects of the problem have been finalized except for its name.\n\nBecause ION has been held for many years, the naming of the problems follows specific rules. According to the ION problem-setting manual, every year the problem-setting committee specifies a lowercase alphabetical string, referred to as that year's \"naming string.\" **The name of each problem must be a non-empty contiguous substring of that year's naming string and must not coincide with any of the names of the problems from the previous year.**\n\nDue to certain special circumstances, A does not know any of the names of the ION2017 problems. However, through some special means, A has obtained the naming string of ION2017. A now has $Q$ queries, where each query specifies the naming string for ION2017 and ION2018. Your task is to determine how many valid problem names can be created, such that these names satisfy the rules set by the problem-setting committee: being a non-empty contiguous substring of the ION2018 naming string and not coinciding with any problem name from ION2017.\n\nDue to specific constraints, all given ION2017 naming strings in the queries must be contiguous substrings of a string $S$, as detailed in the input format below.\n\n---\n\n### Input Format\n\nRead input from the file `name.in`.\n\n- The first line contains a string $S$. All ION2017 naming strings provided in the queries are contiguous substrings of $S$.\n- The second line contains an integer $Q$, representing the number of queries.\n- The next $Q$ lines each contain a string $T$ and two integers $l, r$. This indicates a query asking for the number of valid problem names if the ION2017 naming string is $S[l..r]$ and the ION2018 naming string is $T$.\n\nThe strings in the input consist only of lowercase alphabetical characters.\n\n---\n\n### Output Format\n\nPrint the output to the file `name.out`.\n\nOutput $Q$ lines. The $i^{th}$ line contains a non-negative integer representing the answer to the $i^{th}$ query.\n\n---\n\n### Sample\n\nSee the provided files `name2.in` and `name2.ans` for examples.\n\n---\n\n### Constraints and Hints\n\n\n\n| Test Case | $\\lvert S \\rvert \\leq$ | $Q \\leq$ | $\\sum \\lvert T \\rvert \\leq$ | Query Constraint | Other Constraints |\n|:-:|:-:|:-:|:-:|:-:|:-:|\n| 1 | $200$ | $200$ | $40000$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | $\\lvert T \\rvert \\leq 200$ |\n| 2 | $1000$ | $200$ | $40000$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | $\\lvert T \\rvert \\leq 200$ |\n| 3 | $1000$ | $200$ | $40000$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | $\\lvert T \\rvert \\leq 200$ |\n| 4 | $1000$ | $200$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 5 | $1000$ | $200$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 6 | $5 \\times 10^5$ | $1$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 7 | $5 \\times 10^5$ | $1$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 8 | $10^5$ | $10^5$ | $2 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 9 | $10^5$ | $10^5$ | $2 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 10 | $2 \\times 10^5$ | $10^5$ | $4 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 11 | $2 \\times 10^5$ | $10^5$ | $4 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 12 | $3 \\times 10^5$ | $10^5$ | $6 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 13 | $3 \\times 10^5$ | $10^5$ | $6 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 14 | $4 \\times 10^5$ | $10^5$ | $8 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 15 | $4 \\times 10^5$ | $10^5$ | $8 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 16 | $5 \\times 10^5$ | $10^5$ | $10^6$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 17 | $5 \\times 10^5$ | $10^5$ | $10^6$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 18 | $2 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 19 | $3 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 20 | $4 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 21 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 22 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 23 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 24 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 25 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2130, "prompt": "### Problem Description\n\nLinux and OSX users are likely familiar with package managers. With a package manager, you can install a software package using a single command. The package manager will then help you download the package from a repository, automatically resolve all dependencies (i.e., download and install any other packages required for the installation of the desired package), and complete the configuration. Popular package managers include `apt-get` for Debian/Ubuntu, `yum` for Fedora/CentOS, and `Homebrew` for OSX.\n\nYou decide to design your own package manager. Inevitably, you will need to deal with package dependencies. If package $A$ depends on package $B$, installing package $A$ requires package $B$ to be installed first. Similarly, uninstalling package $B$ requires package $A$ to be uninstalled as well. Now, you have been given all dependency relationships between packages. Furthermore, due to your prior work, every package in your package manager (except for package $0$) depends on exactly one other package, and package $0$ does not depend on any package. The dependency relationships do not contain any cycles (i.e., if there are $m \\ (m \\geq 2)$ packages $A_1, A_2, A_3, \\ldots, A_m$ such that $A_1$ depends on $A_2$, $A_2$ depends on $A_3$, $A_3$ depends on $A_4$, ..., $A_{m\u22121}$ depends on $A_m$, and $A_m$ depends on $A_1$, this forms a dependency cycle). Additionally, no package depends on itself.\n\nNow, you need to write a dependency resolution program for your package manager. Based on user feedback, users want to quickly know how many packages' installation statuses will change when installing or uninstalling a given package (i.e., for an install operation, how many packages will go from uninstalled to installed; and for an uninstall operation, how many packages will go from installed to uninstalled). Your task is to implement this feature. Note that if a user attempts to install an already installed package or uninstall an already uninstalled package, no package's installation status will change, i.e., the number of packages whose installation status changes in this case is $0$.\n\n### Input Format\n\nThe first line of the input contains a single positive integer $n$, representing the total number of packages. Packages are numbered from $0$. \nThe second line contains $n\u22121$ integers separated by single spaces, where the $i^{th}$ integer represents the package on which package $i+1$ depends (for $i \\in \\{1, 2, ..., n-1\\}$). \nThe third line contains a single positive integer $q$, representing the total number of queries. \nThe following $q$ lines each contain a single query, which can be one of two types: \n``install x``: Indicates installing package $x$. \n``uninstall x``: Indicates uninstalling package $x$. \n\nYou need to maintain the installation status of each package. All packages are initially uninstalled. For each query, you must output the number of packages whose installation status changes as a result of the operation, and then apply the operation (i.e., update the maintained installation status accordingly).\n\n### Output Format\n\nThe output consists of $q$ lines. \nThe $i^{th}$ line contains a single integer, representing the number of packages whose installation status changes as a result of the $i^{th}$ query.\n\n### Example\n\nInitially, all packages are uninstalled.\n\n- Installing package $5$ requires installing packages $0, 1, 5$, for a total of $3$ packages. \n- Installing package $6$ afterward only requires installing package $6$. At this point, packages $0, 1, 5, 6$ are installed. \n- Uninstalling package $1$ requires uninstalling packages $1, 5, 6$, for a total of $3$ packages. Now, only package $0$ remains installed. \n- Installing package $4$ requires installing packages $1, 4$, for a total of $2$. At this point, packages $0, 1, 4$ are installed. \n- Finally, uninstalling package $0$ uninstalls all packages.\n\n#### Input\n```\n7\n0 0 1 1 0 1\n5\ninstall 5\ninstall 6\nuninstall 1\ninstall 4\nuninstall 0\n```\n\n#### Output\n```\n3\n1\n3\n2\n3\n```\n\n### Constraints and Notes\n\nFor all inputs, $n \\leq 100000, \\ q \\leq 100000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2601, "prompt": "### Problem Description\nThe picturesque small town of Y City has $n$ beautiful scenic spots. As tourists flock to the area in ever-increasing numbers, Y City has arranged a sightseeing bus to provide more convenient transportation services for visitors.\n\nThe sightseeing bus appears at scenic spot $1$ at minute $0$, and subsequently visits scenic spots $2, 3, \\dots, n$ in sequence. It takes $D_i$ minutes to travel from scenic spot $i$ to scenic spot $i+1$. At any given time, the bus can only move forward or wait at the current spot.\n\nThere are $m$ tourists, each of whom needs to travel exactly once from one scenic spot to another. The $i^{th}$ tourist arrives at scenic spot $A_i$ at minute $T_i$ and wants to travel to scenic spot $B_i$ $(A_i < B_i)$. To ensure all passengers reach their destination, the bus must wait at each stop until all passengers departing from that spot have boarded before heading to the next spot. Assume that boarding and alighting take no time.\n\nA passenger's travel time is defined as the time they reach their destination minus the time they arrived at the departure spot. Since there is only one sightseeing bus, it may need to stop and wait for other passengers, causing complaints about long travel times. To address this issue, the driver ZZ has installed $k$ nitrous accelerators on the bus. Each accelerator can reduce one specific $D_i$ by $1$ minute. The same accelerator can be applied multiple times to the same $D_i$, but the condition $D_i \\geq 0$ must be satisfied after usage.\n\nZZ needs to decide how to use these accelerators to minimize the total travel time of all passengers.\n\n### Input Format\nThe first line contains three integers $n$, $m$, and $k$, separated by spaces. These integers represent the number of scenic spots, the number of passengers, and the number of nitrous accelerators, respectively.\n\nThe second line contains $n-1$ integers separated by spaces, where the $i^{th}$ integer represents the time required to travel from scenic spot $i$ to scenic spot $i+1$, denoted by $D_i$.\n\nThe next $m$ lines (from the 3rd line to the $(m+2)^{th}$ line) each contain three integers $T_i$, $A_i$, and $B_i$, separated by spaces. The $(i+2)^{th}$ line represents the $i^{th}$ passenger's arrival time at the departure scenic spot, the departure scenic spot number, and the destination scenic spot number.\n\n### Output Format\nPrint a single integer representing the minimum possible total travel time.\n\n### Example\nUsing two accelerators on $D_2$, the travel time from scenic spot $2$ to scenic spot $3$ becomes $2$ minutes.\n\nThe bus departs scenic spot $1$ at minute $1$, arrives at scenic spot $2$ at minute $2$, departs scenic spot $2$ at minute $5$, and arrives at scenic spot $3$ at minute $7$.\n\n- The travel time for passenger $1$ is $7 - 0 = 7$ minutes.\n- The travel time for passenger $2$ is $2 - 1 = 1$ minute.\n- The travel time for passenger $3$ is $7 - 5 = 2$ minutes.\n\nTotal travel time: $7 + 1 + 2 = 10$ minutes.\n\n### Constraints & Hints\n- For $8\\%$ of the data, $k=0$.\n- For $16\\%$ of the data, $k=1$.\n- For $32\\%$ of the data, $2 \\leq n \\leq 50$, $m \\leq 1000$, $k \\leq 20$, $D_i \\leq 10$, $T_i \\leq 500$.\n- For $48\\%$ of the data, $n \\leq 100$, $m \\leq 1000$, $k \\leq 100$, $T_i \\leq 10^4$.\n- For $80\\%$ of the data, $n \\leq 1000$, $m \\leq 10^4$, $k \\leq 10^5$, $D_i \\leq 100$, $T_i \\leq 10^5$.\n- **For $100\\%$ of the data,** $1 \\leq n, m \\leq 10^5$, $0 \\leq k \\leq 5 \\times 10^6$, $0 \\leq D_i \\leq 1000$, $0 \\leq T_i \\leq 10^6$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3386, "prompt": "### Problem Description\nFor a city, the drainage system is an extremely important component.\n\nOne day, Little C obtained the design blueprint of a city's drainage system. The drainage system consists of $n$ drainage nodes (numbered from $1 \\sim n$) and several one-way drainage pipes. Each drainage node has several pipes to collect wastewater from other drainage nodes (referred to as the node's collection pipes) and several other pipes to discharge wastewater to other drainage nodes (known as the node's discharge pipes).\n\nAmong the drainage nodes, $m$ nodes are designated as wastewater inlets, numbered as $1, 2, \\ldots, m$, and wastewater can only flow into the drainage system through these inlets. These nodes do not have collection pipes. Additionally, the drainage system has several final outlets that transport wastewater to treatment plants; these nodes are considered final outlets if they have no discharge pipes.\n\nCurrently, each wastewater inlet receives $1$ tonne of wastewater. When wastewater flows into a node, it is evenly distributed among all the discharge pipes of the node and flows to other drainage nodes, while final outlets discharge wastewater out of the system.\n\nLittle C wants to determine how much wastewater each final outlet discharges in the city's drainage system. The city's drainage system is scientifically designed, and the pipes do not form loops\u2014i.e., wastewater will not form circular flows.\n\n### Input Format\nThe first line contains two integers $n$ and $m$ separated by a single space, representing the number of drainage nodes and the number of wastewater inlets, respectively. \nThe following $n$ lines describe the discharge pipes for each node. The $i$-th line starts with an integer $d_i$, representing the number of discharge pipes for node $i$. The next $d_i$ integers $a_1, a_2, \\ldots, a_{d_i}$ indicate the destination drainage nodes of these pipes, separated by single spaces. \nIt is guaranteed that no two pipes will have the same starting and destination nodes.\n\n### Output Format\nOutput several lines, in ascending order of node numbers, showing the volume of wastewater discharged by each final outlet. The volume must be expressed in fractional form. Each line should output two integers $p$ and $q$ separated by a single space, indicating that the discharged volume is $\\frac{p}{q}$. It is required that $p$ and $q$ are coprime, and $q = 1$ should also be included in the output.\n\n**Explanation for Sample #1**\n\nNode $1$ is a wastewater inlet, and nodes $4$ and $5$ are final outlets because they have no discharge pipes. \nWhen $1$ tonne of wastewater flows into node $1$, it is evenly distributed to nodes $2, 3, 5$ via discharge pipes, each receiving $\\frac{1}{3}$ tonne of wastewater. \nWhen node $2$ receives $\\frac{1}{3}$ tonne of wastewater, it is evenly distributed to nodes $4$ and $5$, each receiving $\\frac{1}{6}$ tonne of wastewater. \nWhen node $3$ receives $\\frac{1}{3}$ tonne of wastewater, it is evenly distributed to nodes $4$ and $5$, each receiving $\\frac{1}{6}$ tonne of wastewater. \nFinally, node $4$ discharges $\\frac{1}{6} + \\frac{1}{6} = \\frac{1}{3}$ tonne of wastewater, and node $5$ discharges $\\frac{1}{3} + \\frac{1}{6} + \\frac{1}{6} = \\frac{2}{3}$ tonne of wastewater.\n\n**Sample Input**\n\n```\n5 1\n3 2 3 5\n2 4 5\n2 4 5\n0\n0\n```\n\n**Sample Output**\n\n```\n1 3\n2 3\n```\n\n### Data Constraints\n\n| Test Case Number | $n \\le$ | $m \\le$ |\n|:-:|:-:|:-:|\n| $1 \\sim 3$ | $10$ | $1$ |\n| $4 \\sim 6$ | ${10}^3$ | $1$ |\n| $7 \\sim 8$ | ${10}^5$ | $1$ |\n| $9 \\sim 10$ | ${10}^5$ | $10$ |\n\nFor all test cases, it is guaranteed that $1 \\le n \\le {10}^5$, $1 \\le m \\le 10$, $0 \\le d_i \\le 5$. \n\nThe data also guarantees that when wastewater flows from a wastewater inlet to a final outlet, it will pass through no more than $10$ intermediate drainage nodes (not counting the inlet and the final outlet). \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2297, "prompt": "### Problem Description\n\nThe island of Crete is known for its tribe of wild men. There are $m$ caves on the island, arranged in a circular formation. These caves are numbered clockwise as $1, 2, \\dots, m$. There are $n$ wild men living on the island, and initially, they reside in caves $C_1, C_2, \\dots, C_n$, respectively. Each year, the $i$-th wild man moves forward $P_i$ caves clockwise and settles in that cave.\n\nEach wild man $i$ has a lifespan $L_i$, which represents the number of years they will survive.\n\nThe following four diagrams illustrate the first four years on an island with $6$ caves and $3$ wild men. The initial cave numbers for the wild men are $1, 2, 3$, respectively. The number of caves they move forward each year is $3, 7, 2$, respectively, and their lifespans are $4, 3, 1$.\n\n![](https://img.loj.ac.cn/2022/06/09/2cf510b3762ac.png)\n\nInterestingly, despite having many wild men, no two wild men ever reside in the same cave during their lifetimes. This keeps the island perpetually peaceful, which amazes scientists. They want to determine the minimum number of caves required to maintain peace on the island.\n\n---\n\n### Input Format\n\nThe first line contains an integer $n$, the number of wild men.\n\nThe next $n$ lines each contain three integers, $C_i, P_i, L_i$, indicating the initial cave number, the number of caves the wild man moves forward each year, and their lifespan, respectively.\n\n---\n\n### Output Format\n\nOutput a single integer $M$, the minimum number of caves required. The input guarantees a solution exists, and $M$ will not exceed $10^6$.\n\n---\n\n### Example\n\n**Input:**\n```\n3\n1 3 4\n2 7 3\n3 2 1\n```\n\n**Output:**\n```\n6\n```\n\n---\n\n### Constraints and Hints\n\n- For $100\\%$ of the test cases:\n - $1 \\leq n \\leq 15$.\n - $1 \\leq C_i, P_i \\leq 100$.\n - $0 \\leq L_i \\leq 10^6$.\n - The solution satisfies $M \\leq 10^6$.\n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3342, "prompt": "### Problem Description\nThe chef plans to prepare $m$ dishes for children, with each dish requiring $k$ grams of ingredients. To achieve this, the chef has purchased $n$ types of ingredients, numbered from $1$ to $n$. The weight of the $i$-th ingredient is $d_i$ grams. The **total weight of the $n$ ingredients is exactly $m \\times k$ grams**, and both $d_i$ and $k$ are **positive integers**.\n\nWhen preparing dishes, each ingredient can be used in multiple dishes. However, to preserve the purity of the flavor, the chef wants each dish to use **at most 2 types of ingredients**. Your task is to determine whether there exists a preparation plan that satisfies the following conditions:\n- Exactly $m$ dishes are prepared.\n- Each dish uses at most $2$ types of ingredients.\n- Each dish uses exactly $k$ grams of ingredients.\n- The weight of each ingredient used in a dish is a positive integer.\n- All $n$ types of ingredients are used up exactly.\n\nIf such a preparation plan exists, you should also provide one valid preparation plan.\n\n### Input Format\n**This problem contains multiple test cases in a single input file.**\n\nThe first line contains an integer $T$, the number of test cases. For each test case:\n- The first line contains three positive integers $n$, $m$, and $k$, representing the number of ingredient types, the number of dishes to prepare, and the weight of ingredients required for each dish, respectively.\n- The second line contains $n$ integers, where the $i$-th integer represents the weight $d_i$ of the $i$-th ingredient.\n\n### Output Format\nFor each test case:\n- **If no valid preparation plan exists, output a single line containing the integer $-1$.**\n- Otherwise, output $m$ lines, each describing how one dish is prepared. Depending on the number of ingredient types used in the dish, the format should be one of the following:\n - Output a single line with two integers $i$ and $x$, meaning the dish is prepared using $x$ grams of the $i$-th ingredient. You must ensure $1 \\leq i \\leq n$, and $x = k$.\n - Output a single line with four integers $i$, $x$, $j$, and $y$, meaning the dish is prepared using $x$ grams of the $i$-th ingredient and $y$ grams of the $j$-th ingredient. You must ensure $1 \\leq i, j \\leq n$, $i \\neq j$, $x + y = k$, and $x, y > 0$.\n\nThis problem uses a **custom checker** to validate your solution. Therefore, if there are multiple valid solutions, you only need to output **any one** of them.\n\nEnsure that the output format is correct and that numbers in the same line are separated by a single space. Apart from this, your output should **not contain any extra characters**.\n\n#### Sample Explanation 1\n\nFor the second test case, one valid preparation plan is as follows:\n- Use $80$ grams of ingredient $1$ and $20$ grams of ingredient $2$ to make the first dish.\n- Use $10$ grams of ingredient $2$ and $90$ grams of ingredient $3$ to make the second dish.\n- Use $100$ grams of ingredient $4$ to make the third dish.\n\n#### Sample 2\n\nRefer to the files `dish/dish2.in` and `dish/dish2.ans` in the participant's directory.\n\n#### Sample 3\n\nRefer to the files `dish/dish3.in` and `dish/dish3.ans` in the participant's directory.\n\n---\n\n### Constraints\nFor all test cases:\n$1 \\leq T \\leq 10$, $1 \\leq n \\leq 500$, $n - 2 \\leq m \\leq 5000$, $m \\geq 1$, $1 \\leq k \\leq 5000$, $\\sum_{i=1}^{n}d_i = m \\times k$.\n\nThe specific constraints for each test case are given in the table below:\n\n| Test Case Index | $n$ | $m$ | $k$ |\n| :-: | :-: | :-: | :-: |\n| $1\\sim 3$ | $\\le 4$ | $\\le 4$ | $\\le 50$ |\n| $4\\sim 5$ | $\\le 10$ | $\\le 10$ | $\\le 5\\times 10^3$ |\n| $6\\sim 7$ | $\\le 500$ | $=n-1$ | $\\le 5\\times 10^3$ |\n| $8\\sim 9$ | $\\le 500$ | $n-1\\le m\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n| $10$ | $\\le 25$ | $\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n| $11\\sim 12$ | $\\le 25$ | $\\le 5\\times 10^3$ | $\\le 500$ |\n| $13\\sim 14$ | $\\le 50$ | $\\le 5\\times 10^3$ | $\\le 500$ |\n| $15\\sim 17$ | $\\le 100$ | $\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n| $18\\sim 20$ | $\\le 500$ | $\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2132, "prompt": "### Problem Description\n\n> \"The one who chases shadows becomes the shadow.\" \u2014 Homer\n\nAllison has recently developed an interest in literature. She enjoys sipping a cup of cappuccino on a lazy afternoon while indulging in her cherished copy of the *Homeric Epics*. A monumental work composed of *The Odyssey* and *The Iliad*, the Homeric Epics are too lengthy for her liking. Thus, Allison seeks to shorten it by employing an encoding technique. \n\nThe Homeric Epics contain $n$ distinct words, numbered from $1$ to $n$. The $i$th word appears $w_i$ times in total. Allison wants to replace the $i$th word with a $k$-ary string $s_i$ such that the following condition is satisfied: \nFor any $1 \\leq i, j \\leq n$, where $i \\neq j$, $s_i$ is not a prefix of $s_j$. \n\nNow Allison wishes to determine how to choose the $s_i$ values in order to minimize the total length of the encoded Homeric Epics. Furthermore, under the condition of minimizing the total length, she also wants to know the shortest possible length of the longest string $s_i$. \n\nSome definitions: \n\n- A string is called a **$k$-ary string** if and only if each character in the string is an integer between $0$ and $k-1$ (inclusive). \n- A string $\\text{Str}_1$ is called the **prefix** of a string $\\text{Str}_2$ if and only if there exists $1 \\leq t \\leq m$ such that $\\text{Str}_1 = \\text{Str}_2[1 \\ldots t]$, where $m$ is the length of $\\text{Str}_2$, and $\\text{Str}_2[1 \\ldots t]$ represents the substring composed of the first $t$ characters of $\\text{Str}_2$. \n\n---\n\n### Input Format\nThe input file consists of multiple lines: \n\n- The first line contains two positive integers, $n$ and $k$, separated by a single space, indicating that there are $n$ distinct words to be replaced using $k$-ary strings. \n- The next $n$ lines each contain a single non-negative integer $w_i$, representing the frequency of occurrence of the $i$th word. \n\n---\n\n### Output Format\nThe output file consists of two lines: \n\n- The first line outputs an integer, representing the minimum length of the encoded Homeric Epics after the replacement. \n- The second line outputs an integer, representing the shortest possible length of the longest $s_i$ string under the condition of achieving the minimum total length. \n\n---\n\n### Example 1\nLet $X_{(k)}$ denote that $X$ is a string in $k$-ary notation. \n\nOne optimal solution is: \n- Replace the first word with $00_{(2)}$, \n- Replace the second word with $01_{(2)}$, \n- Replace the third word with $10_{(2)}$, \n- Replace the fourth word with $11_{(2)}$. \n\nIn this solution, the encoded length is: \n$1 \\times 2 + 1 \\times 2 + 2 \\times 2 + 2 \\times 2 = 12$, \nand the length of the longest $s_i$ is $2$. \n\nA non-optimal solution is: \n- Replace the first word with $000_{(2)}$, \n- Replace the second word with $001_{(2)}$, \n- Replace the third word with $01_{(2)}$, \n- Replace the fourth word with $1_{(2)}$. \n\nIn this case, the encoded length is: \n$1 \\times 3 + 1 \\times 3 + 2 \\times 2 + 2 \\times 1 = 12$, \nbut the length of the longest $s_i$ is $3$. Compared to the optimal solution, the total length is the same, but the length of the longest string is higher. \n\n---\n\n### Example 2\nAn optimal solution is: \n- Replace the first word with $000_{(3)}$, \n- Replace the second word with $001_{(3)}$, \n- Replace the third word with $01_{(3)}$, \n- Replace the fourth word with $02_{(3)}$, \n- Replace the fifth word with $1_{(3)}$, \n- Replace the sixth word with $2_{(3)}$. \n\n---\n\n### Constraints and Hints\n\n#### Limits and Constraints\n\n| Case # | Scale of $n$ | Scale of $k$ | Additional Constraints |\n|:-:|:-:|:-:|:-:|\n| 1 | $n = 3$ | $k = 2$ | - |\n| 2 | $n = 5$ | $k = 2$ | - |\n| 3 | $n = 16$ | $k = 2$ | All $w_i$ are equal |\n| 4 | $n = 1000$ | $k = 2$ | $w_i$ are uniformly random |\n| 5 | $n = 1000$ | $k = 2$ | - |\n| 6 | $n = 100000$ | $k = 2$ | - |\n| 7 | $n = 100000$ | $k = 2$ | All $w_i$ are equal |\n| 8 | $n = 100000$ | $k = 2$ | - |\n| 9 | $n = 7$ | $k = 3$ | - |\n| 10 | $n = 16$ | $k = 3$ | All $w_i$ are equal |\n| 11 | $n = 1001$ | $k = 3$ | All $w_i$ are equal |\n| 12 | $n = 99999$ | $k = 4$ | All $w_i$ are equal |\n| 13 | $n = 100000$ | $k = 4$ | - |\n| 14 | $n = 100000$ | $k = 4$ | - |\n| 15 | $n = 1000$ | $k = 5$ | - |\n| 16 | $n = 100000$ | $k = 7$ | $w_i$ are uniformly random |\n| 17 | $n = 100000$ | $k = 7$ | - |\n| 18 | $n = 100000$ | $k = 8$ | $w_i$ are uniformly random |\n| 19 | $n = 100000$ | $k = 9$ | - |\n| 20 | $n = 100000$ | $k = 9$ | - |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2668, "prompt": "### Problem Description\nStudent Xiao E is very fond of calligraphy. Upon hearing that NOI2013 has started, he wants to create a calligraphy piece that spells \"NOI\" and present it to everyone.\n\nXiao E has a magical sheet of paper that can be represented by an $n$-row by $m$-column 2D grid matrix. For convenience, we define the coordinate of the bottom-left grid cell in the matrix as $(1,1)$ and the coordinate of the top-right grid cell as $(m, n)$.\n\nEach grid cell in the matrix has an integer value called \"luck value\". Writing on the grid cells increases everyone's luck. The degree of luck enhancement is precisely the sum of the luck values of all the cells covered by writing. Now, you need to write the letters `N`, `O`, `I` on the paper.\n\nHere are the definitions of the three calligraphy letters:\n\n* `N` consists of multiple (at least 3) rectangles whose sides are parallel to the coordinate axes. Suppose it is composed of $K$ rectangles (indexed as $1 \\ldots K$); the bottom-left coordinate of the $i^{th}$ rectangle is $(L_i, B_i)$, and the top-right coordinate is $(R_i, T_i)$. The rectangles must satisfy:\n1. $L_i \\leq R_i$, $B_i \\leq T_i$;\n2. For any $1 < i \\leq K$, $L_i = R_{i\u22121} + 1$;\n3. For any $3 \\le i < K$, $B_{i\u22121} \u2212 1 \\le T_i \\le T_{i\u22121}$, $B_i \\le B_{i\u22121}$;\n4. $B_2 > B_1$, $T_2 = T_1$, $B_{K\u22121} = B_K$, $T_{K\u22121} < T_K$;\n\n* `O` is created by cutting out a smaller rectangle $B$ from a larger rectangle $A`. Both rectangles have sides parallel to the coordinate axes. Assume that the bottom-left coordinate of the larger rectangle $A$ is $(u, v)$, with a length of $W$ and a width of $H$. Rectangle $B` satisfies the following conditions: the bottom-left coordinate is $(u+1, v+1)$, with a length of $W \u2212 2` and a width of $H \u2212 2`. The conditions to satisfy are:\n1. $W \\geq 3$, $H \\geq 3$;\n2. $u > R_K + 1`;\n\n* `I` consists of three solid rectangles whose sides are parallel to the coordinate axes, stacked from bottom to top and numbered $1, 2, 3` (from bottom to top). The bottom-left coordinate of the $i^{th}$ rectangle is $(P_i, Q_i)`, and its top-right coordinate is $(G_i, H_i)`. The conditions to satisfy are:\n1. $P_i \\leq G_i$, $Q_i \\leq H_i`;\n2. $P_1 = P_3 > u + W`, $G_1 = G_3`;\n3. $Q_1 = H_1 = Q_2 \u2212 1, H_2 + 1 = Q_3 = H_3`;\n4. $P_1 < P_2 \\leq G_2 < G_1`;\n\nBelow is an example of the letters `N`, `O`, and `I`.\n![](https://i.loli.net/2018/06/10/5b1cf2cd05775.png)\n\nAdditionally, all drawn shapes must not exceed the edges of the sheet of paper. Now, Xiao E wants to know the maximum luck he can achieve by drawing these letters.\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, representing the number of rows and columns of the matrix.\n\nThe next $n$ lines each contain $m$ integers. The $(i+1)^{th}$ line's $j^{th}$ number represents the luck value of the grid cell $(j, n \u2212 i + 1)`.\n\n---\n\n### Output Format\nOutput a single integer $T`, representing the maximum luck Xiao E can achieve.\n\n---\n\n### Examples\n#### Sample Input 1\n```plain\n3 13\n1 1 -1 -1 1 -1 1 1 1 -1 1 1 1\n1 -1 1 -1 1 -1 1 -1 1 -1 -1 1 -1\n1 -1 -1 1 1 -1 1 1 1 -1 1 1 1\n```\n\n#### Sample Output 1\n```plain\n24\n```\n\n#### Explanation 1\n![](https://i.loli.net/2018/06/10/5b1cf34eecabe.png)\n\n---\n\n#### Sample Input 2\n```plain\n3 13\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n```\n\n#### Sample Output 2\n```plain\n-20\n```\n\n#### Explanation 2\nBelow is an example of an optimal solution; other optimal solutions may exist.\n![](https://i.loli.net/2018/06/10/5b1cf38caea6c.png)\n\n---\n\n#### Sample Input/Output 3\nRefer to the provided files `penman.in` and `penman.ans`.\n\n---\n\n### Constraints and Hints\n| Test Case Number | $n$ | $m$ | Luck Value Range |\n| :--------------: | :------: | :------: | :---------------: |\n| 1 | $=3$ | $=12$ | $[-50,50]$ |\n| 2 | $=3$ | $=12$ | $[-50,50]$ |\n| 3 | $=3$ | $=12$ | $[-50,50]$ |\n| 4 | $=3$ | $=12$ | $[-50,50]$ |\n| 5 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 6 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 7 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 8 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 9 | $\\leq150$ | $\\leq500$ | $=1$ |\n| 10 | $\\leq150$ | $\\leq500$ | $=1$ |\n| 11 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 12 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 13 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 14 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 15 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 16 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 17 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 18 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 19 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 20 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n\nFor all test cases, it is guaranteed that $n \\geq 3$, $m \\geq 12`.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3387, "prompt": "### Problem Description\n\nC is learning about string matching and is working on a problem.\n\nFor a string $S$, the task is to find the number of possible splitting schemes of $S$ that satisfy the following forms:\n\n$S = ABC$, $S = ABABC$, $S = ABAB \\ldots ABC$, where $A$, $B$, and $C$ are all non-empty strings, and the number of characters that appear an odd number of times in $A$ does not exceed that in $C$.\n\nMore specifically, we can define $AB$ to denote the concatenation of two strings $A$ and $B$. For example, if $A = \\texttt{aab}$ and $B = \\texttt{ab}$, then $AB = \\texttt{aabab}$.\n\nWe can also recursively define $A^1 = A$, $A^n = A^{n - 1} A$ (where $n \\geq 2$ and is a positive integer). For example, if $A = \\texttt{abb}$, then $A^3 = \\texttt{abbabbabb}$.\n\nThus, C\u2019s task is to find the number of splitting schemes for $S = {(AB)}^iC$, where $F(A) \\leq F(C)$. Here, $F(S)$ represents the number of characters in string $S$ that appear an odd number of times. Two schemes are considered different if and only if at least one of the strings $A$, $B$, $C$ differs.\n\nC doesn\u2019t know how to solve this problem, so they\u2019re asking for your help.\n\n### Input Format\n\nThe input consists of multiple test cases. The first line contains a positive integer $T$, representing the number of test cases.\n\nEach test case consists of a single line containing a string $S$, as described in the problem statement. $S$ consists only of lowercase English letters.\n\n### Output Format\n\nFor each test case, output a single integer on a new line, representing the answer.\n\n### **Sample Input #1**\n\n```\n1\nnnrnrr\n```\n\n### **Sample Output #1**\n\n```\n8\n```\n\n### **Explanation for Sample #1**\n\nFor the first test case, all possible schemes are:\n\n1. $A = \\texttt{n}$, $B = \\texttt{nr}$, $C = \\texttt{nnr}$.\n2. $A = \\texttt{n}$, $B = \\texttt{nrn}$, $C = \\texttt{nr}$.\n3. $A = \\texttt{n}$, $B = \\texttt{nrnn}$, $C = \\texttt{r}$.\n4. $A = \\texttt{nn}$, $B = \\texttt{r}$, $C = \\texttt{nnr}$.\n5. $A = \\texttt{nn}$, $B = \\texttt{rn}$, $C = \\texttt{nr}$.\n6. $A = \\texttt{nn}$, $B = \\texttt{rnn}$, $C = \\texttt{r}$.\n7. $A = \\texttt{nnr}$, $B = \\texttt{n}$, $C = \\texttt{nr}$.\n8. $A = \\texttt{nnr}$, $B = \\texttt{nn}$, $C = \\texttt{r}$.\n\n### Constraints\n\n| Test Point ID | $\\lvert S \\rvert \\leq$ | Special Properties |\n|:-:|:-:|:-:|\n| $1 \\sim 4$ | $10$ | None |\n| $5 \\sim 8$ | $100$ | None |\n| $9 \\sim 12$ | $1000$ | None |\n| $13 \\sim 14$ | $2^{15}$ | $S$ contains only one type of character |\n| $15 \\sim 17$ | $2^{16}$ | $S$ contains only two types of characters |\n| $18 \\sim 21$ | $2^{17}$ | None |\n| $22 \\sim 25$ | $2^{20}$ | None |\n\nFor all test cases, it is guaranteed that $1 \\leq T \\leq 5$, $1 \\leq \\lvert S \\rvert \\leq 2^{20}$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3565, "prompt": "### Problem Description\n\nGiven integers $n, m, k$, and a positive integer array of length $m + 1$ denoted as $v_0, v_1, \\ldots, v_m$.\n\nFor a non-negative integer sequence $\\{a_i\\}$ of length $n$, where the indices start from $1$ and each element does not exceed $m$, we define its weight as $v_{a_1} \\times v_{a_2} \\times \\cdots \\times v_{a_n}$.\n\nIf such a sequence $\\{a_i\\}$ satisfies the condition that the number of $1$s in the binary representation of the integer $S = 2^{a_1} + 2^{a_2} + \\cdots + 2^{a_n}$ does not exceed $k$, we consider $\\{a_i\\}$ to be a valid sequence.\n\nCompute the sum of the weights of all valid sequences $\\{a_i\\}$, modulo $998244353$.\n\n### Input Format\n\nThe first line contains three integers $n, m, k$.\n\nThe second line contains $m + 1$ integers, $v_0, v_1, \\ldots, v_m$.\n\n### Output Format\n\nOutput a single integer, representing the sum of the weights of all valid sequences modulo $998244353$.\n\n**Example Explanation #1**\n\nSince $k = 1$, and from $n \\leq S \\leq n \\times 2^m$ we know $5 \\leq S \\leq 10$, the only valid $S$ is $S = 8$. This requires the sequence $a$ to contain exactly $2$ zeros and $3$ ones. There are $\\binom{5}{2} = 10$ possible sequences, and each sequence contributes a weight of $v_0^2 v_1^3 = 4$. Thus, the total weight sum is $10 \\times 4 = 40$.\n\n### Constraints\n\nAll test cases guarantee that $1 \\leq k \\leq n \\leq 30$, $0 \\leq m \\leq 100$, and $1 \\leq v_i < 998244353$.\n\n| Test Case | $n$ | $k$ | $m$ |\n| :-------------: | :---: | :------: | :----: |\n| $1 \\sim 4$ | $=8$ | $\\leq n$ | $=9$ |\n| $5 \\sim 7$ | $=30$ | $\\leq n$ | $=7$ |\n| $8 \\sim 10$ | $=30$ | $\\leq n$ | $=12$ |\n| $11 \\sim 13$ | $=30$ | $=1$ | $=100$ |\n| $14 \\sim 15$ | $=5$ | $\\leq n$ | $=50$ |\n| $16$ | $=15$ | $\\leq n$ | $=100$ |\n| $17 \\sim 18$ | $=30$ | $\\leq n$ | $=30$ |\n| $19 \\sim 20$ | $=30$ | $\\leq n$ | $=100$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2670, "prompt": "### Problem Description\n\nDongdong has recently become fascinated by random algorithms, and random number generation is the foundation of random algorithms. Dongdong plans to use the Linear Congruential Method to generate a sequence of random numbers. This method requires setting four non-negative integer parameters $m$, $a$, $c$, and $X_0$, and generates a sequence of random numbers $\\lbrace X_n \\rbrace$ based on the following formula:\n\n$$\nX_{n+1} = (aX_n + c) \\bmod m\n$$\n\nHere, $\\bmod m$ represents the remainder of the division of the preceding number by $m$. From this formula, it can be observed that the next number in the sequence is always derived from the previous number.\n\nSequences generated using this method exhibit properties of randomness, and this method is widely used, including in common C++ and Pascal random number generation library functions, which implement this method.\n\nAlthough Dongdong knows that sequences generated this way have good randomness, he is eager to know the value of $X_n$ as soon as possible. Since Dongdong needs random numbers between $0$, $1$, ..., $g-1$, he will take the remainder of $X_n$ divided by $g$, i.e., $X_n \\bmod g$. Your task is to simply tell Dongdong the result of $X_n \\bmod g$.\n\n---\n\n### Input Format\n\nA single line containing $6$ space-separated integers $m$, $a$, $c$, $X_0$, $n$, and $g$, where $a$, $c$, $X_0$ are non-negative integers, and $m$, $n$, $g$ are positive integers.\n\n---\n\n### Output Format\n\nOutput a single integer, which is the value of $X_n \\bmod g$.\n\n---\n\n### Examples\n\nThe first few terms of $\\lbrace X_n \\rbrace$ are:\n\n$$\n\\begin{array}{ l | c | r } \\hline\nk & 0 & 1 & 2 & 3 & 4 & 5 \\\\ \\hline\nX_k & 1 & 4 & 6 & 0 & 7 & 8 \\\\ \\hline\n\\end{array}\n$$\n\nThus, the answer is $X_5 \\bmod g = 8 \\bmod 3 = 2$.\n\n---\n\n### Constraints and Hints\n\n| Test Case Number | $n$ | $m,a,c,X_0$ | Properties of $m,a$ |\n| :-: | :-: | :-: | :-: |\n| 1 | $n \\leq 100$ | $m,a,c,X_0 \\leq 100$ | $m$ is a prime number |\n| 2 | $n \\leq 1000$ | $m,a,c,X_0 \\leq 1000$ | $m$ is a prime number |\n| 3 | $n \\leq 10^4$ | $m,a,c,X_0 \\leq 10^4$ | $m$ is a prime number |\n| 4 | $n \\leq 10^4$ | $m,a,c,X_0 \\leq 10^4$ | $m$ is a prime number |\n| 5 | $n \\leq 10^5$ | $m,a,c,X_0 \\leq 10^4$ | $m$ and $a-1$ are coprime |\n| 6 | $n \\leq 10^5$ | $m,a,c,X_0 \\leq 10^4$ | $m$ and $a-1$ are coprime |\n| 7 | $n \\leq 10^5$ | $m,a,c,X_0 \\leq 10^4$ | $m$ and $a-1$ are coprime |\n| 8 | $n \\leq 10^6$ | $m,a,c,X_0 \\leq 10^4$ | - |\n| 9 | $n \\leq 10^6$ | $m,a,c,X_0 \\leq 10^9$ | $m$ is a prime number |\n| 10 | $n \\leq 10^6$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 11 | $n \\leq 10^{12}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ is a prime number |\n| 12 | $n \\leq 10^{12}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ is a prime number |\n| 13 | $n \\leq 10^{16}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ and $a-1$ are coprime |\n| 14 | $n \\leq 10^{16}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ and $a-1$ are coprime |\n| 15 | $n \\leq 10^{16}$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 16 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 17 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 18 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^{18}$ | $m$ is a prime number |\n| 19 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^{18}$ | $m$ and $a-1$ are coprime |\n| 20 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^{18}$ | - |\n\nFor all test cases, $n \\geq 1$, $m \\geq 1$, $a \\geq 0$, $c \\geq 0$, $X_0 \\geq 0$, $1 \\leq g \\leq 10^8$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3566, "prompt": "### Problem Description\n\nGiven a sequence of positive integers of length $n$ that is non-strictly increasing, $1 \\leq a_1 \\leq a_2 \\leq \\cdots \\leq a_n$. The operation you can perform each time is: arbitrarily select any positive integer $1 < i < n$ and replace $a_i$ with $a_{i - 1} + a_{i + 1} - a_i$. Find the minimum variance of this sequence after performing some number of operations. Output the result multiplied by $n^2$.\n\nThe definition of variance is: the average of the squares of the differences between each number in the sequence and the mean of the sequence. More formally, the variance is defined as $D = \\frac{1}{n} \\sum_{i = 1}^{n} {(a_i - \\bar{a})}^2$, where $\\bar{a} = \\frac{1}{n} \\sum_{i = 1}^{n} a_i$.\n\n### Input Format\n\nThe first line of the input contains a positive integer $n$, ensuring $n \\leq {10}^4$.\n\nThe second line contains $n$ positive integers, where the $i$th number represents the value of $a_i$. It is guaranteed that $1 \\leq a_1 \\leq a_2 \\leq \\cdots \\leq a_n$.\n\n### Output Format\n\nOutput a single line containing a non-negative integer, which represents the minimum variance multiplied by $n^2$.\n\n**Sample Explanation #1**\n\nFor $(a_1, a_2, a_3, a_4) = (1, 2, 4, 6)$, after the first operation, the sequence becomes $(1, 3, 4, 6)$, and after the second operation, the sequence becomes $(1, 3, 5, 6)$. No new sequences can be obtained after this.\n\nFor $(a_1, a_2, a_3, a_4) = (1, 2, 4, 6)$, the mean value is $\\frac{13}{4}$, and the variance is $\\frac{1}{4}({(1 - \\frac{13}{4})}^2 + {(2 - \\frac{13}{4})}^2 + {(4 - \\frac{13}{4})}^2 + {(6 - \\frac{13}{4})}^2) = \\frac{59}{16}$.\n\nFor $(a_1, a_2, a_3, a_4) = (1, 3, 4, 6)$, the mean value is $\\frac{7}{2}$, and the variance is $\\frac{1}{4}({(1 - \\frac{7}{2})}^2 + {(3 - \\frac{7}{2})}^2 + {(4 - \\frac{7}{2})}^2 + {(6 - \\frac{7}{2})}^2) = \\frac{13}{4}$.\n\nFor $(a_1, a_2, a_3, a_4) = (1, 3, 5, 6)$, the mean value is $\\frac{15}{4}$, and the variance is $\\frac{1}{4}({(1 - \\frac{15}{4})}^2 + {(3 - \\frac{15}{4})}^2 + {(5 - \\frac{15}{4})}^2 + {(6 - \\frac{15}{4})}^2) = \\frac{59}{16}$.\n\n**Data Constraints**\n\n| Test Case ID | $n \\leq$ | $a_i \\leq$ |\n|:-:|:-:|:-:|\n| $1 \\sim 3$ | $4$ | $10$ |\n| $4 \\sim 5$ | $10$ | $40$ |\n| $6 \\sim 8$ | $15$ | $20$ |\n| $9 \\sim 12$ | $20$ | $300$ |\n| $13 \\sim 15$ | $50$ | $70$ |\n| $16 \\sim 18$ | $100$ | $40$ |\n| $19 \\sim 22$ | $400$ | $600$ |\n| $23 \\sim 25$ | ${10}^4$ | $50$ |\n\nFor all test cases, it is ensured that $1 \\leq n \\leq {10}^4$ and $1 \\leq a_i \\leq 600$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2447, "prompt": "### Problem Description\n\nThese days, Bunny and Eggy have become fond of a new board game.\n\nThe game is played on a chessboard with $n$ rows and $m$ columns. Before the game starts, one cell on the chessboard is empty, while all other cells contain a chess piece, which can either be black or white.\n\nIn each round of the game, Bunny goes first, followed by Eggy, taking turns alternately. The rules for their moves are as follows:\n* On each turn, Bunny chooses a white chess piece adjacent to the empty cell and moves it into the empty cell.\n* On each turn, Eggy chooses a black chess piece adjacent to the empty cell and moves it into the empty cell.\n\nThe first player who cannot make a valid move according to the rules loses the game. To make the description clearer, the move of \"moving the chess piece in row $x$, column $y$ into the empty cell\" is denoted as $M(x,y)$.\n\nFor example, the following are three examples of the game:\n\n![](https://i.loli.net/2018/06/11/5b1e029d60b0d.png)\n\n![](https://i.loli.net/2018/06/11/5b1e029d6886a.png)\n\n![](https://i.loli.net/2018/06/11/5b1e029d7f3b9.png)\n\nRecently, Bunny has been losing games a lot, and Eggy has been especially smug about it. As a result, Bunny has approached you, her good friend, for help. She has brought you the game record of a match where she lost to Eggy. Your task is to identify all the moments during the game where Bunny \"made mistakes.\"\n\nNote:\n* Two cells are considered adjacent if and only if they share a common edge.\n* Bunny's move is considered a \"mistake\" if and only if she had a winning strategy before the move but, after the move, Eggy has a winning strategy.\n\n---\n\n### Input Format\nThe first line contains two integers $n$ and $m$.\n\nThe next $n$ lines describe the initial chessboard. The $i$-th line contains $m$ characters, where each character is one of the following:\n* An uppercase letter `X`, `O`, or a dot `.`. \n * The letter `X` represents a cell with a black chess piece.\n * The letter `O` represents a cell with a white chess piece.\n * The dot `.` represents the empty cell.\n\nIt is guaranteed that the board contains exactly one empty cell.\n\nThe next line contains an integer $k$ ($1 \\le k \\le 1000$), representing the total number of moves made by Bunny and Eggy (Bunny moves $k$ times, and Eggy also moves $k$ times).\n\nThe next $2k$ lines describe the gameplay process. Specifically:\n* The $2i - 1$-th line corresponds to Bunny's $i$-th move (the move with index $i$).\n* The $2i$-th line corresponds to Eggy's $i$-th move.\n\nEach move is described by two integers $x, y$, which represent moving the chess piece in row $x$, column $y$ into the empty cell.\n\nIt is guaranteed that throughout the game:\n* There is exactly one empty cell on the board at any time.\n* Every move made by Bunny and Eggy is valid.\n* Eggy wins the game in the end.\n\n---\n\n### Output Format\nThe first line of the output contains an integer $r$, representing the total number of times Bunny made mistakes during the game.\n\nThe next $r$ lines contain the indices of Bunny's mistaken moves in increasing order. Specifically:\n* The $i$-th line contains an integer $a_i$, indicating that Bunny's $i$-th mistake occurred on her $a_i$-th move during the game.\n\n---\n\n### Sample 1\n\n#### Input\n```plaintext\n2 2\nXO\n.O\n2\n1 2\n2 2\n2 1\n1 1\n```\n\n#### Output\n```plaintext\n1\n1\n```\n\n---\n\n### Sample 2\n\n#### Input\n```plaintext\n3 3\nOOO\nO.O\nXXX\n2\n2 2\n2 3\n1 3\n3 3\n```\n\n#### Output\n```plaintext\n1\n2\n```\n\n---\n\n### Sample 3\n\n#### Input\n```plaintext\n3 4\nXXXX\n.OOX\nXOOX\n2\n2 2\n2 3\n2 4\n1 4\n```\n\n#### Output\n```plaintext\n0\n```\n\n---\n\n### Sample Interpretations\n* **Sample 1** corresponds to the game shown in the first figure.\n* **Sample 2** corresponds to the game shown in the third figure.\n\n---\n\n### Constraints and Notes\n\nThe following table outlines the constraints on the problem:\n\n| Test Case Number | Scale of $n$ | Scale of $m$ |\n| :-: | :-: | :-: |\n| 1 | $n = 1$ | $1 \\le m \\le 20$ |\n| 2 | $n = 1$ | $1 \\le m \\le 20$ |\n| 3 | $n = 3$ | $m = 4$ |\n| 4 | $n = 4$ | $m = 4$ |\n| 5 | $n = 4$ | $m = 4$ |\n| 6 | $n = 4$ | $m = 5$ |\n| 7 | $n = 4$ | $m = 5$ |\n| 8 | $n = 3$ | $m = 7$ |\n| 9 | $n = 2$ | $1 \\le m \\le 40$ |\n| 10 | $n = 2$ | $1 \\le m \\le 40$ |\n| 11 | $n = 2$ | $1 \\le m \\le 40$ |\n| 12 | $n = 2$ | $1 \\le m \\le 40$ |\n| 13 | $n = 2$ | $1 \\le m \\le 40$ |\n| 14 | $n = 2$ | $1 \\le m \\le 40$ |\n| 15 | $1 \\le n \\le 16$ | $1 \\le m \\le 16$ |\n| 16 | $1 \\le n \\le 16$ | $1 \\le m \\le 16$ |\n| 17 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n| 18 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n| 19 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n| 20 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2608, "prompt": "### Problem Description\n$n$ friends (numbered from $0$ to $n-1$) sit in a circle and play a game. The positions are numbered clockwise from $0$ to $n-1$. Initially, the $0$th friend is at position $0$, the $1$st friend is at position $1$, and so on.\n\nThe rules of the game are as follows: During each round, the friend at position $0$ moves clockwise to position $m$, the friend at position $1$ moves to position $m+1$, and so forth. The friend at position $n\u2212m$ moves to position $0$, the friend at position $n\u2212m+1$ moves to position $1$, and finally, the friend at position $n\u22121$ moves clockwise to position $m\u22121$.\n\nGiven that a total of $10^k$ rounds are played, determine the position of the friend numbered $x$ after all the rounds.\n\n### Input Format\nThe input consists of $1$ line containing $4$ integers $n$, $m$, $k$, and $x$, separated by spaces.\n\n### Output Format\nOutput $1$ line containing $1$ integer, representing the final position of the friend numbered $x$ after $10^k$ rounds.\n\n### Example\n\n#### Input:\n```\n10 3 1 4\n```\n\n#### Output:\n```\n7\n```\n\n### Constraints and Notes\n- For $30\\%$ of the data, $0 < k < 7$;\n- For $80\\%$ of the data, $0 < k < 10^7$;\n- For $100\\%$ of the data, $1 < n < 10^6$, $0 < m < n$, $1 \\leq x \\leq n$, $0 < k < 10^9$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2421, "prompt": "### Problem Description\n\nThere are $n$ students (numbered from $1$ to $n$) playing an information transmission game. In the game, each student has a fixed target to whom they transmit information. Specifically, the information transmission target for the student numbered $i$ is the student numbered $T_i$. At the beginning of the game, each student only knows their own birthday. In each subsequent round, all students simultaneously share the birthday information they currently know with their respective transmission targets (note: some students may receive information from multiple people, but every student only shares their information with one person \u2014 their transmission target). The game ends when a student learns their own birthday from someone else. Your task is to determine the total number of rounds the game can proceed before it ends.\n\n---\n\n### Input Format\n\nThe input consists of $2$ lines:\n\n- The first line contains a single positive integer $n$, representing the number of students. \n- The second line contains $n$ positive integers $T_1, T_2, \\ldots, T_n$, where the integer $T_i$ indicates that the transmission target of the student numbered $i$ is the student numbered $T_i$. Here, $T_i \\leq n$ and $T_i \\neq i$.\n\nIt is guaranteed that the game will eventually end.\n\n---\n\n### Output Format\n\nOutput a single line containing one integer, representing the total number of rounds the game runs.\n\n---\n\n### Sample\n\n(Provide example input and output here.)\n\n---\n\n### Constraints and Hints\n\n- For $30\\%$ of the data, $n \\leq 200$; \n- For $60\\%$ of the data, $n \\leq 2500$; \n- For $100\\%$ of the data, $n \\leq 200,000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2355, "prompt": "### Problem Description\nT Company is a manufacturer that specializes in producing colorful beaded necklaces. Their necklaces are known for innovative designs, diverse styles, and reasonable prices, making them highly popular among young people. Recently, T Company decided to launch a necklace self-production system, allowing customers to design their own beautiful necklaces according to their preferences. \n\nThis necklace self-production system consists of hardware and software components. The software system interacts with the user and controls the hardware system, while the hardware system executes commands from the software to produce the specified necklace. The hardware system has already been completed, but the software system is yet to be developed. T Company has approached you, a participant in a national informatics competition, to help them develop a software simulation system. \n\nA necklace consists of $N$ beads, each of a color chosen from the set $1, 2, \\dots , c$. The necklace is affixed to a flat surface, and one position on the surface is designated as position $1$. The other positions are numbered $2, 3, \\dots, N$ in a clockwise direction.\n\n![fff(1).png](https://i.loli.net/2018/02/12/5a81482d1a124.png)\n\nYour task is to write a software system that supports the following commands:\n\n![fa.png](https://i.loli.net/2018/02/12/5a81482d414fe.png)\n\n#### Clarifications\n- **On Rotation and Reversal:** \n The `Rotate` command rotates the \"beads\" without changing the numbering of the \"positions\", while the `Flip` command always uses position $1$ as the axis of symmetry.\n \n- **On the `CountSegment` Command:** \n The `CS` command queries how many \"segments\" are present in a specified \"line segment\". Note that when the queried length equals $N$, the query is still considered as a \"line segment\".\n\n---\n\n### Input Format\nThe first line of input contains two integers $N$ and $c$, representing the number of beads in the necklace and the number of colors, respectively. \nThe second line contains $N$ integers, $x_1, x_2, \\dots, x_N$, representing the colors of the beads from position $1$ to position $N$, where $1 \\leq x_i \\leq c$. \nThe third line contains an integer $Q$, representing the number of commands. The following $Q$ lines each contain one command as described above. \n\n---\n\n### Output Format\nFor every `Count` (`C`) and `CountSegment` (`CS`) command, output an integer representing the corresponding answer.\n\n---\n\n### Example\n\n#### Input\n```\n10 3\n1 1 2 2 3 3 3 2 2 1\n6\nR 2\nC 3\nCS 1 6\nF\nC 4\nCS 1 10\n```\n\n#### Output\n```\n2\n2\n1\n3\n4\n```\n\n---\n\n### Data Range and Notes\n- For $60\\%$ of the test cases, $N \\leq 1000$ and $Q \\leq 1000$. \n- For $100\\%$ of the test cases, $N \\leq 500,000$, $Q \\leq 500,000$, and $c \\leq 1000$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2296, "prompt": "### Problem Background\n\nThe legendary Nine-Headed Dragon is an extremely gluttonous creature. Although it is called the \"Nine-Headed Dragon,\" this name only refers to the fact that it was born with nine heads. During its growth, it sometimes grows many new heads, causing the total number of heads to greatly exceed nine; naturally, some older heads may also fall off due to aging.\n\n### Problem Description\n\nOne day, a Nine-Headed Dragon with $M$ heads encounters a tree with $N$ fruits and becomes ecstatic, wishing it could eat all the fruits in one bite. However, every head must be attended to. Thus, the $N$ fruits need to be split into $M$ groups, with each group containing at least one fruit, so that each head can eat one group.\n\nAmong these $M$ heads, there is one head that is the largest, known as the \"big head,\" which is the leader of all the heads. The big head must eat exactly $K$ fruits, and these $K$ fruits must include the single biggest fruit. The fruits are connected by $N-1$ branches, forming a structure such that the entire tree is interconnected: starting from any fruit, one can traverse the branches to reach any other fruit.\n\nFor each branch, if the two fruits it connects are eaten by different heads, the two heads will jointly break the branch to separate the fruits. If the two fruits are eaten by the same head, this head will eat the fruits together with the branch, avoiding the need for separation. However, eating a branch is uncomfortable; each branch has a \"discomfort value,\" and the dragon's overall discomfort value is defined as the sum of the discomfort values of all the branches eaten by its heads.\n\nThe Nine-Headed Dragon hopes to minimize its overall discomfort value. Can you help it calculate the minimum discomfort value?\n\n### Input Format\n\n- The first line contains three integers $N$, $M$, and $K$. The $N$ fruits are numbered $1, 2, \\dots, N$, and the biggest fruit is always numbered as $1$.\n- Lines $2$ through $N$ describe the structure of the tree. Each line contains three integers $a$, $b$, and $c$, indicating there is a branch with a discomfort value of $c$ connecting fruit $a$ and fruit $b$.\n\n### Output Format\n\n- Output a single integer in one line, representing the minimum discomfort value of the dragon while meeting the requirement of the \"big head.\" If the requirements cannot be satisfied, output $-1$.\n\n### Example\n\nFor the example shown in **Figure 1**, the fruit tree contains $8$ fruits and $7$ branches. The discomfort values are labeled next to each branch. The Nine-Headed Dragon has $2$ heads, and the big head needs to eat $4$ fruits, including the biggest fruit. That is, $N=8$, $M=2$, and $K=4$:\n\n![](https://img.loj.ac.cn/2022/06/09/9f4ca2a84dced.png)\n\n**Figure 1** shows the structure of the fruit tree, and **Figure 2** shows the optimal strategy.\n\n### Constraints and Hints\n\nFor $100\\%$ of the data:\n- $1 \\leq K \\leq N \\leq 300$\n- $2 \\leq M \\leq N$\n- $1 \\leq a, b \\leq N$\n- $0 \\leq c \\leq 10^5$\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3160, "prompt": "### Problem Description\nLittle S is playing a game called \"Dou Dizhu\" with Little F.\n\nUnfortunately, Little S finds that he cannot win against Little F during the card play phase, so he decides to cheat during the shuffling phase.\n\nA deck consists of $n$ cards, numbered sequentially from $1 \\sim n$ from top to bottom. The **score** of the card numbered $i$ is denoted as $f(i)$. In this problem, $f(i)$ can only have two possible values: $f(i) = i$ or $f(i) = i^2$.\n\nThe shuffling process is similar to how we shuffle cards in real-life games. Below is a formalized definition of the process:\n\nThe shuffling consists of $m$ rounds, which are executed in sequence. During the $i$-th round of shuffling:\n1. Little S takes out the top $A_i$ cards. This splits the deck into two piles: the first pile contains the top $A_i$ cards, and the second pile contains the remaining $n - A_i$ cards, both maintaining their relative order. Specifically, if $A_i = n$ or $A_i = 0$, one of the piles will be empty.\n2. The two piles are then merged into a new third pile. If the first pile still contains $X$ cards and the second pile still contains $Y$ cards, there is a probability of $\\frac{X}{X+Y}$ of taking the bottom card of the first pile and placing it on the top of the new third pile, and a probability of $\\frac{Y}{X+Y}$ of taking the bottom card of the second pile and placing it on the top of the new third pile.\n3. Step 2 is repeated until both piles are empty. At this point, the current round of shuffling is complete.\n\nSince the shuffling process is random, Little S cannot determine the exact card in a specific position. However, Little S wants to ask about the **expected score** of the card at a specific position after $m$ rounds of shuffling. He will ask you $Q$ such questions.\n\n---\n\n### Input Format\nThe input is read from a file named `landlords.in`.\n\nThe first line contains three positive integers $n$, $m$, and $\\text{type}$, which represent the number of cards, the number of shuffling rounds, and the type of $f(i)$, respectively. When $\\text{type} = 1$, $f(i) = i$. When $\\text{type} = 2$, $f(i) = i^2$.\n\nThe second line contains $m$ integers, denoting $A_1 \\sim A_m$.\n\nThe third line contains a positive integer $Q$, representing the number of questions Little S will ask.\n\nThe next $Q$ lines each contain a positive integer $c_i$, representing that Little S wants to know the **expected score** of the card at the $c_i$-th position from the top. It is guaranteed that $1 \\leq c_i \\leq n$.\n\n---\n\n### Output Format\nThe output is written to a file named `landlords.out`.\n\nThe output consists of $Q$ lines, each containing an integer, representing the answer under modulo $998244353$.\n\nSpecifically, if the answer in its simplest fractional form is $\\frac{a}{b}$, where $a$ and $b$ are coprime, output an integer $x$ such that $bx \\equiv a \\pmod{998244353}$ and $0 \\leq x < 998244353$. It can be proven that such an integer $x$ is unique.\n\n---\n\n### Example\nThere is a $\\frac{1}{4}$ probability that, after shuffling, the deck order from top to bottom is $\\{1, 2, 3, 4\\}$.\n\nThere is a $\\frac{1}{4}$ probability that the deck order is $\\{1, 2, 4, 3\\}$.\n\nThere is a $\\frac{1}{4}$ probability that the deck order is $\\{1, 4, 2, 3\\}$.\n\nThere is a $\\frac{1}{4}$ probability that the deck order is $\\{4, 1, 2, 3\\}$.\n\nThus, the first position has a $\\frac{1}{4}$ probability of being $4$ and a $\\frac{3}{4}$ probability of being $1$, resulting in an expected score of $\\frac{7}{4}$.\n\nTo help you better understand the shuffling process, the following diagram illustrates the process that results in $\\{1, 4, 2, 3\\}$:\n\n![No.3160.CN.png](https://img.loj.ac.cn/2020/12/22/5fe13fd6d76c0.png)\n\n---\n\n### Constraints and Hints\nFor all test cases: $3 \\leq n \\leq 10^7$, $1 \\leq m, Q \\leq 5 \\times 10^5$, $0 \\leq A_i \\leq n$, and $\\text{type} \\in \\{1, 2\\}$.\n\nAdditional constraints for specific test cases are as follows:\n\n| Test Case ID | $n$ | $m$ | $\\text{type}=$ | Additional Properties |\n| :----------: | :-------: | :------------: | :------------: | :-----------------------------: |\n| $1$ | $\\leq 10$ | $\\leq 1$ | $1$ | None |\n| $2$ | $\\leq 80$ | $\\leq 80$ | $1$ | None |\n| $3$ | $\\leq 80$ | $\\leq 80$ | $2$ | None |\n| $4$ | $\\leq 100$| $5 \\times 10^5$| $2$ | All $A_i$ are identical |\n| $5$ | $10^7$ | $5 \\times 10^5$| $1$ | None |\n| $6$ | $10^7$ | $5 \\times 10^5$| $1$ | None |\n| $7$ | $10^7$ | $5 \\times 10^5$| $1$ | None |\n| $8$ | $10^7$ | $5 \\times 10^5$| $2$ | None |\n| $9$ | $10^7$ | $5 \\times 10^5$| $2$ | None |\n| $10$ | $10^7$ | $5 \\times 10^5$| $2$ | None |\n\nNote that we do **not guarantee** $Q \\leq n$.\n\nHere we provide the definition of the expected value $\\mathbb{E}[x]$ of a discrete random variable $X$:\n\nGiven a discrete random variable $X$ with possible values $X_1, X_2, \\ldots, X_k$ and corresponding probabilities $\\text{Pr}[X_1], \\text{Pr}[X_2], \\ldots, \\text{Pr}[X_k]$, the expected value is defined as:\n$$\n\\mathbb{E}[x] = \\sum_{i=1}^k X_i \\text{Pr}[X_i]\n$$\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2667, "prompt": "### Problem Description\n\nTingting is a little girl who loves matrices. One day, she decided to use a computer to generate a huge matrix with $n$ rows and $m$ columns (you don\u2019t need to worry about how she stores it). The matrix she generates satisfies a magical property: if $F[i][j]$ represents the element in the $i$-th row and $j$-th column of the matrix, then $F[i][j]$ satisfies the following recurrence relations:\n$$\n\\begin{cases}\nF[1][1] = 1 \\\\\nF[i][j] = a * F[i][j-1]+b & j \\neq 1 \\\\\nF[i][1] = c * F[i-1][m]+d & i \\neq 1\n\\end{cases}\n$$\nHere, $a$, $b$, $c$, $d$ are given constants.\n\nNow Tingting wants to know the value of $F[n][m]$. Please help her calculate it. Since the final result may be very large, you only need to output $F[n][m]$ modulo $1,000,000,007$.\n\n---\n\n### Input Format\n\nA single line containing six integers: $n$, $m$, $a$, $b$, $c$, $d$, as described in the problem statement.\n\n---\n\n### Output Format\n\nOutput a single integer, representing $F[n][m]$ modulo $1,000,000,007$.\n\n---\n\n### Examples\n\n#### Example Input 1\n```plain\n3 4 1 3 2 6\n```\n\n#### Example Output 1\n```plain\n85\n```\n\n#### Example Explanation 1\nThe matrix for the example is:\n$$\n\\begin{pmatrix} \n1 & 4 & 7 & 10 \\\\ \n26 & 29 & 32 & 35 \\\\ \n76 & 79 & 82 & 85 \n\\end{pmatrix}\n$$\n\n#### Example Input/Output 2\nRefer to the attached files: `matrix.in` and `matrix.ans`.\n\n---\n\n### Constraints and Hints\n\n| Test Case ID | Constraints |\n| :-: | :-: |\n| 1 | $1 \\le n,m \\le 10$; $1 \\le a,b,c,d \\le 1,000$ |\n| 2 | $1 \\le n,m \\le 100$; $1 \\le a,b,c,d \\le 1,000$ |\n| 3 | $1 \\le n,m \\le 10^3$; $1 \\le a,b,c,d \\le 10^9$ |\n| 4 | $1 \\le n,m \\le 10^3$; $1 \\le a,b,c,d \\le 10^9$ |\n| 5 | $1 \\le n,m \\le 10^9$; $1 \\le a = c \\le 10^9$; $1 \\le b = d \\le 10^9$ |\n| 6 | $1 \\le n,m \\le 10^9$; $a = c = 1$; $1 \\le b,d \\le 10^9$ |\n| 7 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 8 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 9 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 10 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 11 | $1 \\le n,m \\le 10^{1000}$; $a = c = 1$; $1 \\le b,d \\le 10^9$ |\n| 12 | $1 \\le n,m \\le 10^{1000}$; $1 \\le a = c \\le 10^9$; $1 \\le b = d \\le 10^9$ |\n| 13 | $1 \\le n,m \\le 10^{1000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 14 | $1 \\le n,m \\le 10^{1000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 15 | $1 \\le n,m \\le 10^{20000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 16 | $1 \\le n,m \\le 10^{20000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 17 | $1 \\le n,m \\le 10^{1,000,000}$; $a = c = 1$; $1 \\le b,d \\le 10^9$ |\n| 18 | $1 \\le n,m \\le 10^{1,000,000}$; $1 \\le a = c \\le 10^9$; $1 \\le b = d \\le 10^9$ |\n| 19 | $1 \\le n,m \\le 10^{1,000,000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 20 | $1 \\le n,m \\le 10^{1,000,000}$; $1 \\le a,b,c,d \\le 10^9$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3760, "prompt": "### Problem Description\nDuring the World Expo, the air passenger traffic in Shanghai greatly exceeded normal levels, leading to frequent air traffic control occurrences. Recently, Xiao X experienced two consecutive delays of more than two hours at the airport due to air traffic control. Xiao X is quite dissatisfied with this situation.\n\nOn a recent trip to Yantai, Xiao X unfortunately encountered air traffic control again. This prompted Xiao X to ponder the problem of air traffic control.\n\nSuppose there are currently $n$ delayed flights, numbered from $1$ to $n$. The airport has only one runway for takeoff, and all flights must take off in a certain sequence (referred to as the takeoff sequence). The takeoff order of a flight is defined as its position in the takeoff sequence, i.e., the order in which the flight takes off.\n\nThe takeoff sequence is subject to two types of constraints:\n\n- **Type 1 (Latest Takeoff Time Constraint):** The takeoff order of the flight numbered $i$ must not exceed $k_i$.\n\n- **Type 2 (Relative Takeoff Order Constraint):** Some relative takeoff order constraints $(a, b)$ exist, indicating that flight $a$ must take off before flight $b$. In other words, the takeoff order of flight $a$ must be smaller than that of flight $b$.\n\nXiao X considers two questions: \n1. Given the above two types of constraints, is it possible to compute a feasible takeoff sequence? \n2. Considering both types of constraints, what is the minimum possible takeoff order for each flight out of all feasible takeoff sequences?\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, where $n$ represents the number of flights and $m$ represents the number of Type 2 constraints (relative takeoff order constraints).\n\nThe second line contains $n$ positive integers $k_1, k_2, \\cdots, k_n$.\n\nThe following $m$ lines each contain two positive integers $a$ and $b$, representing a Type 2 constraint $(a, b)$, where $1 \\leq a, b \\leq n$, indicating that flight $a$ must take off before flight $b$.\n\n---\n\n### Output Format\n- The first line contains $n$ integers, representing one feasible takeoff sequence, separated by a space. The input guarantees that at least one feasible takeoff sequence exists. If there are multiple solutions, you can output any one of them.\n- The second line contains $n$ integers $t_1, t_2, \\cdots, t_n$, where $t_i$ represents the minimum possible takeoff order for flight $i$ among all feasible takeoff sequences, separated by a space.\n\n---\n\n### Sample Input 1\n```\n5 4\n5 5 3 5 4\n3 1\n5 1\n3 4\n2 5\n```\n\n### Sample Output 1\n```\n3 5 1 4 2\n3 5 1 4 4\n```\n\n#### Explanation for Sample 1:\nThe takeoff sequence `3 5 1 4 2` satisfies all the constraints. All takeoff sequences that meet the constraints are:\n\n$$\n\\begin{aligned}\n3\\ 4\\ 5\\ 1\\ 2\\\\\n3\\ 5\\ 1\\ 2\\ 4\\\\\n3\\ 5\\ 1\\ 4\\ 2\\\\\n3\\ 5\\ 4\\ 1\\ 2\\\\\n5\\ 3\\ 1\\ 2\\ 4\\\\\n5\\ 3\\ 1\\ 4\\ 2\\\\\n5\\ 3\\ 4\\ 1\\ 2\n\\end{aligned}\n$$\n\nBecause there are Type 2 constraints $(5,1)$ and $(3,1)$, flight $1$ can only be scheduled to take off after both flights $5$ and $3$, so its earliest takeoff order is $3$. The other flights follow a similar approach.\n\n---\n\n### Sample Input 2\n```\n5 3\n5 5 3 5 5\n1 4\n2 4\n3 4\n```\n\n### Sample Output 2\n```\n1 2 3 5 4\n1 2 3 4 4\n```\n\n#### Explanation for Sample 2:\nAlthough flights $4$ and $5$ have no relative takeoff order constraints, flights $1$, $2$, and $3$ must take off in the first three slots, meaning flights $4$ and $5$ can only take off starting from the fourth slot.\n\n---\n\n### Constraints and Hints\n- For $30\\%$ of the test cases, $n \\leq 10$. \n- For $60\\%$ of the test cases, $n \\leq 500$. \n- For $100\\%$ of the test cases, $n \\leq 2 \\times 10^3$ and $m \\leq 10^4$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3761, "prompt": "### Problem Description\n\nLittle Z is a well-known pianist. Recently, Dr. C gifted Little Z a super piano, and Little Z hopes to use this piano to create the most beautiful music in the world.\n\nThis super piano can play $n$ notes, numbered from $1$ to $n$. The beauty value of the $i$-th note is $A_i$, where $A_i$ can be positive or negative.\n\nA \"super chord\" is composed of a series of consecutive notes, containing at least $L$ and at most $R$ notes. The beauty value of a super chord is defined as the sum of the beauty values of all the notes it contains. Two super chords are considered the same if and only if the set of notes they contain is identical.\n\nLittle Z plans to compose a piece of music consisting of $k$ super chords. To make the music more melodious, the $k$ super chords must all be distinct. The beauty value of a piece of music is defined as the sum of the beauty values of all the super chords it contains. Little Z wants to know the maximum beauty value of a piece of music he can compose.\n\n---\n\n### Input Format\n\nThe first line contains four positive integers $n$, $k$, $L$, and $R$. Here:\n- $n$ is the number of notes,\n- $k$ is the number of super chords in the piece of music,\n- $L$ and $R$ are the lower and upper limits on the number of notes a super chord can contain, respectively.\n\nThe next $n$ lines each contain a single integer $A_i$, which represents the beauty value of the $i$-th note in order.\n\n---\n\n### Output Format\n\nOutput a single integer, representing the maximum possible beauty value of the piece of music.\n\n---\n\n### Example\n\nThere are $5$ different super chords:\n\n1. Notes $1 \\sim 2$, beauty value $3 + 2 = 5$;\n2. Notes $2 \\sim 3$, beauty value $2 + (-6) = -4$;\n3. Notes $3 \\sim 4$, beauty value $(-6) + 8 = 2$;\n4. Notes $1 \\sim 3$, beauty value $3 + 2 + (-6) = -1$;\n5. Notes $2 \\sim 4$, beauty value $2 + (-6) + 8 = 4$.\n\nThe optimal solution is: the piece of music consists of super chords $1$, $3$, and $5$, with a total beauty value of $5 + 2 + 4 = 11$.\n\n---\n\n### Constraints and Hints\n\n| Test Case | $n$ | $k$ |\n|-----------|-------------|-------------|\n| $1$ | $\\leq 10$ | $\\leq 100$ |\n| $2$ | $\\leq 1000$ | $\\leq 5 \\times 10^5$ |\n| $3$ | $\\leq 10^5$ | $= 1$ |\n| $4$ | $\\leq 10^4$ | $\\leq 10^4$ |\n| $5$ | $\\leq 5 \\times 10^5$ | $\\leq 10^4$ |\n| $6$ | $\\leq 8 \\times 10^4$ | $\\leq 8 \\times 10^4$ |\n| $7$ | $\\leq 10^5$ | $\\leq 10^5$ |\n| $8$ | $\\leq 10^5$ | $\\leq 5 \\times 10^5$ |\n| $9$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ |\n| $10$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ |\n\nAll data satisfy:\n- $-1000 \\leq A_i \\leq 1000$, \n- $1 \\leq L \\leq R \\leq n$, and \n- it is guaranteed that a valid piece of music always exists.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3157, "prompt": "### Problem Description\nLittle R enjoys researching robots.\n\nRecently, Little R has developed two types of robots, named `P`-type robots and `Q`-type robots. He wants to test the mobility of these two types of robots. The test takes place on a row of $n$ pillars, numbered from $1$ to $n$ from left to right. The height of pillar $i$ is represented by a positive integer $h_i$. Robots **can only move between adjacent pillars**, i.e., if a robot is currently on pillar $i$, it can only attempt to move to pillar $i-1$ or pillar $i+1$.\n\nFor each test, Little R selects a starting point $s$ and places both types of robots on pillar $s$. Then, the robots move according to their respective moving rules.\n\nThe `P`-type robot always moves **to the left** but **cannot** move to pillars that are **higher** than the starting pillar $s$. More specifically, the `P`-type robot stops at pillar $l (l \\leq s)$ **if and only if** the following two conditions are simultaneously satisfied:\n\n- $l = 1$ or $h_{l-1} > h_s$.\n- For all $j$ such that $l \\leq j \\leq s$, $h_j \\leq h_s$.\n\nThe `Q`-type robot always moves **to the right** but **can only** move to pillars that are **lower** than the starting pillar $s$. More specifically, the `Q`-type robot stops at pillar $r (r \\geq s)$ **if and only if** the following two conditions are simultaneously satisfied:\n\n- $r = n$ or $h_{r+1} \\geq h_s$.\n- For all $j$ such that $s < j \\leq r$, $h_j < h_s$.\n\nNow, Little R can configure the height of each pillar, and the height of pillar $i$ must be in the range $[A_i, B_i]$, which satisfies $A_i \\leq h_i \\leq B_i$. Little R hopes that **no matter** where the starting point $s$ is selected, the absolute difference in the number of pillars traversed by the two robots is **less than or equal to** $2$. He wants to know how many configurations of pillar heights satisfy this requirement. Little R considers two configurations to be different if there exists some $k$ such that the height of pillar $k$ differs between the two configurations. Please tell him the number of configurations that meet the requirements modulo $10^9 + 7$.\n\n### Input Format\nThe first line contains a positive integer $n$, representing the number of pillars.\n\nThe following $n$ lines each contain two positive integers $A_i, B_i$, representing the minimum and maximum height of pillar $i$.\n\n### Output Format\nA single line that contains an integer\u2014the answer modulo $10^9 + 7$.\n\n### Additional Sample Cases\n\nYou can refer to the attached files for additional sample cases.\n\n#### Sample Case 2\n\nSee the attached files: `robot/robot2.in` and `robot/robot2.ans`.\n\n#### Sample Case 3\n\nSee the attached files: `robot/robot3.in` and `robot/robot3.ans`.\n\n#### Sample Case 4\n\nSee the attached files: `robot/robot4.in` and `robot/robot4.ans`.\n\n### Explanation of Sample Case 1\n\nThere are two possible configurations for the pillar heights:\n\n- Heights: `3 2 3 2 3`. In this case, if the starting point is set at $5$, the `P`-type robot stops at pillar $1$ after traversing $4$ pillars, while the `Q`-type robot stops at pillar $5$ after traversing $0$ pillars. This does not satisfy the condition.\n\n- Heights: `3 2 4 2 3`. In this case, the condition is satisfied regardless of the starting point, as shown in the table below:\n\n| Starting Point | `P`-type Robot | `Q`-type Robot |\n| :------------: | :------------: | :------------: |\n| $1$ | Stops at pillar $1$, traverses $0$ pillars | Stops at pillar $2$, traverses $1$ pillar |\n| $2$ | Stops at pillar $2$, traverses $0$ pillars | Stops at pillar $2$, traverses $0$ pillars |\n| $3$ | Stops at pillar $1$, traverses $2$ pillars | Stops at pillar $5$, traverses $2$ pillars |\n| $4$ | Stops at pillar $4$, traverses $0$ pillars | Stops at pillar $4$, traverses $0$ pillars |\n| $5$ | Stops at pillar $4$, traverses $1$ pillar | Stops at pillar $5$, traverses $0$ pillars |\n\n### Constraints\n\nFor all test data: $1 \\leq n \\leq 300$, $1 \\leq A_i \\leq B_i \\leq 10^9$.\n\nSpecific constraints for each test point are shown in the following table:\n\n| Test Point | $n\\leq$ | Special Property |\n| :--------: | :-----: | :--------------: |\n| $1,2$ | $7$ | $A_i=B_i, B_i\\leq 7$ |\n| $3,4$ | $7$ | $B_i\\leq 7$ |\n| $5,6,7$ | $50$ | $B_i\\leq 100$ |\n| $8,9,10$ | $300$ | $B_i\\leq 10^4$ |\n| $11,12$ | $50$ | $A_i=1, B_i=10^9$ |\n| $13,14,15$ | $50$ | None |\n| $16,17$ | $150$ | None |\n| $18,19$ | $200$ | None |\n| $20$ | $300$ | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2294, "prompt": "### Problem Background\nIn the year $5801$, humans from Earth migrated to the second planet of Alpha Tauri, where they proclaimed the founding declaration of the Galactic Federation. That year was renamed to Year 1 of the Cosmic Calendar, and humanity began expanding toward the depths of the Milky Way galaxy.\n\nIn Year $799$ of the Cosmic Calendar, a war broke out in the Bamilion Starzone between two major military factions of the galaxy. The faction \"Mountain Crushing Alliance\" dispatched a fleet of over one hundred thousand warships led by Fleet Commander Reinhard. Their opponent, \"River Sweeping Alliance,\" sent thirty thousand warships under the command of Yang Wenli to face them.\n\n### Problem Description\nYang Wenli is skilled in strategic warfare and adept at utilizing various tactics to achieve victories against larger forces. Inevitably, he developed some complacency. In this decisive battle, he divided the battlefield in the Bamilion Starzone into $30000$ columns, numbered sequentially as $1, 2, \\ldots, 30000$. He also numbered his warships from $1, 2, \\ldots, 30000$, such that the $i$-th warship was initially positioned in the $i$-th column, forming a \"long snake array\" to lure the enemy into advancing recklessly. This was the initial formation. \n\nWhen the enemy advanced, Yang Wenli issued a series of merge commands to consolidate most of his warships into a few columns in order to launch concentrated attacks. The merge command has the format `M i j`, which means that the entire warship sequence in the same column as Warship $i$ (ordered from front to back) is appended to the end of the warship sequence in the same column as Warship $j$. Naturally, each column consists of one or more warships. The execution of the merge command increases the size of the resulting column. \n\nHowever, Reinhard, with his strategic ingenuity, had already gained an upper hand. During the battle, he utilized an extensive intelligence network to eavesdrop on Yang Wenli's fleet movement commands.\n\nAs Yang Wenli issued commands to maneuver his fleet, Reinhard also issued query commands: `C i j`. Each query asks whether Warship $i$ and Warship $j$ are currently in the same column, and if they are, how many warships are positioned between them.\n\nAs a skilled software developer, you are tasked with writing a program to analyze and process Yang Wenli's commands while responding to Reinhard's queries.\n\n### Input Format\nThe first line contains an integer $T$, denoting the total number of commands.\n\nThe following $T$ lines contain one command per line. Each command follows one of the two formats below:\n\n1. `M i j`: Here, $i$ and $j$ are integers representing warship identifiers. This is a merge command issued by Yang Wenli, and it is guaranteed that Warships $i$ and $j$ are not in the same column.\n2. `C i j`: Here, $i$ and $j$ are integers representing warship identifiers. This is a query command issued by Reinhard.\n\n### Output Format\nFor each command:\n\n- If it is a merge command (`M i j`) issued by Yang Wenli, it indicates that the fleet's arrangement has changed. Your program should process this command, but no output is required.\n- If it is a query command (`C i j`) issued by Reinhard, your program should output a single integer:\n - If Warship $i$ and Warship $j$ are not in the same column, output `-1`.\n - If Warship $i$ and Warship $j$ are in the same column, output the number of warships positioned between them.\n\n### Sample\nThe following illustrates the configuration of the warship positions. Numbers in the table refer to the identifiers of the warships.\n\n| | Column 1 | Column 2 | Column 3 | Column 4 | $\\dots$ |\n| - | - | - | - | - | - |\n| Initial State | $1$ | $2$ | $3$ | $4$ | $\\dots$ |\n| `M 2 3` | $1$ | | $3$
$2$ | $4$ | $\\dots$ |\n| `C 1 2` | Warship $1$ and $2$ are not in the same column, output `-1` |\n| `M 2 4` | $1$ | | | $4$
$3$
$2$ | $\\dots$ |\n| `C 4 2` | Warship $4$ and $2$ are in the same column, and only Warship $3$ is between them. Output `1` |\n\n### Constraints and Notes\nFor $100\\%$ of the test cases:\n- $1 \\leq T \\leq 5 \\times 10^5$\n- $1 \\leq i, j \\leq 30000$\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3534, "prompt": "### Problem Description\n\nCountry C is a prosperous nation consisting of $n$ cities and $m$ directed roads, with cities numbered from $1$ to $n$. If one can travel from city $x$ to city $y$ using a series of roads, we say that city $x$ is reachable to city $y$, denoted as $x \\Rightarrow y$. The roads of Country C have a unique property: for any three cities $x$, $y$, $z$, if $x \\Rightarrow z$ and $y \\Rightarrow z$, then $x \\Rightarrow y$ or $y \\Rightarrow x$.\n\nA month from now is the millennium anniversary of Country C's founding, and its citizens are preparing for a grand parade celebration. Currently, Country C has $q$ parade plans, and for the $i$-th plan, the parade hopes to start at city $s_i$ and end at city $t_i$ after passing through several cities. During the parade, **a city can be visited multiple times**. To make the parade more exciting, each parade will **temporarily** construct $k$ ($0 \\leq k \\leq 2$) directed roads specifically for this parade, meaning other parades cannot use the newly built roads.\n\nNow, Country C wants to know how many cities each parade plan could **possibly pass through**.\n\nNote: The temporarily constructed roads **do not need to satisfy the original properties of Country C's roads**.\n\n### Input Format\n\nThe first line contains four integers $n$, $m$, $q$, $k$, representing the number of cities, number of roads, number of parade plans, and the number of temporarily constructed roads per parade, respectively.\n\nThe next $m$ lines each contain two integers $u, v$, representing a directed road $u \\rightarrow v$.\n\nThe next $q$ lines each begin with two integers $s_i, t_i$, representing the starting city and ending city of the parade. These lines also contain $k$ pairs of integers $a, b$, each pair representing a temporarily added directed road $a \\rightarrow b$.\n\nIt is guaranteed that if the original directed roads of Country C are treated as undirected roads, all cities are mutually reachable.\n\n### Output Format\n\nFor each query, output a single integer on a new line representing the answer. If a parade cannot reach the destination from the starting point, output $0$.\n\n### **Sample Explanation #1**\n\nFor the first parade plan, the starting city is city $1$, the ending city is city $4$, and the temporarily constructed road is $5 \\rightarrow 1$. The cities that can possibly be passed are $\\{1, 2, 4, 5\\}$.\n\nFor the second parade plan, the starting city is city $2$, the ending city is city $3$, and the temporarily constructed road is $5 \\rightarrow 3$. The cities that can possibly be passed are $\\{2, 3, 4, 5\\}$.\n\nFor the third parade plan, the starting city is city $1$, the ending city is city $2$, and the temporarily constructed road is $5 \\rightarrow 2$. The cities that can possibly be passed are $\\{1, 2, 4, 5\\}$.\n\nFor the fourth parade plan, the starting city is city $3$, the ending city is city $4$, and the temporarily constructed road is $5 \\rightarrow 1$. Starting from city $3$, it is not possible to reach city $4$.\n\n### **Sample #2**\n\nSee attachments `celebration/celebration2.in` and `celebration/celebration2.ans`.\n\nThis sample corresponds to the constraints of test cases $5 \\sim 7$.\n\n### **Sample #3**\n\nSee attachments `celebration/celebration3.in` and `celebration/celebration3.ans`.\n\nThis sample corresponds to the constraints of test cases $10 \\sim 11$.\n\n### **Sample #4**\n\nSee attachments `celebration/celebration4.in` and `celebration/celebration4.ans`.\n\nThis sample corresponds to the constraints of test cases $15 \\sim 16$.\n\n### **Sample #5**\n\nSee attachments `celebration/celebration5.in` and `celebration/celebration5.ans`.\n\nThis sample corresponds to the constraints of test cases $20 \\sim 25$.\n\n### **Constraints**\n\nFor all test cases, $1 \\leq n, q \\leq 3 \\times {10}^5$, $n - 1 \\leq m \\leq 6 \\times {10}^5$, $0 \\leq k \\leq 2$.\n\n| Test Case ID | $n, q \\leq$ | $k$ | Special Property |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 4$ | $5$ | $= 0$ | None |\n| $5 \\sim 7$ | $1000$ | $\\leq 2$ | None |\n| $8 \\sim 9$ | $3 \\times {10}^5$ | $= 0$ | $m = n - 1$ |\n| $10 \\sim 11$ | $3 \\times {10}^5$ | $= 1$ | $m = n - 1$ |\n| $12 \\sim 14$ | $3 \\times {10}^5$ | $= 2$ | $m = n - 1$ |\n| $15 \\sim 16$ | $3 \\times {10}^5$ | $= 0$ | None |\n| $17 \\sim 19$ | $3 \\times {10}^5$ | $= 1$ | None |\n| $20 \\sim 25$ | $3 \\times {10}^5$ | $= 2$ | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3340, "prompt": "### Problem Description\n**Hint**: At the end of the problem description, we provide a brief, formal description of the task.\n\nIn the distant future, physicists have finally discovered the natural laws of time and causality. Even before someone is born, we can theoretically analyze their life's outcomes. In other words, physics allows us to \"predict\" someone's \"destiny\" to some extent.\n\nSimply put, a person's destiny is a rooted tree $T$ composed of time points: the root node represents birth, and the leaf nodes represent death. Every non-leaf node $u$ has one or more children $v_1, v_2, \\dots, v_{c_u}$, indicating the $c_u$ different choices the person can make at the time point $u$ that lead to different possibilities. Formally, a **choice** is represented by an edge $(u, v_i)$ in the tree, where $u$ is the parent of $v_i$.\n\nA person's lifetime is a path from birth (the root node) to death (a certain leaf node), and this path includes no repeated nodes. Any subpath on the lifetime path that contains at least one edge is considered a segment of the person's **life experience**. The set of all life experiences this person could possibly have, formed by all possible ways they might live, is called **potential life experiences**. In other words, the set of all potential life experiences consists of all paths $(u, v)$ in the tree $T$, where $u \\neq v$ and $u$ is an ancestor of $v$. Mathematically, these potential life experiences are denoted as ordered pairs $(u, v)$, and the set of all such experiences in the tree $T$ is denoted as $\\mathcal{P}_T$.\n\nPhysics not only allows us to observe the tree representing destiny but also lets us analyze whether certain potential life experiences are \"important.\" Every choice someone makes\u2014i.e., every edge in the tree\u2014can be **important** or **not important**. A potential life experience is considered important if and only if there exists at least one edge in its corresponding path that is labeled as important. We can observe that some potential life experiences are important. In other words, we are given a set $\\mathcal{Q} \\subseteq \\mathcal{P}_T$, where each potential life experience $(u, v) \\in \\mathcal{Q}$ is important.\n\nThe structure of the tree $T$ has already been computed, and the set $\\mathcal{Q}$ has been observed. While the uncertainty in someone's destiny has greatly been reduced, it is still significant. Let's compute it: given the tree $T$ and the set $\\mathcal{Q}$, determine how many different ways there are to assign importance to the edges such that all constraints from the observed set $\\mathcal{Q}$ are satisfied. Specifically, for any $(u, v) \\in \\mathcal{Q}$, there must exist at least one edge on the path from $u$ to $v$ that is marked as important.\n\n**Formal Description**: Given a tree $T = (V, E)$ and a point pair set $\\mathcal{Q} \\subseteq V \\times V$, where for all $(u, v) \\in \\mathcal{Q}$, $u \\neq v$, and $u$ is an ancestor of $v$ in tree $T$. $V$ and $E$ denote the sets of nodes and edges in tree $T$, respectively. Compute how many distinct functions $f: E \\rightarrow \\{0, 1\\}$ (assigning each edge $e \\in E$ a value of either $0$ or $1$) there are, satisfying that for any $(u, v) \\in \\mathcal{Q}$, there exists at least one edge $e$ on the path from $u$ to $v$ such that $f(e) = 1$. Since the result may be very large, output the result modulo $998,244,353$ (a prime number).\n\n### Input Format\nRead data from the file `destiny.in`.\n\n- The first line contains a positive integer $n$, indicating the size of the tree $T$. The nodes in the tree are numbered from $1$ to $n$, with node $1$ being the root.\n- The next $n - 1$ lines each contain two space-separated integers $x_i$ and $y_i$ satisfying $1 \\leq x_i, y_i \\leq n$, indicating that there is an edge between nodes $x_i$ and $y_i$. Note that the edges may not be oriented.\n- The next line contains a non-negative integer $m$, indicating the number of observed pieces of information.\n- The next $m$ lines each contain two space-separated integers $u_i$ and $v_i$, indicating $(u_i, v_i) \\in \\mathcal{Q}$. **Note**: the input data may contain duplicates, meaning there may exist $i \\neq j$ such that $u_i = u_j$ and $v_i = v_j$.\n\nThe input size and constraints are summarized in the table at the end of this document.\n\n### Output Format\nWrite the output to the file `destiny.out`.\n\n- Output contains only one integer, representing the number of valid assignments modulo $998,244,353$.\n\n---\n\n### Example 1\nThere are $16$ possible assignments, of which the following $6$ are invalid:\n\n- $(1, 2), (2, 3), (3, 5)$ are marked as not important, while $(3, 4)$ is marked as important: no constraints in $\\mathcal{Q}$ are satisfied.\n- $(1, 2), (2, 3), (3, 4), (3, 5)$ are all marked as not important: no constraints in $\\mathcal{Q}$ are satisfied.\n- $(1, 2), (2, 3)$ are marked as not important, while $(3, 4), (3, 5)$ are marked as important: the constraint $(1, 3)$ in $\\mathcal{Q}$ is not satisfied.\n- $(1, 2), (2, 3), (3, 4)$ are marked as not important, while $(3, 5)$ is marked as important: the constraint $(1, 3)$ in $\\mathcal{Q}$ is not satisfied.\n- $(2, 3), (3, 5)$ are marked as not important, while $(1, 2), (3, 4)$ are marked as important: the constraint $(2, 5)$ in $\\mathcal{Q}$ is not satisfied.\n- $(2, 3), (3, 4), (3, 5)$ are marked as not important, while $(1, 2)$ is marked as important: the constraint $(2, 5)$ in $\\mathcal{Q}$ is not satisfied.\n\nUnder other assignments, all constraints imposed by $\\mathcal{Q}$ are satisfied.\n\n---\n\n### Example 2\nSee the attached files `destiny3.in` and `destiny3.ans`.\n\n---\n\nSee the attached files `destiny4.in` and `destiny4.ans`.\n\n---\n\n### Data Constraints and Hints\n\n| Test Case ID | $n$ | $m$ | $T$ is a complete binary tree |\n| :----------: | :-----------------: | :-----------------: | :---------------------------: |\n| $1$ | $\\leq 10$ | $\\leq 10$ | No |\n| $2$ | $\\leq 10$ | $\\leq 10$ | No |\n| $3$ | $\\leq 10$ | $\\leq 10$ | No |\n| $4$ | $\\leq 10$ | $\\leq 10$ | No |\n| $5$ | $\\leq 500$ | $\\leq 15$ | No |\n| $6$ | $\\leq 10^4$ | $\\leq 10$ | No |\n| $7$ | $\\leq 10^5$ | $\\leq 16$ | No |\n| $8$ | $\\leq 5 \\times 10^5$ | $\\leq 16$ | No |\n| $9$ | $\\leq 10^5$ | $\\leq 22$ | No |\n| $10$ | $\\leq 5 \\times 10^5$ | $\\leq 22$ | No |\n| $11$ | $\\leq 600$ | $\\leq 600$ | No |\n| $12$ | $\\leq 1000$ | $\\leq 1000$ | No |\n| $13$ | $\\leq 2000$ | $\\leq 5 \\times 10^5$ | No |\n| $14$ | $\\leq 2000$ | $\\leq 5 \\times 10^5$ | No |\n| $15$ | $\\leq 5 \\times 10^5$ | $\\leq 2000$ | No |\n| $16$ | $\\leq 5 \\times 10^5$ | $\\leq 2000$ | No |\n| $17$ | $\\leq 10^5$ | $\\leq 10^5$ | Yes |\n| $18$ | $\\leq 10^5$ | $\\leq 10^5$ | Yes |\n| $19$ | $\\leq 5 \\times 10^4$ | $\\leq 10^5$ | No |\n| $20$ | $\\leq 8 \\times 10^4$ | $\\leq 10^5$ | No |\n| $21$ | $\\leq 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $22$ | $\\leq 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $23$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $24$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $25$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ | No |\n\n**All constraints satisfy**: $n \\leq 5 \\times 10^5$, $m \\leq 5 \\times 10^5$. The input forms a valid tree, and for $1 \\leq i \\leq m$, it is always true that $u_i$ is an ancestor of $v_i$.\n\n**Complete Binary Tree**: In this problem, a complete binary tree is defined as a tree where each non-leaf node has left and right children, and all leaf nodes have the same depth. A tree constructed by numbering the nodes of a full binary tree in top-to-bottom, left-to-right order, and taking the smallest numbered nodes forms a complete binary tree.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2604, "prompt": "### Problem Description\nA and B have decided to travel during their vacation. The cities they want to visit are numbered from $1$ to $N$, where cities with smaller numbers are located west of cities with larger numbers. The altitude of each city is unique, and the altitude of city $i$ is denoted as $H_i$. The distance $d_{i, j}$ between two cities $i$ and $j$ is the absolute difference of their altitudes, i.e., $d_{i, j} = |H_i - H_j|$.\n\nDuring their trip, A and B take turns driving. A drives on the first day, then they alternate each subsequent day. They decide to start their journey from a city $S$ and always head east, traveling at most $X$ kilometers before ending the trip. A and B have different driving styles: B always chooses the nearest city (in terms of distance) in the forward direction as their destination, while A chooses the second nearest city (also in the forward direction) as their destination. **Note:** If two cities are at the same distance from the current city, the city with the lower altitude is considered closer. If either person cannot choose a destination according to their principles, or reaching their chosen destination would exceed the maximum distance $X$, they end the trip. \n\nBefore departing, A wants to know the answers to two questions:\n\n1. For a given $X = X_0$, which city should they start from to minimize the ratio of total distance traveled by A to the total distance traveled by B (if B's total distance is $0$, the ratio is considered infinite, and two infinite values are regarded as equal)? If multiple starting cities result in the same minimum ratio, output the city with the highest altitude.\n2. For any given $X = X_i$ and starting city $S_i$, calculate the total distances traveled by A and B.\n\n---\n\n### Input Format\n\n- The first line contains an integer $N$, denoting the number of cities.\n- The second line contains $N$ integers separated by spaces, representing the altitudes of cities $1$ to $N$, i.e., $H_1, H_2, \\dots, H_N$, where each $H_i$ is unique.\n- The third line contains an integer $X_0$.\n- The fourth line contains an integer $M$, denoting the number of queries regarding $S_i$ and $X_i$.\n- The next $M$ lines each contain two integers $S_i$ and $X_i$, representing the starting city $S_i$ and the maximum distance $X_i$.\n\n---\n\n### Output Format\n\n- The first line contains an integer $S_0$, representing the city index where the ratio of distances traveled by A to B is minimized for $X_0$. If multiple cities lead to the same minimum ratio, choose the city with the highest altitude.\n- The next $M$ lines each contain two integers separated by a space, representing the total distance traveled by A and the total distance traveled by B for the given $S_i$ and $X_i$.\n\n---\n\n### Example 1\n![drive.png](https://img.loj.ac.cn/2021/12/29/5417cef0899f3.png)\n\nThe altitude and distances between cities are as shown in the figure above.\n\n- If starting from city $1$, the reachable cities are $2$, $3$, and $4$, with distances $1$, $1$, and $2$, respectively. Since city $3$ has a lower altitude than city $2$, city $3$ is considered closer to city $1$, and city $2$ is considered the second closest, so A travels to city $2$. From city $2$, the reachable cities are $3$ and $4$, with distances $2$ and $1$, respectively, so B travels to city $4$. From city $4$, no further cities can be reached, and the trip ends.\n- If starting from city $2$, the reachable cities are $3$ and $4$, with distances $2$ and $1$, respectively. Since city $3$ is the second closest, A travels to city $3$. From city $3$, the only remaining city is $4$, but traveling to city $4 would result in a total distance of $2+3=5 > X_0=3$, so B ends the trip at city $3$.\n- If starting from city $3$, the only reachable city is $4$, but since no city is considered second closest to city $3$, the trip ends before it begins.\n- If starting from city $4$, no cities can be reached, and the trip ends before it begins.\n\n---\n\n### Example 2\nWhen $X = 7$:\n- Starting from city $1$, the route is $1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 8 \\rightarrow 9$. A travels a distance of $1 + 2 = 3$, while B travels a distance of $1 + 1 = 2$ (at city $1$, A first chooses city $2 over city $6 since city $2$ has a higher altitude; at city $9$, A cannot make a second choice, ending the trip).\n- Starting from city $2$, the route is $2 \\rightarrow 6 \\rightarrow 7$. A and B travel distances of $2$ and $4$, respectively.\n- Starting from city $3$, the route is $3 \\rightarrow 8 \\rightarrow 9$. A and B travel distances of $2$ and $1$, respectively.\n- Starting from city $4$, the route is $4 \\rightarrow 6 \\rightarrow 7$. A and B travel distances of $2$ and $4$, respectively.\n- Starting from city $5$, the route is $5 \\rightarrow 7 \\rightarrow 8$. A and B travel distances of $5$ and $1$, respectively.\n- Starting from city $6$, the route is $6 \\rightarrow 8 \\rightarrow 9$. A and B travel distances of $5$ and $1$, respectively.\n- Starting from city $7$, the route is $7 \\rightarrow 9 \\rightarrow 10$. A and B travel distances of $2$ and $1$, respectively.\n- Starting from city $8$, the route is $8 \\rightarrow 10$. A and B travel distances of $2$ and $0$, respectively.\n- Starting from city $9$, the route is just $9$. A and B travel distances of $0$ and $0`, respectively (the trip ends before it starts).\n- Starting from city $10$, the route is just $10`. A and B travel distances of $0` and $0`, respectively.\n\nStarting from cities $2$ or $4$, the ratio of A's total distance to B's total distance is minimized. Since city $2$ has a higher altitude, the output for the first line is `2`.\n\n---\n\n### Constraints and Hints\n\n- For 30% of the data: $1 \\leq N \\leq 20$, $1 \\leq M \\leq 20$\n- For 40% of the data: $1 \\leq N \\leq 100$, $1 \\leq M \\leq 100$\n- For 50% of the data: $1 \\leq N \\leq 100$, $1 \\leq M \\leq 1,000$\n- For 70% of the data: $1 \\leq N \\leq 1,000$, $1 \\leq M \\leq 10,000$\n- For 100% of the data: $1 \\leq N \\leq 100,000$, $1 \\leq M \\leq 10,000$, $|H_i| \\leq 10^9$, $0 \\leq X_i \\leq 10^9$ for all $i \\geq 0$, $1 \\leq S_i \\leq N$ for all $i \\geq 1$. It is guaranteed that all $H_i$ are unique.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2498, "prompt": "## Problem Description\n\nRock-Paper-Scissors is a common hand game: rock beats scissors, scissors beats paper, and paper beats rock. If both players use the same gesture, the game ends in a draw. In Season 2, Episode $8$ of *The Big Bang Theory*, an enhanced version of Rock-Paper-Scissors was introduced.\n\nThe enhanced version extends the traditional game by adding two new gestures:\n\n- **Spock**: A character from *Star Trek*. \n- **Lizard**: A villain from *Star Trek*.\n\nThe winning relationships among the five gestures are shown in Table 1, which describes the result of Player A versus Player B.\n\n| A \\ B | Scissors | Rock | Paper | Lizard | Spock |\n|:--------:|:--------:|:-----:|:-----:|:------:|:------:|\n| Scissors | Draw | Lose | Win | Win | Lose |\n| Rock | - | Draw | Lose | Win | Lose |\n| Paper | - | - | Draw | Lose | Win |\n| Lizard | - | - | - | Draw | Win |\n| Spock | - | - | - | - | Draw |\n\nNow, Player A and Player B want to try this enhanced version of the hand game. It is known that both players play according to a periodic pattern, but the cycle lengths of their patterns may differ. For example, if Player A plays with a period of length $6$ as \"Rock - Paper - Rock - Scissors - Lizard - Spock\", Player A's play sequence would be \"Rock - Paper - Rock - Scissors - Lizard - Spock - Rock - Paper - Rock - Scissors - Lizard - Spock - ...\". If Player B plays with a period of length $5$ as \"Scissors - Rock - Paper - Spock - Lizard\", Player B's play sequence would be \"Scissors - Rock - Paper - Spock - Lizard - Scissors - Rock - Paper - Spock - Lizard - ...\".\n\nGiven that Player A and Player B play against each other $N$ times, the winner of each match earns $1$ point, while the loser earns $0$ points. If the match is a draw, neither player earns any points. Your task is to compute the scores of Player A and Player B after $N$ matches.\n\n---\n\n## Input Format\n\nThe first line contains three integers: $N, N_A, N_B$, which represent the total number of matches ($N$), the length of Player A's gesture cycle ($N_A$), and the length of Player B's gesture cycle ($N_B$). The numbers are separated by a single space.\n\nThe second line contains $N_A$ integers, representing the periodic pattern of Player A's gestures. \nThe third line contains $N_B$ integers, representing the periodic pattern of Player B's gestures. \n\nIn both sequences: \n- $0$ represents \"Scissors\", \n- $1$ represents \"Rock\", \n- $2$ represents \"Paper\", \n- $3$ represents \"Lizard\", \n- $4$ represents \"Spock\". \n\nThe numbers are separated by a single space.\n\n---\n\n## Output Format\n\nOutput a single line containing two integers, separated by a single space, representing the scores of Player A and Player B, respectively.\n\n---\n\n## Sample Input 1\n\n```plaintext\n10 3 2\n0 1 2\n3 4\n```\n\n## Sample Output 1\n\n```plaintext\n7 3\n```\n\n---\n\n## Sample Input 2\n\n```plaintext\n6 6 6\n0 1 2 3 4 0\n0 1 2 3 4 0\n```\n\n## Sample Output 2\n\n```plaintext\n0 0\n```\n\n---\n\n## Constraints and Notes\n\n- $0 < N \\leq 200$ \n- $0 < N_A \\leq 200$ \n- $0 < N_B \\leq 200$ \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2359, "prompt": "### Problem Description\n\nLittle C finds running very interesting, so he decided to create a game called *\"Run & Fun Everyday\"*. *\"Run & Fun Everyday\"* is a simulation game where players need to log in every day and complete check-in tasks.\n\nThe game map can be represented as a tree with $n$ nodes and $n - 1$ edges. Each edge connects two nodes on the tree, and any two nodes are connected by a unique path. The nodes of the tree are numbered from $1$ to $n$ as consecutive positive integers.\n\nThere are $m$ players, and the $i$-th player's starting point is $S_i$, and their destination is $T_i$. At the start of the daily check-in task at second $0$, all players simultaneously start from their starting points and move at a speed of one edge per second along the shortest path toward their respective destinations. Once a player reaches their destination, the player completes the check-in task. (Since the map is a tree, each player's path is unique.)\n\nLittle C wants to measure the game's activity level by placing an observer at each node. The observer at node $j$ will observe players at the $W_j$ second. A player can be observed by the observer at node $j$ if and only if the player is at node $j$ exactly at the $W_j$ second. Little C wants to know how many players each observer will observe.\n\n**Note:** A player is considered to have finished the game once they reach their destination, and they cannot wait at their destination to be observed. That is, for a player with node $j$ as their destination:\n- If the player arrives at their destination before the $W_j$ second, the observer at node $j$ cannot observe this player.\n- If the player arrives at their destination exactly at the $W_j$ second, the observer at node $j$ can observe this player.\n\n---\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, where $n$ represents the number of nodes in the tree (and also the number of observers), and $m$ represents the number of players.\n\nThe next $n - 1$ lines each contain two integers $u$ and $v$, indicating that there is an edge between node $u$ and node $v$.\n\nThe next line contains $n$ integers, where the $i$-th integer is $W_i$, representing the observation time for the observer at node $i$.\n\nThe following $m$ lines each contain two integers $S_i$ and $T_i$, representing the starting point and destination of a player.\n\nIt is guaranteed that $1 \\leq S_i, T_i \\leq n, 0 \\leq W_j \\leq n$ for all input data.\n\n---\n\n### Output Format\n\nOutput a single line with $n$ integers, where the $j$-th integer represents the number of players the observer at node $j$ can observe.\n\n---\n\n### Sample Input 1\n\n```\n6 3\n1 2\n1 3\n1 4\n4 5\n4 6\n0 2 5 4 4 6\n1 4\n5 1\n6 6\n```\n\n### Sample Output 1\n\n```\n2 0 0 1 1 1\n```\n\n**Explanation:**\n\n- For node $1$, $W_1 = 0$. Only players who start at node $1$ can be observed by the observer. Players $1$ and $2$ are observed, so a total of $2$ players are observed.\n- For node $2$, no player is at this node at the $2$-second mark, so $0$ players are observed.\n- For node $3$, no player is at this node at the $5$-second mark, so $0$ players are observed.\n- For node $4$, player $1$ is observed, so $1$ player is observed in total.\n- For node $5$, player $1$ is observed, so $1$ player is observed in total.\n- For node $6$, player $3$ is observed, so $1$ player is observed in total.\n\n---\n\n### Sample Input 2\n\n```\n5 5\n1 2\n2 3\n3 4\n4 5\n0 1 2 3 4\n1 1\n2 2\n3 3\n4 4\n5 5\n```\n\n### Sample Output 2\n\n```\n1 1 1 1 1\n```\n\n---\n\n### Constraints and Hints\n\n- **Test Case $1 \\sim 2$:** $n = m = 991$. All players start at their own destinations, i.e., $S_i = T_i$.\n- **Test Case $3 \\sim 4$:** $n = m = 992$, and $W_j = 0$ for all $j$.\n- **Test Case $5$:** $n = m = 993$.\n- **Test Case $6 \\sim 8$:** $n = m = 99994$, and the tree degenerates into a straight line. For $1 \\leq i < n$, there is an edge between $i$ and $i + 1$.\n- **Test Case $9 \\sim 12$:** $n = m = 99995$, with $S_i = 1$ for all players.\n- **Test Case $13 \\sim 16$:** $n = m = 99996$, with $T_i = 1$ for all players.\n- **Test Case $17 \\sim 19$:** $n = m = 99997$.\n- **Test Case $20$:** $n = m = 299998$.\n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2134, "prompt": "### Problem Description\n\nThe gardener Mr. S is in charge of a field, which can be seen as a two-dimensional plane. There are $n$ wishing trees in the field, numbered as $1, 2, 3, \\ldots, n$. Each tree can be treated as a point in the plane, and the $i$-th tree ($1 \\leq i \\leq n$) is located at coordinates $(x_i, y_i)$. The coordinates of any two trees are distinct.\n\nVeteran driver Mr. P will set off from the origin $(0, 0)$ and perform several rounds of actions. In each round, Mr. P first chooses a direction that satisfies the following conditions:\n\n1. The direction is one of the following five options: left, right, up, 45\u00b0 up-left, or 45\u00b0 up-right.\n2. Moving along this direction allows him to reach a tree that he has not yet made a wish at.\n\nAfter choosing a direction, Mr. P will move along this direction in a straight line and must reach the nearest tree in this direction that he has not wished at. He will make a wish under this tree and move on to the next round. If no valid direction is available, he stops. He will adopt an optimal strategy to make wishes at as many trees as possible. If there are multiple optimal strategies, he can choose any one of them.\n\nUnfortunately, the gardener Mr. S finds that because the soil in the field is soft, Mr. P's car leaves wheel tracks on the field during each round of driving. A wheel track can be treated as a line segment with endpoints at two trees (or the origin and one tree).\n\nIn the future, many other wishing visitors plan to drive to the field to make wishes. These visitors will follow the same type of optimal strategy as Mr. P. Mr. S finds the wheel tracks in non-horizontal directions (i.e., up, 45\u00b0 up-left, 45\u00b0 up-right) visually unappealing. To maintain the appearance of the field, he plans to rent some rollers to flatten all ground that might leave \"non-horizontal wheel tracks\" before these visitors arrive.\n\nThe \"ground that might leave non-horizontal wheel tracks\" refers to some line segments in the field, each of which is included in the travel routes under certain optimal strategies. Each roller operates under the following conditions:\n\n1. It starts from the origin or any tree.\n2. It can only move in one of the following three directions: up, 45\u00b0 up-left, or 45\u00b0 up-right, and can only change direction or stop under a tree.\n3. It can only traverse the ground that might leave \"non-horizontal wheel tracks,\" but the same piece of ground can be traversed by multiple rollers.\n\nNow, Mr. P and Mr. S each have a question for you:\n\n1. For Mr. P, please provide any one optimal route.\n2. For Mr. S, tell him the minimum number of rollers he needs to rent.\n\n---\n\n### Input Format\n\nThe first line of the input file contains a positive integer $n$, representing the number of wishing trees. \nThe following $n$ lines each contain two integers $x_i$ and $y_i$, separated by a single space, representing the coordinates of the $i$-th wishing tree.\n\n---\n\n### Output Format\n\nThe output file consists of three lines: \n\nThe first line contains a single integer $m$, representing the maximum number of trees at which Mr. P can make wishes. \nThe second line contains $m$ integers separated by single spaces, representing the order in which Mr. P should make wishes at the trees. \nThe third line contains a single integer, representing the minimum number of rollers Mr. S needs to rent.\n\n---\n\n### Sample\n\nOptimal paths allow making wishes at three trees: \n$(0,0) \\rightarrow (1,1) \\rightarrow (-1,1) \\rightarrow (-2,2)$ or $(0,0) \\rightarrow (0,8) \\rightarrow (0,9) \\rightarrow (0,10)$.\n\nAt least three rollers are needed: \nRoutes are $(0,0) \\rightarrow (1,1)$, $(-1,1) \\rightarrow (-2,2)$, and $(0,0) \\rightarrow (0,8) \\rightarrow (0,9) \\rightarrow (0,10)$.\n\n---\n\n### Constraints and Hints\n\nFor all test cases, $n \\leq 50000$, $|x_i| \\leq 10^9$, $0 < y_i \\leq 10^9$.\n\nFor each test case:\n\n- If the output of the first line is correct, you will receive $20\\%$ of the points for that test case.\n- If the output of the second line is also correct, you will receive an additional $20\\%$ of the points.\n- If the third line is correct, you will receive the remaining $60\\%$ of the points.\n\nIt should be noted that **even if your program can only earn partial points, you must strictly follow the output format**; otherwise, your program will be judged as scoring $0$ points. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3898, "prompt": "### Problem Description\n\nCountry A and Country B are engaged in an intense war. Country A plans to build several military camps within its territory.\n\nThe territory of Country A consists of $n$ cities connected by $m$ bidirectional roads, such that **any two cities are directly or indirectly reachable** via these roads. Country A plans to select one or more cities (**at least one**) and construct a military camp in each selected city.\n\nIt is well known that communication between military camps is extremely important. However, Country A has received intelligence that Country B will soon attack one of Country A's roads, though the exact target is unknown. If Country B's attack succeeds, this road will be cut off, possibly causing two military camps in Country A to be unable to reach each other, which Country A must avoid at all costs. Therefore, Country A has decided to deploy troops to guard some roads (**one, more than one, or even none**). Country A is confident that the guarded roads will resist any attack from Country B and will not be cut off.\n\nCountry A hopes to devise a plan for constructing military camps and guarding roads such that no matter which road Country B attacks, it will not lead to any two military camps being unable to communicate with each other. Please help Country A calculate the number of such possible plans for constructing military camps and guarding roads. Since the number of plans can be very large, you only need to output the result modulo $1,000,000,007\\left(10^{9} + 7\\right)$. Two plans are considered different if and only if there exists at least one city where a military camp is built in one plan and not in the other, or at least one road where troops are deployed in one plan but not in the other.\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of cities and bidirectional roads.\n\nThe next $m$ lines each contain two positive integers $u_{i}$ and $v_{i}$, describing a bidirectional road connecting $u_{i}$ and $v_{i}$. It is guaranteed that there are no duplicate roads or self-loops.\n\n### Output Format\n\nOutput a single integer, which is the number of plans to construct military camps and guard roads, modulo $1,000,000,007\\left(10^{9} + 7\\right)$.\n\n### Sample Explanation\n\nCountry A has two cities connected by one road. All possible plans are as follows:\n\n- Build a military camp in city $1$, do not guard the road;\n- Build a military camp in city $1$, guard the road;\n- Build a military camp in city $2$, do not guard the road;\n- Build a military camp in city $2$, guard the road;\n- Build military camps in both cities $1$ and $2$, guard the road.\n\n### Constraints\n\nFor all test cases, it is guaranteed that $1 \\leq n \\leq 5 \\times 10^5$, $n - 1 \\leq m \\leq 10^6$, and $1 \\leq u_i, v_i \\leq n$, $u_i \\neq v_i$.\n\nThe details of the test cases' constraints are as follows:\n\n| Test Case ID | $n \\leq$ | $m \\leq$ | Special Condition |\n|:------------:|:--------:|:--------:|:-----------------:|\n| $1 \\sim 3$ | $8$ | $10$ | None |\n| $4 \\sim 7$ | $16$ | $25$ | None |\n| $8 \\sim 9$ | $3000$ | $5000$ | None |\n| $10 \\sim 11$ | $5 \\times 10^5$ | $10^6$ | Special Property $\\mathrm{A}$ |\n| $12 \\sim 14$ | $5 \\times 10^5$ | $10^6$ | $m = n - 1$ |\n| $15 \\sim 16$ | $5 \\times 10^5$ | $10^6$ | $m = n$ |\n| $17 \\sim 20$ | $5 \\times 10^5$ | $10^6$ | None |\n\nSpecial Property $\\mathrm{A}$: It is guaranteed that $m = n - 1$ and the $i$-th road connects city $i$ and city $i+1$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3762, "prompt": "### Problem Description\n\nIn 2010, the World Expo was held in Shanghai, China, attracting tens of millions of domestic and international visitors. During the summer holiday, little Z also visited the Shanghai Expo Park. She had heard of its crowdedness and was well-prepared for situations where it would take hours to queue for some pavilions. To make her Expo trip smoother and more enjoyable, she decided to plan a detailed travel route beforehand.\n\nLittle Z collected a map of the Expo Park and found that, overall, the park was a very narrow rectangular area, with each pavilion occupying a square of roughly the same size. Thus, the entire park can be viewed as a $n \\times m$ matrix ($n \\leq 3$), where each cell represents a themed pavilion.\n\nSince different pavilions vary in popularity, the queuing time differs accordingly. Based on statistical information, little Z marked each pavilion $(x, y)$ with $T_{x,y} = 0$ or $1$: if $T_{x,y} = 1$, the pavilion is highly popular and requires a long time to queue; if $T_{x,y} = 0$, the pavilion is relatively normal and requires little to no queuing. Little Z wants to plan a reasonable route that alternates between popular pavilions and ordinary ones, avoiding long queues caused by continuous visits to popular pavilions and preventing the trip from becoming monotonous by visiting only ordinary ones. Moreover, little Z is efficient and hopes to visit all pavilions without retracing her steps or wasting energy. Therefore, she wants her travel route to meet the following constraints:\n\n1. After visiting the pavilion at $(x, y)$, the next pavilion visited must be an unvisited adjacent pavilion $(x^\\prime, y^\\prime)$ such that $|x-x^\\prime|+|y-y^\\prime|=1$;\n2. The starting point of the route must lie on the boundary of the matrix, i.e., $x = 1$ or $x = n$ or $y = 1$ or $y = m$;\n\nShe has planned a 01 sequence $L$ of length $n \\times m$, where the pavilion $(x,y)$ visited at step $i$ must satisfy $T_{x,y}=L_i$.\n\nLittle Z wants to know how many different travel routes meet her requirements. Since the total number of feasible routes might be large, she only wants to know the count modulo $11,192,869$.\n\n### Input Format\n\nThe first line contains two positive integers $n, m$.\n\nThe next $n$ lines contain $m$ 01 integers each, where the $i$-th row and $j$-th column represents $T_{i,j}$.\n\nThe $(n+2)$-th line contains $n \\times m$ 01 integers, where the $i$-th number represents the value of $L_i$.\n\n### Output Format\n\nOutput a single integer, representing the total number of feasible travel routes modulo $11,192,869$.\n\n### Example\n\nThere are four feasible travel routes:\n\n$$\n\\begin{aligned}\n(1,1) \\to (1,2) \\to (2,2) \\to (2,1)\\\\\n(1,1) \\to (2,1) \\to (2,2) \\to (1,2)\\\\\n(2,2) \\to (1,2) \\to (1,1) \\to (2,1)\\\\\n(2,2) \\to (2,1) \\to (1,1) \\to (1,2)\n\\end{aligned}\n$$\n\n### Constraints and Hints\n\n- For $10\\%$ of the cases: $n=1$;\n- For $30\\%$ of the cases: $n=2$;\n- For $60\\%$ of the cases: $n=3$ and $20\\%$ of the cases have $T_{i,j}$ all equal to $0$;\n- For $100\\%$ of the cases: $m \\leq 50$, $L_i, T_{i,j} = 0$ or $1$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2607, "prompt": "### Problem Description\n\nCountry H has $n$ cities. These $n$ cities are connected by $n-1$ bidirectional roads, forming a tree structure. City $1$ is the capital of the country and also serves as the root node of the tree.\n\nA highly dangerous infectious disease outbreak has occurred in the capital. To control the epidemic and prevent it from spreading to the border cities (the cities represented by the leaf nodes), the authorities have decided to deploy the army to establish checkpoints in certain cities. Checkpoints must be placed such that every path from the capital to a border city goes through at least one checkpoint. Note that border cities are also allowed to have checkpoints, but the capital cannot have a checkpoint.\n\nIn certain cities of Country H, there are already some troops stationed, and a city may have multiple troops. Each troop can move freely between connected cities via the roads and establish a checkpoint in any city except the capital. A troop can only establish a checkpoint in one city. The time required for a troop to move from one city to another is equal to the length of the connecting road (in hours).\n\nYour task is to determine the minimum time (in hours) required to control the epidemic. Note that multiple troops can move simultaneously.\n\n### Input Format\n\nThe input consists of multiple lines:\n\n- The first line contains an integer $n$, representing the number of cities.\n- The next $n-1$ lines each contain three integers $u$, $v$, and $w$, separated by spaces, where $u$ and $v$ are the indices of two cities connected by a road of length $w$. The input guarantees that the given structure forms a tree and that City $1$ is the root node.\n- The following line contains an integer $m$, representing the number of troops.\n- The next line contains $m$ integers, separated by spaces, indicating the city indices where the $m$ troops are stationed.\n\n### Output Format\n\nOutput a single integer, representing the minimum time required to control the epidemic. If it is impossible to control the epidemic, output $-1$.\n\n### Sample Explanation\n\nThe first troop establishes a checkpoint at City $2$, while the second troop moves from City $2$ to City $3$ to establish a checkpoint. The total time required is $3$ hours.\n\n### Constraints and Hints\n\n**It is guaranteed that troops are not stationed in the capital.**\n\n- For $10\\%$ of the test cases, $n \\leq 10$.\n- For $20\\%$ of the test cases, $n \\leq 50$, $w < 10^5$.\n- For $30\\%$ of the test cases, $n \\leq 1,000$, $w < 10^6$.\n- For $40\\%$ of the test cases, $n \\leq 10,000$.\n- For $50\\%$ of the test cases, $n \\leq 50,000$.\n- **For $80\\%$ of the test cases, $n \\leq 100,000$.**\n\n- **For $100\\%$ of the test cases, $2 \\leq m \\leq n \\leq 300,000$, and $0 < w < 10^9$.**\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3159, "prompt": "### Problem Description\n\nThere are $n$ cities in the Kingdom of Fleas, numbered $1$ through $n$, with City $1$ being the capital. All cities are distributed within a $w \\times h$ grid. Each city has a unique integer coordinate $(x, y)$ such that $1 \\leq x \\leq w$ and $1 \\leq y \\leq h$. The coordinates of different cities are unique.\n\nThe Kingdom has $m$ jumping devices, numbered $1$ through $m$. The $i$-th jumping device is located in City $p_i$ and has parameters $t_i, L_i, R_i, D_i, U_i$. Using this jumping device, a flea can spend $t_i\\ (t_i > 0)$ units of time to jump from City $p_i$ to any city within the rectangular region where $L_i \\leq x \\leq R_i$ and $D_i \\leq y \\leq U_i\\ (1 \\leq L_i \\leq R_i \\leq w, 1 \\leq D_i \\leq U_i \\leq h)$. Note that a city may have multiple jumping devices or may not have any jumping devices at all.\n\nSince the distance between cities is large, fleas must rely on jumping devices for their travel. Specifically, a single trip involves passing through several cities, with the sequence of visited city numbers represented by $a_0, a_1, \\ldots, a_k$. The sequence of used jumping devices during the trip is represented by $b_1, b_2, \\ldots, b_k$. In this trip:\n\n- Each city may occur multiple times in the sequence $\\{a_j\\}$.\n- Each jumping device may occur multiple times in the sequence $\\{b_j\\}$.\n- For each $j \\ (1 \\leq j \\leq k)$, the jumping device $b_j$ is located in City $a_{j-1}$, and the flea can use this jumping device to jump to City $a_j$.\n\nThis is referred to as a trip from city $a_0$ to city $a_k$, involving $k$ jumps and costing a total of $\\sum_{i=1}^k t_{b_i}$ units of time.\n\nThe King of Fleas wants to know the minimum time needed to travel from the capital (City $1$) to each of the other cities in the kingdom. The king guarantees that for every city, there is at least one valid trip from the capital to that city.\n\n---\n\n### Input Format\n\nInput is read from the file `jump.in`.\n\nThe first line contains four integers $n, m, w, h$, whose meanings are explained in the problem description.\n\nThe next $n$ lines each contain two integers $x_i, y_i$, representing the coordinates of City $i$.\n\nThe next $m$ lines each contain six integers $p_i, t_i, L_i, R_i, D_i, U_i$, which represent the city where the $i$-th jumping device is located, the time required for the jump, and the rectangular region reachable by this device, respectively. These integers are explained in detail in the problem description.\n\n---\n\n### Output Format\n\nOutput to the file `jump.out`.\n\nThe output should contain $n - 1$ lines. Each line $i$ should consist of a single integer, representing the minimum time required to travel from the capital to City $i+1$.\n\n---\n\n### Example\n\nRefer to the attached files `jump/jump2.in` and `jump/jump2.ans`.\n\nIn this example, the data constraints are $n = 10^4, m = 2\\times 10^4, w = 10^4, h = 1$.\n\nRefer to the attached files `jump/jump3.in` and `jump/jump3.ans`.\n\nIn this example, the data constraints are $n = 10^4, m = 2\\times 10^4, w = 10^4, h = 10^4$.\n\n---\n\n### Constraints and Hints\n\nFor all test points and examples, the constraints satisfy:\n- $1 \\leq n \\leq 7\\times 10^4$\n- $1 \\leq m \\leq 1.5\\times 10^5$\n- $1 \\leq w, h \\leq n$\n- $1 \\leq t_i \\leq 10^4$\n\nDetailed restrictions for each test point are provided in the table below:\n\n| Test Point Number | $1\\leq n\\leq$ | $1\\leq m\\leq$ | Special Restrictions |\n| :---------------: | :--------------------------: | :------------------: | :----------------------------------------------------------------: |\n| $1\\sim 8$ | $100$ | $100$ | None |\n| $9\\sim 13$ | $5\\times 10^4$ | $10^5$ | Each jumping device can reach exactly one city, with $L_i = R_i, D_i = U_i$ |\n| $14\\sim 18$ | $5\\times 10^4$ | $10^5$ | $h=1$ |\n| $19\\sim 22$ | $2.5\\times 10^4$ | $5\\times 10^4$ | None |\n| $23\\sim 25$ | $7\\times 10^4$ | $1.5\\times 10^5$ | None |\n\n**Note: The memory limit for this problem is 128MB.**\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3388, "prompt": "### Problem Description\n\nLittle C is playing a ball-moving game. In front of him, there are $n + 1$ rods numbered from $1$ to $n + 1$. Rods $1$, $2$, ..., $n$ each have $m$ balls on them, stacked from bottom to top. Rod $n + 1$ initially has no balls. These $n \\times m$ balls come in $n$ different colors, with $m$ balls of each color.\n\nInitially, the balls on a rod may be of various colors. Little C's task is to move the balls such that all balls of the same color are grouped onto the same rod. This is the only goal, and there is no restriction on which rod each color ends up on.\n\nLittle C can achieve the goal using several operations. In one operation, he can move one ball from the top of one rod to the top of another rod. More specifically, to move a ball from rod $x$ to rod $y$, the following conditions must be met:\n\n1. Rod $x$ has at least one ball.\n2. Rod $y$ has at most $m - 1$ balls.\n3. Only the topmost ball of rod $x$ can be moved, and it must be placed on top of rod $y$.\n\nThe task itself is not very difficult to accomplish, but Little C has decided to challenge himself: in addition to achieving the objective, the total number of operations must not exceed $820,000$. In other words, Little C needs to achieve the goal in at most $820,000$ operations.\n\nLittle C is stuck with this problem, but he believes you are capable of solving it. Please provide an operation plan to achieve Little C's goal. There may be multiple valid solutions; you only need to provide one. It is guaranteed that at least one valid solution exists.\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, separated by a space, representing the number of ball colors and the number of balls of each color, respectively.\n\nThe next $n$ lines each contain $m$ integers separated by a single space. The integers on the $i$-th line, given in order from bottom to top, represent the colors of the balls on rod $i$.\n\n### Output Format\n\nThis problem uses a custom validator (special judge) for evaluation. \n\nThe first line of your output should contain a single integer $k$, representing the number of operations in your solution. You must ensure $0 \\le k \\le 820000$. \n\nThe next $k$ lines should each contain two integers $x$ and $y$, separated by a single space, indicating an operation where the topmost ball of rod $x$ is moved to the top of rod $y$. You must ensure $1 \\le x, y \\le n + 1$ and $x \\ne y$.\n\n**Example Explanation of Sample #1**\n\nThe contents of the rods are shown as follows, with balls listed from bottom to top:\n\n| Operation | Rod 1 | Rod 2 | Rod 3 |\n|:---------:|:-------------:|:-------------:|:-------------:|\n| Initial | $1\\ 1\\ 2$ | $2\\ 1\\ 2$ | |\n| $1\\ 3$ | $1\\ 1$ | $2\\ 1\\ 2$ | $2$ |\n| $2\\ 3$ | $1\\ 1$ | $2\\ 1$ | $2\\ 2$ |\n| $2\\ 3$ | $1\\ 1$ | $2$ | $2\\ 2\\ 1$ |\n| $3\\ 1$ | $1\\ 1\\ 1$ | $2$ | $2\\ 2$ |\n| $3\\ 2$ | $1\\ 1\\ 1$ | $2\\ 2$ | $2$ |\n| $3\\ 2$ | $1\\ 1\\ 1$ | $2\\ 2\\ 2$ | |\n\n### Constraints\n\n| Test Case | $n \\le$ | $m \\le$ |\n|:---------:|:-------:|:-------:|\n| $1 \\sim 2$| $2$ | $20$ |\n| $3 \\sim 5$| $10$ | $20$ |\n| $6 \\sim 8$| $50$ | $85$ |\n| $9 \\sim 14$| $50$ | $300$ |\n| $15 \\sim 20$| $50$ | $400$ |\n\nFor all test cases, it is guaranteed that $2 \\le n \\le 50$ and $2 \\le m \\le 400$.\n\n### Validator\n\nTo facilitate testing, a `checker.cpp` file is provided in the `ball` directory. You can compile this program and use it to validate your output file. Note that the checker used for local testing is not completely identical to the final evaluation checker. You also do not need to concern yourself with its code implementation.\n\nThe compilation command is: `g++ checker.cpp -o checker -std=c++11`.\n\nThe usage of the `checker` program is: `checker `. The arguments represent the input file and your output file, respectively.\n\nIf your output contains invalid numbers, the validator will give an appropriate error message. If your numbers are within valid ranges but your solution is incorrect, the validator will provide brief error information:\n\n1. `A x`, indicating that the $x$-th operation is invalid.\n2. `B x`, indicating that, after all operations, the balls on rod $x$ are not grouped correctly.\n\nIf your solution is correct, the validator will output `OK`.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2244, "prompt": "### Problem Description\n\nIn the 21st century, many people have developed a strange disorder called \"Getting Out of Bed Difficulty Syndrome.\" Its clinical manifestations include difficulty in getting out of bed and low energy after waking up. As a young and vibrant individual, atm has always been determined to fight against this syndrome. Through studying related literature, he has found the root cause of the disease: in the deep depths of the Pacific Ocean, there is a dragon named `drd` that holds the essence of sleep, allowing it to extend people's sleep indefinitely. It is because of `drd`'s actions that the syndrome has been intensifying and rapidly spreading across the world. To completely eliminate this disease, atm has decided to go underwater to defeat this dragon.\n\nAfter overcoming many challenges, atm finally arrived at the location of `drd` and is preparing for a difficult and arduous battle. The dragon `drd` possesses an extraordinary ability: its defensive mechanism can alter the damage it receives using certain operations. Specifically, the defensive mechanism of `drd` consists of **$n$ defense gates**. Each defense gate has an operation $\\mathrm{op}$ and a parameter $t$. The operation is guaranteed to be one of **OR**, **XOR**, or **AND**, and the parameter is a non-negative integer. If atm's attack power before passing through the gate is $x$, his attack power will become $x \\mathbin{\\mathrm{op}} t$ after passing through the gate. The total damage that `drd` receives is the attack power obtained by atm's initial attack power **after passing sequentially through all $n$ defense gates**.\n\nSince atm's abilities are limited, his initial attack power must be an integer between $0$ and $m$ inclusive (i.e., it must be one of $0, 1, \\dots, m$, though the attack power after passing the gates is not constrained by $m$). In order to conserve his strength, atm wants to choose an initial attack power such that the damage dealt to `drd` is maximized. Can you help him calculate the maximum damage that can be dealt to `drd` in a single attack?\n\n---\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, representing the number of defense gates `drd` has and the range of atm's initial attack power between $0$ and $m$, respectively. \n\nThe next $n$ lines describe each defense gate. Each line contains a string $\\mathrm{op}$ and a non-negative integer $t$, separated by a space. Here $\\mathrm{op}$ indicates the operation corresponding to the defense gate, and $t$ is its associated parameter.\n\n---\n\n### Output Format\n\nOutput a single integer on one line, representing the maximum damage that `drd` can receive in a single attack.\n\n---\n\n### Example\n\nSuppose the initial attack power is $4$, and the final attack power is computed as follows:\n\n- $4 \\ \\mathbin{\\mathrm{AND}} \\ 5 = 4$; \n- $4 \\ \\mathbin{\\mathrm{OR}} \\ 6 = 6$; \n- $6 \\ \\mathbin{\\mathrm{XOR}} \\ 7 = 1$.\n\nSimilarly, we can compute the final attack power for other initial values:\n- For initial attack powers of $1, 3, 5, 7, 9$, the final attack power is $0$.\n- For initial attack powers of $0, 2, 4, 6, 8, 10$, the final attack power is $1$. \n\nThus, the maximum damage dealt to `drd` in a single attack is $1$.\n\n---\n\n### Constraints and Hints\n\n\n\n| Case # | Scale of $n, m$ | Additional Constraints |\n|:-:|:-:|:-:|\n| 1 | $2 \\leq n \\leq 100, m = 0$ | - |\n| 2 | $2 \\leq n \\leq 1000, 1 \\leq m \\leq 1000$ | - |\n| 3 | $2 \\leq n \\leq 1000, 1 \\leq m \\leq 1000$ | - |\n| 4 | $2 \\leq n, m \\leq 10^5$ | One defense gate performs **AND 0** |\n| 5 | $2 \\leq n, m \\leq 10^5$ | All defense gates perform the same operation |\n| 6 | $2 \\leq n, m \\leq 10^5$ | - |\n| 7 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | All defense gates perform the same operation |\n| 8 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | - |\n| 9 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | - |\n| 10 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | - |\n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2595, "prompt": "### Problem Description\n\n![flow1.jpg](https://img.loj.ac.cn/2024/04/21/2659904243acb.jpg)\n\nIn a distant land, one side is a scenic lake, while the other is an endless desert. The administrative division of this country forms a perfect rectangle with $N$ rows and $M$ columns, as shown in the figure above. Each grid cell represents a city, and every city has an altitude value.\n\nTo ensure that all residents have access to clear lake water, water facilities need to be built in some cities. There are two types of water facilities: **Reservoirs** and **Water Transmission Stations**. The function of a reservoir is to pump lake water into the reservoir in the city it is located. As a result, reservoirs can only be built in cities located in the first row, which are adjacent to the lake. Water transmission stations, on the other hand, can transfer lake water from higher-altitude cities to lower-altitude ones through pipelines. Therefore, for a city to have a water transmission station, there must be an adjacent city (sharing a common edge) at a higher altitude that already has a water facility.\n\nSince the cities in the last row ($N$th row) are near the desert, which is the arid region of the country, it is required that every city in the $N$th row have a water facility. Can this requirement be satisfied? If yes, find the minimum number of reservoirs that need to be built. If not, calculate the number of cities in the arid region that cannot have water facilities.\n\n---\n\n### Input Format\n\nEach line of input contains integers separated by spaces.\n\n- The first line contains two positive integers $N$ and $M$, which specify the dimensions of the rectangle.\n- The next $N$ lines each contain $M$ positive integers, representing the altitude of each city.\n\n---\n\n### Output Format\n\nThe output consists of two lines:\n\n- If the requirement can be satisfied, the first line outputs an integer `1`, and the second line outputs a single integer, representing the minimum number of reservoirs that need to be built.\n- If the requirement cannot be satisfied, the first line outputs an integer `0`, and the second line outputs a single integer, representing the number of cities in the arid region that cannot have water facilities.\n\n---\n\n### Example 1\n\nIn this example, building a reservoir in the city with an altitude of $9$ will satisfy the requirement.\n\n---\n\n### Example 2\n\n![flow2.jpg](https://img.loj.ac.cn/2024/04/21/64305a51c5dd0.jpg)\n\nIn the figure above, building reservoirs in the three cities marked with bold outlines can satisfy the requirement. The water transmission stations originating from these three reservoirs to the arid region cities are marked with three different colors. Note that there may be multiple ways to construct the facilities.\n\n---\n\n### Constraints and Hints\n\nThe problem contains $10$ test cases. The constraints for each test case are given in the table below:\n\n| Test Case ID | Feasibility | $N$ | $M$ | \n| :----------: | :---------: | :-------: | :-------: | \n| 1 | Not Feasible | $\\le 10$ | $\\le 10$ | \n| 2 | Not Feasible | $\\le 100$ | $\\le 100$ | \n| 3 | Not Feasible | $\\le 500$ | $\\le 500$ | \n| 4 | Feasible | $=1$ | $\\le 10$ | \n| 5 | Feasible | $\\le 10$ | $\\le 10$ | \n| 6 | Feasible | $\\le 100$ | $\\le 20$ | \n| 7 | Feasible | $\\le 100$ | $\\le 50$ | \n| 8 | Feasible | $\\le 100$ | $\\le 100$ | \n| 9 | Feasible | $\\le 200$ | $\\le 200$ | \n| 10 | Feasible | $\\le 500$ | $\\le 500$ | \n\nFor all $10$ test cases, the altitude of each city does not exceed $10^6$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3848, "prompt": "### Problem Description\n\nYou are playing a mini-game called \"Remove Stones.\"\n\nThere are $n$ piles of stones arranged in a row, and the $i$-th pile contains $a_i$ stones. Your task is to remove all the stones through the following operations:\n\n- **Operation 1**: Choose one pile of stones and remove at least $2$ stones from it.\n- **Operation 2**: Choose a continuous interval of indices $[l, r]$ ($1 \\le l \\le r \\le n$) such that $r - l \\ge 2$, and remove exactly $1$ stone from each pile in this interval.\n\nYou may perform the above two types of operations in any order and as many times as you wish until no further operations can be performed. If you manage to remove all stones, you win the game.\n\nYou may have already started pondering over questions like \"how many distinct ways to perform the operations?\", but in practice, you always seem to lose the game. Thus, you decide to play a little trick: at the start of the game, you secretly hold $k$ extra stones in your hand. **Before performing any operations, you must distribute and add these $k$ stones into one or more piles of stones.** You hope this might increase your chances of winning, but you also understand that it could potentially make you lose in situations where you might have otherwise won.\n\nNow, you can freely choose an initial game configuration. Specifically, for each pile $a_i$, you can choose its initial number of stones to be any integer within the range $[l_i, r_i]$. You wish to calculate the number of distinct initial configurations where it is possible to have at least one winning strategy. Since the result can be very large, you only need to output the count modulo $({10}^9 + 7)$. **Two initial configurations are considered different if and only if there exists at least one $\\boldsymbol{1 \\le i \\le n}$ such that the two configurations have different values of $\\boldsymbol{a_i}$. Note that an \"initial configuration\" refers to the state before adding the $\\boldsymbol{k}$ stones.**\n\n### Input Format\n\n**There are multiple test cases in this problem.** The first line contains a positive integer $T$ denoting the number of test cases, followed by the descriptions of each test case.\n\nFor each test case:\n- The first line contains two integers $n$ and $k$, representing the number of piles and the number of extra stones to be added.\n- The next $n$ lines each contain two non-negative integers $l_i$ and $r_i$, representing the range of the number of stones in the $i$-th pile.\n\n### Output Format\n\nFor each test case, output a single integer on a separate line, representing the count of possible winning configurations modulo $({10}^9 + 7)$.\n\n### Sample Explanation #1\n\nThere are $2^4 = 16$ possible initial configurations. It can be proven that only the configurations $(0 \\ 0 \\ 0 \\ 0)$ and $(1 \\ 0 \\ 0 \\ 1)$ are unwinnable. In every other configuration, there exists at least one winning strategy. For example, when the initial configuration is $(1 \\ 0 \\ 1 \\ 0)$, you can place the $1$ stone in your hand into the second pile, resulting in the configuration $(1 \\ 1 \\ 1 \\ 0)$. You can then apply Operation 2 on the interval $[1, 3]$ to remove all the stones.\n\n----\n\n**Sample #2**\n\nSee the attached file `stone/stone2.in` and its corresponding answer `stone/stone2.ans`.\n\n----\n\n**Sample #3**\n\nSee the attached file `stone/stone3.in` and its corresponding answer `stone/stone3.ans`.\n\n----\n\n**Sample #4**\n\nSee the attached file `stone/stone4.in` and its corresponding answer `stone/stone4.ans`.\n\n----\n\n### Constraints\n\nFor $100\\%$ of the data, it is guaranteed that:\n\n- $T \\le 10$\n- $3 \\le n \\le 1000$\n- $0 \\le l_i \\le r_i \\le {10}^9$\n- $0 \\le k \\le 100$\n\n| Test Case ID | $n \\le$ | $k \\le$ | Special Conditions |\n|:-:|:-:|:-:|:-:|\n| 1 to 3 | 5 | 2 | $r_i \\le 5$ |\n| 4 to 5 | 1000 | 0 | $l_i = r_i$ |\n| 6 to 8 | 1000 | 100 | $l_i = r_i$ |\n| 9 to 11 | 1000 | 0 | None |\n| 12 to 13 | 1000 | 2 | None |\n| 14 to 15 | 1000 | 100 | $r_i \\le 10$ |\n| 16 to 20 | 1000 | 100 | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2671, "prompt": "### Problem Description\n\nDandan is highly enthusiastic about challenging himself. This summer vacation, he plans to cycle along the Sichuan-Tibet route from Chengdu to Lhasa. The Sichuan-Tibet route offers breathtaking scenery, but it also poses many challenges due to its varied road conditions. Since Dandan's physical stamina is limited, it is crucial for him to set a destination each day and allocate his energy wisely.\n\nThanks to his well-equipped bicycle, we can ignore friction from the bike itself and between the bike and the ground during his rides. Thus, on any given day, it is assumed that Dandan only expends energy overcoming air resistance. On a given day, he plans to ride across $N$ segments, where the road conditions are consistent within each segment. For the $i$-th segment, the road conditions are described by three parameters: $s_i$, $k_i$, and $v_i\u2032$. Here, $s_i$ represents the length of the segment, $k_i$ represents the air resistance coefficient for the segment, and $v_i\u2032$ represents the wind speed for the segment. ($v_i\u2032 > 0$ indicates a tailwind, while $v_i\u2032 < 0$ indicates a headwind).\n\nIf Dandan rides at speed $v$ on the $i$-th segment, the air resistance he experiences is given by $F = k_i (v \u2212 v_i\u2032 )^2$. If he maintains speed $v$ throughout the segment with length $s$, the energy he expends (work done) on this segment is given by $E = k_i (v \u2212 v_i\u2032 )^2 s$.\n\nDandan starts the day with a maximum energy $E_U$. Please help him design a riding strategy to minimize the time $T$ it takes to reach his destination within the provided energy constraints. Output the shortest possible time $T$.\n\n---\n\n### Input Format\n\nThe first line contains a positive integer $N$ and a real number $E_U$, representing the number of road segments and Dandan's maximum energy, respectively.\n\nThe following $N$ lines each describe one segment. Each line contains three real numbers $s_i$, $k_i$, and $v_i\u2032$, representing the segment's length, air resistance coefficient, and wind speed, respectively.\n\n---\n\n### Output Format\n\nOutput a single real number $T$, representing the shortest time it takes for Dandan to reach the destination. The result should be accurate to at least 6 decimal places.\n\n---\n\n### Sample\n\nA possible plan could be: Dandan rides at constant speeds for all three road segments, specifically at $5.12939919$, $8.03515481$, and $6.17837967$.\n\n---\n\n### Constraints and Hints\n\n- **Scoring:** This problem has no partial credits. Your program's output must have an absolute difference of at most $0.000001$ from the standard answer to receive full marks for any test case; otherwise, no points will be awarded.\n\n---\n\n#### Data Constraints:\n\n- For $10\\%$ of the data, $N = 1$;\n- For $40\\%$ of the data, $N \\leq 2$;\n- For $60\\%$ of the data, $N \\leq 100$;\n- For $80\\%$ of the data, $N \\leq 1000$;\n- For all cases, $N \\leq 10000$, $0 \\leq E_U \\leq 10^8$, $0 < s_i \\leq 100000$, $0 < k_i \\leq 15$, $\u2212100 < v_i\u2032 < 100$.\n\nThe data guarantees that the final answer will not exceed $10^5$.\n\n---\n\n#### Hint:\nThere must exist an optimal energy allocation plan where Dandan rides at a **constant speed** on each segment.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3757, "prompt": "### Problem Description\nYT City is a well-planned city, divided into $n \\times n$ areas by east-west and north-south main roads. For simplicity, YT City can be considered as a square, and each area can also be considered as a square. Thus, YT City contains $(n + 1) \\times (n + 1)$ intersections and $2n \\times (n + 1)$ bidirectional roads (referred to as roads). Each bidirectional road connects two adjacent intersections on the main roads. The figure below shows the map of YT City for $n = 2$. The city is divided into $2 \\times 2$ areas, including $3 \\times 3$ intersections and $12$ bidirectional roads.\n\n![](https://img.loj.ac.cn/2022/06/01/9e4fd032418a3.png)\n\nAs the mayor of the city, Mr. Z has gathered statistical data on the traffic flow during rush hour for each direction on every road in YT City. For each road, the numbers represent the number of people passing through the road in both directions during rush hour. Every intersection has a unique elevation value. YT City residents consider uphill climbs to be exhausting. Moving uphill by an elevation of $h$ consumes $h$ units of energy. Conversely, moving downhill does not consume energy. If the difference between the elevation of the endpoint and the starting point of a road is $h$ (note that $h$ may be negative), the energy consumed by one person traveling along this road is $\\max\\{0, h\\}$.\n\nMr. Z also measured the elevation at the northwest intersection, which is $0$, and the southeast intersection, which is $1$ (as shown in the figure above). However, the elevations of all other intersections are unknown. Mr. Z wants to know the minimum total energy consumption during rush hour by all commuters climbing uphill under the most ideal circumstances (i.e., you can assign the elevations of other intersections arbitrarily).\n\n### Input Format\nThe first line contains an integer $n$.\n\nThe next $4n(n + 1)$ lines each contain a non-negative integer. These numbers represent the traffic flow information for each road in both directions.\n\nThe order of input is as follows: $n(n + 1)$ numbers represent traffic flow from west to east, followed by $n(n + 1)$ numbers for traffic flow from north to south, then $n(n + 1)$ numbers for traffic flow from east to west, and finally $n(n + 1)$ numbers for traffic flow from south to north. For each direction, the input order follows the starting intersections from north to south, and if two intersections are at the same north-south position, they are ordered from west to east (see sample input).\n\n### Output Format\nOutput a single number, representing the minimum total energy consumption for all commuters climbing uphill during rush hour under the most ideal circumstances (i.e., the minimum value of the total energy consumption). Round the result to the nearest integer.\n\n### Sample\n![](https://img.loj.ac.cn/2022/06/01/5d669f4600d16.png)\n\n### Data Range and Hints\n- For $20\\%$ of the data: $n \\leq 3$;\n- For $50\\%$ of the data: $n \\leq 15$;\n- For $80\\%$ of the data: $n \\leq 40$;\n- For $100\\%$ of the data: $1 \\leq n \\leq 500$, $0 \\leq \\text{traffic flow} \\leq 10^6$, and all traffic flow values are integers.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3532, "prompt": "### Problem Description\nSmall W has a tree of $n$ nodes, where each edge on the tree can either be a light edge or a heavy edge. You are required to perform $m$ operations on the tree. Initially, all edges on the tree are light edges. The operations are as follows:\n\n1. Given two points $a$ and $b$, first, for every node $x$ on the path from $a$ to $b$ (including $a$ and $b$), you need to change all edges connected to $x$ into light edges. Then, change all edges on the path from $a$ to $b$ into heavy edges.\n2. Given two points $a$ and $b$, calculate how many heavy edges are currently present on the path from $a$ to $b$.\n\n### Input Format\nThe problem contains multiple test cases. The first line of input includes a positive integer $T$, representing the number of test cases. For each test case:\n\nThe first line contains two integers $n$ and $m$, where $n$ represents the number of nodes and $m$ represents the number of operations.\n\nThe next $n - 1$ lines each contain two integers $u\\ v$, representing an edge in the tree.\n\nThe next $m$ lines each contain three integers ${\\mathit{op}}_i\\ a_i\\ b_i$, describing an operation, where ${\\mathit{op}}_i = 1$ denotes the first type of operation, and ${\\mathit{op}}_i = 2$ denotes the second type of operation.\n\nIt is guaranteed that $a_i \\neq b_i$.\n\n### Output Format\nFor each operation of type $2$, output one integer per line representing the result.\n\n**\u3010Sample Explanation #1\u3011**\n\nAfter the first operation, the heavy edges are: $(1, 3)$, $(3, 6)$, $(6, 7)$.\n\nAfter the second operation, the heavy edges include: $(1, 3)$.\n\nAfter the third operation, the heavy edges include: $(1, 3)$, $(3, 6)$, $(6, 7)$.\n\nAfter the fourth operation, edges $(1, 3)$ and $(3, 6)$ become light edges, and edges $(1, 3)$ and $(3, 5)$ become heavy edges.\n\nAfter the fifth operation, the heavy edges include: $(1, 3)$ and $(6, 7)$.\n\nAfter the sixth operation, edge $(1, 3)$ becomes a light edge, and edge $(1, 2)$ becomes a heavy edge.\n\nAfter the seventh operation, the heavy edges include: $(6, 7)$.\n\n**\u3010Sample #2\u3011**\n\nRefer to the files `edge/edge2.in` and `edge/edge2.ans`.\n\nThis sample's constraints are consistent with test points $3 \\sim 6$.\n\n**\u3010Sample #3\u3011**\n\nRefer to the files `edge/edge3.in` and `edge/edge3.ans`.\n\nThis sample's constraints are consistent with test points $9 \\sim 10$.\n\n**\u3010Sample #4\u3011**\n\nRefer to the files `edge/edge4.in` and `edge/edge4.ans`.\n\nThis sample's constraints are consistent with test points $11 \\sim 14$.\n\n**\u3010Sample #5\u3011**\n\nRefer to the files `edge/edge5.in` and `edge/edge5.ans`.\n\nThis sample's constraints are consistent with test points $17 \\sim 20$.\n\n**\u3010Data Constraints\u3011**\n\nFor all test cases: $T \\le 3$, $1 \\le n, m \\le {10}^5$.\n\n| Test Point Index | $n, m \\le $ | Special Properties |\n|:-:|:-:|:-:|\n| $1 \\sim 2$ | $10$ | None |\n| $3 \\sim 6$ | $5000$ | None |\n| $7 \\sim 8$ | ${10}^5$ | A, B |\n| $9 \\sim 10$ | ${10}^5$ | A |\n| $11 \\sim 14$ | ${10}^5$ | B |\n| $15 \\sim 16$ | $2\\times {10}^4$ | None |\n| $17 \\sim 20$ | ${10}^5$ | None |\n\nSpecial Property A: The tree takes the form of a chain.\n\nSpecial Property B: For operations of type $2$, the points $a_i$ and $b_i$ are directly connected by an edge.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2085, "prompt": "### Problem Description\n\nNiuNiu is a high school student passionate about algorithm design. In the algorithms he designs, he often uses numbers with decimal fractions. NiuNiu believes that if the fractional part of a number is **purely periodic** in base $k$, the number is beautiful.\n\nNow, NiuNiu wants to know: given the decimal numbers $n$ and $m$, how many **distinct** purely periodic fractions expressed as $\\frac{x}{y}$ are there in base $k$, where $1 \\leq x \\leq n, 1 \\leq y \\leq m$, and $x$ and $y$ are integers?\n\nA number is purely periodic if and only if it can be written in the following form:\n$$a.\\dot{c_1}c_2c_3 \\ldots c_{p-1}\\dot{c_p}$$\nwhere $a$ is an integer and $p \\geq 1$; for $1 \\leq i \\leq p$, $c_i$ is a single digit in base $k$.\n\nFor example:\n- In decimal (base-10), $0.45454545\\ldots = 0.\\dot{4}\\dot{5}$ is purely periodic. It can be expressed as $\\frac{5}{11}$, $\\frac{10}{22}$, etc.\n- In decimal (base-10), $0.1666666\\ldots = 0.1\\dot{6}$ is not purely periodic. It can be expressed as $\\frac{1}{6}$.\n\nIt is important to note that:\n- We consider integers as purely periodic because their fractional part can be represented as a repetition of $0$ or $k-1$.\n- However, finite decimal fractions with non-zero fractional parts are not purely periodic.\n\n---\n\n### Input Format\nThe input consists of a single line containing three decimal integers $n$, $m$, and $k$, as described above.\n\n---\n\n### Output Format\nOutput a single integer: the number of beautiful numbers that meet the specified conditions.\n\n---\n\n### Sample Case 1\n**Input:**\n```\n2 3 10\n```\n\n**Output:**\n```\n4\n```\n\n**Explanation:**\nThe numbers satisfying the conditions are:\n1. $$1/1 = 1.0000 \\ldots$$\n2. $$1/3 = 0.3333 \\ldots$$\n3. $$2/1 = 2.0000 \\ldots$$\n4. $$2/3 = 0.6666 \\ldots$$\n\nAlthough $1/1$ and $2/2$ are both purely periodic fractions, they are considered as the same value, so they are only counted once. Similarly, $1/3$ and $2/6$ are also counted as the same.\n\n---\n\n### Sample Case 2\n**Input:**\n```\n1 1 2\n```\n\n**Output:**\n```\n1\n```\n\n---\n\n### Constraints and Hints\nFor all test cases, the following conditions are satisfied:\n$$1 \\leq n \\leq 10^9, \\quad 1 \\leq m \\leq 10^9, \\quad 2 \\leq k \\leq 2000$$\n\nFor each test case, the constraints are as follows (where blank cells mean no special constraints):\n\n| Test Case ID | $n$ | $m$ | $k$ |\n|:------------:|:-----------------:|:-----------------:|:-----------------:|\n| 1 | $\\leq 10$ | $\\leq 20$ | $=2$ |\n| 2 | $\\leq 100$ | $\\leq 10^4$ | $=2$ |\n| 3 | $\\leq 1000$ | | $=2$ |\n| 4 | $\\leq 10000$ | | $=2$ |\n| 5 | $\\leq 10$ | $\\leq 20$ | $=3$ |\n| 6 | $\\leq 100$ | $\\leq 10^4$ | $=3$ |\n| 7 | $\\leq 1000$ | | $=3$ |\n| 8 | $\\leq 10000$ | | $=3$ |\n| 9 | $\\leq 10$ | $\\leq 20$ | $\\leq 100$ |\n| 10 | $\\leq 100$ | $\\leq 10^4$ | $\\leq 100$ |\n| 11 | $\\leq 1000$ | | $\\leq 1000$ |\n| 12 | $\\leq 10000$ | | |\n| 13 | $\\leq 10^5$ | $\\leq 10^8$ | $\\leq 100$ |\n| 14 | $\\leq 2 \\times 10^5$ | | $\\leq 1000$ |\n| 15 | $\\leq 5 \\times 10^5$ | | |\n| 16 | $\\leq 10^6$ | $\\leq 10^8$ | $\\leq 100$ |\n| 17 | $\\leq 2 \\times 10^6$ | | $\\leq 1000$ |\n| 18 | $\\leq 5 \\times 10^6$ | | |\n| 19 | $\\leq 10^7$ | $\\leq 10^8$ | $\\leq 100$ |\n| 20 | $\\leq 2 \\times 10^7$ | | $\\leq 1000$ |\n| 21 | $\\leq 2 \\times 10^7$ | | |\n| 22 | $\\leq 10^8$ | $\\leq 10^8$ | |\n| 23 | $\\leq 10^8$ | $\\leq 10^8$ | |\n| 24 | | | |\n| 25 | | | |\n\n\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2305, "prompt": "### Problem Statement\n\nLittle L plans to play $n$ games. Each game takes place on a map, where Little L selects a car to complete the game on that map.\n\nLittle L has three racing cars, denoted by the uppercase letters $A$, $B$, and $C$. There are four types of maps, denoted by the lowercase letters $x$, $a$, $b$, and $c$. \n\n- Car $A$ is not suitable for map $a$. \n- Car $B$ is not suitable for map $b$. \n- Car $C$ is not suitable for map $c$. \n- Map $x$ is suitable for all cars.\n\nMaps suitable for all cars are rare, and there are at most $d$ such maps.\n\nThe maps for the $n$ games can be described as a string of lowercase letters. For example, $S=\\texttt{xaabxcbc}$ means Little L plans to play $8$ games. The types of maps are as follows: \n- The $1$st and $5$th games use map $x$, suitable for all cars. \n- The $2$nd and $3$rd games use map $a$, not suitable for car $A$. \n- The $4$th and $7$th games use map $b$, not suitable for car $B$. \n- The $6$th and $8$th games use map $c$, not suitable for car $C$. \n\nLittle L has some specific requirements that can be described using a tuple $(i, h_i, j, h_j)$, indicating that if car model $h_i$ is used in the $i$th game, then car model $h_j$ must be used in the $j$th game.\n\nCan you help Little L choose which car to use for each game? If there are multiple valid solutions, output any one of them.\n\nIf there is no solution, output `-1`.\n\n---\n\n### Input Format\n\nThe first line contains two non-negative integers $n$ and $d$. \n\nThe second line contains a string $S$, where: \n- $S$ is a description of the maps for the $n$ games. \n- $S$ contains $n$ characters, with exactly $d$ of them being the letter $x$. \n\nThe third line contains a positive integer $m$, representing the number of rules related to car usage. \n\nThe next $m$ lines each contain a tuple $i, h_i, j, h_j$, where: \n- $i$ and $j$ are integers. \n- $h_i$ and $h_j$ are characters $A$, $B$, or $C$. \nThe tuple describes the relationship between the car choices for the $i$th and $j$th games.\n\n---\n\n### Output Format\n\nOutput a single line: \n- If there is no solution, output `-1`.\n\n---\n\n### Example\n\nLittle L plans to play $3$ games. \n- The $1$st game's map type is $x$, suitable for all cars. \n- The $2$nd and $3$rd games use map $c$, not suitable for car $C$. \n\nLittle L wants: \n- If car $A$ is used for the $1$st game, then car $B$ must be used for the $2$nd game.\n\nA valid solution could assign cars $A$, $B$, and $A$ to the $3$ games. \n\nAssigning cars $B$, $B$, and $B$ or $B$, $A$, and $A$ is also valid. \n\nAssigning cars $A$, $A$, and $B$ or $A$, $B$, and $C$ is invalid because they do not satisfy all rules.\n\n---\n\n### Constraints & Hints\n\n| Test Case Number | $n$ | $d$ | $m$ | Additional Properties |\n| :--------------: | :----------------: | :-----: | :--------: | :-----------------------------------: |\n| $1$ | $\\le 2$ | $0$ | $\\le 4$ | None |\n| $2$ | $\\le 2$ | $\\le n$ | $\\le 4$ | None |\n| $3$ | $\\le 5$ | $0$ | $\\le 10$ | None |\n| $4$ | $\\le 5$ | $\\le n$ | $\\le 10$ | None |\n| $5$ | $\\le 10$ | $0$ | $\\le 20$ | None |\n| $6$ | $\\le 10$ | $\\le 8$ | $\\le 20$ | None |\n| $7$ | $\\le 20$ | $0$ | $\\le 40$ | $S$ only contains $c$ |\n| $8$ | $\\le 20$ | $0$ | $\\le 40$ | None |\n| $9$ | $\\le 20$ | $\\le 8$ | $\\le 40$ | $S$ only contains $x$ or $c$ |\n| $10$ | $\\le 20$ | $\\le 8$ | $\\le 40$ | None |\n| $11$ | $\\le 100$ | $0$ | $\\le 200$ | $S$ only contains $c$ |\n| $12$ | $\\le 100$ | $0$ | $\\le 200$ | None |\n| $13$ | $\\le 100$ | $\\le 8$ | $\\le 200$ | $S$ only contains $x$ or $c$ |\n| $14$ | $\\le 100$ | $\\le 8$ | $\\le 200$ | None |\n| $15$ | $\\le 5\\times 10^3$ | $0$ | $\\le 10^4$ | None |\n| $16$ | $\\le 5\\times 10^3$ | $\\le 8$ | $\\le 10^4$ | $S$ only contains $x$ or $c$ |\n| $17$ | $\\le 5\\times 10^3$ | $\\le 8$ | $\\le 10^4$ | None |\n| $18$ | $\\le 5\\times 10^4$ | $0$ | $\\le 10^5$ | None |\n| $19$ | $\\le 5\\times 10^4$ | $\\le 8$ | $\\le 10^5$ | $S$ only contains $x$ or $c$ |\n| $20$ | $\\le 5\\times 10^4$ | $\\le 8$ | $\\le 10^5$ | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2086, "prompt": "### Problem Description\n\nOn a number line, there are $n$ closed intervals: $[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$. You need to select $m$ intervals from these such that the selected $m$ intervals collectively include at least one position. In other words, there must exist at least one position $x$ such that for every selected interval $[l_i, r_i]$, $l_i \\leq x \\leq r_i$.\n\nFor a valid selection, the cost is defined as the length of the longest selected interval minus the length of the shortest selected interval. The length of an interval $[l_i, r_i]$ is defined as $r_i - l_i$, i.e., the difference between its right endpoint value and its left endpoint value.\n\nFind the minimum cost among all valid selections. If no valid selection exists, output $-1$.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, separated by a space, as described above. It is guaranteed that $1 \\leq m \\leq n$.\n\nThe next $n$ lines each describe an interval, containing two integers $l_i$ and $r_i$, separated by a space, representing the left and right endpoints of the interval.\n\n---\n\n### Output Format\n\nOutput a single integer: the minimum cost.\n\n---\n\n### Example\n\n![](https://img.loj.ac.cn/2022/09/22/94a95ae0be394.png)\n\nFor $n = 6, m = 3$, the minimum cost selection is to choose the intervals $[3, 5]$, $[3, 4]$, and $[1, 4]$. These intervals collectively include position $4$, making the selection valid. Among the selected intervals, the longest one is $[1, 4]$ and the shortest one is $[3, 4]$. The cost of this selection is $(4 - 1) - (4 - 3) = 2$. \n\n---\n\n### Data Range and Hints\n\nThe range and characteristics of the test data are shown in the table below:\n\n\n\n| Test Case ID | $ n $ | $ m $ | $ l_i, r_i $ |\n|:-:|:-:|:-:|:-:|\n| 1 | $ 20 $ | $ 9 $ | $ 0 \\leq l_i \\leq r_i \\leq 100 $ |\n| 2 | $ 20 $ | $ 10 $ | $ 0 \\leq l_i \\leq r_i \\leq 100 $ |\n| 3 | $ 199 $ | $ 3 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 4 | $ 200 $ | $ 3 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 5 | $ 1000 $ | $ 2 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 6 | $ 2000 $ | $ 2 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 7 | $ 199 $ | $ 60 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 8 | $ 200 $ | $ 50 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 9 | $ 200 $ | $ 50 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 10 | $ 1999 $ | $ 500 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 11 | $ 2000 $ | $ 400 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 12 | $ 2000 $ | $ 500 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 13 | $ 30000 $ | $ 2000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 14 | $ 40000 $ | $ 1000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 15 | $ 50000 $ | $ 15000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 16 | $ 100000 $ | $ 20000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 17 | $ 200000 $ | $ 20000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 18 | $ 300000 $ | $ 50000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 19 | $ 400000 $ | $ 90000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 20 | $ 500000 $ | $ 200000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n\n---\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3008, "prompt": "### Problem Description\n\nA rooted and weighted tree is defined as a **Symmetric Binary Tree** by Xuanxuan if it satisfies the following conditions:\n\n1. It is a binary tree.\n2. After swapping the left and right subtrees of **all** nodes, the resulting tree has the same structure as the original tree, and the corresponding nodes have the same values.\n\nIn the diagram below, the numbers inside the nodes represent the weights, and the `$id$` outside the nodes represents the node identifier.\n\n![](https://uploadfiles.nowcoder.com/images/20181110/306604_1541848852978_E09FB8BAC799B78F2BA4FA809F4F25DE)\n\nGiven a binary tree, your task is to find a subtree of this tree that is a **Symmetric Binary Tree** and has the largest number of nodes. Output the number of nodes in this subtree.\n\n**Note**: A tree with only the root node is also a symmetric binary tree. In this problem, a subtree rooted at node $T$ includes node $T$ and **all** its descendant nodes.\n\n### Input Format\n\nThe input file is named `tree.in`.\n\nThe input consists of:\n\n- The first line contains a positive integer $n$, the number of nodes in the given tree. Nodes are indexed from $1$ to $n$, and node $1$ is the root of the tree.\n- The second line contains $n$ positive integers separated by spaces, where the $i$-th integer $v_i$ represents the weight of node $i$.\n- The next $n$ lines each contain two integers $l_i$ and $r_i$, representing the left and right child of node $i$, respectively. If a node does not have a left or right child, it is denoted by $-1$. Both numbers are separated by a space.\n\n### Output Format\n\nThe output file is named `tree.out`.\n\nThe output contains a single integer, representing the number of nodes in the largest symmetric binary subtree of the given tree.\n\n---\n\n### Example 1\n\n\n\nThe largest symmetric binary subtree is the subtree rooted at node $2$, which has $1$ node.\n\n---\n\n### Example 2\n\n\n\nThe largest symmetric binary subtree is the subtree rooted at node $7$, which has $3$ nodes.\n\n---\n\nRefer to the accompanying `tree3.in` and `tree3.ans` files for further examples.\n\n### Constraints and Hints\n\nThere are $25$ test cases.\n\n- $v_i \\leq 1000$.\n- For test cases $1 \\sim 3$, $n \\leq 10$. In these cases, all nodes in the left subtree of the root do not have right children, and all nodes in the right subtree of the root do not have left children.\n- For test cases $4 \\sim 8$, $n \\leq 10$.\n- For test cases $9 \\sim 12$, $n \\leq 10^5$, and the input tree is guaranteed to be a \"Full Binary Tree\".\n- For test cases $13 \\sim 16$, $n \\leq 10^5$, and the input tree is guaranteed to be a \"Complete Binary Tree\".\n- For test cases $17 \\sim 20$, $n \\leq 10^5$, and all node weights of the input tree are the same ($v_i = 1$).\n- For test cases $21 \\sim 25$, $n \\leq 10^6$.\n\n---\n\n### Definitions\n\n**Level**: The level of a node is its distance from the root. The root is at level $1$, and the children of the root are at level $2$. For any node, its level is equal to the level of its parent plus $1$. \n**Depth of a Tree**: The depth of a tree is defined as the maximum level among all its nodes.\n\n#### Full Binary Tree \nA binary tree is a **Full Binary Tree** if its depth is $h$ and it contains $2^h - 1$ nodes.\n\n![](https://uploadfiles.nowcoder.com/images/20181110/306604_1541859030087_B663B244A48AAD0CE81DCC50E78E1386)\n\n#### Complete Binary Tree \nA binary tree is a **Complete Binary Tree** if all levels except possibly the last level are completely filled, and all the nodes in the last level are aligned to the left.\n\n![](https://uploadfiles.nowcoder.com/images/20181110/306604_1541859056448_08E14E77121B5C0CDDB7A458EF4DC4C3)\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3533, "prompt": "### Problem Description\n\nLittle L has a directed graph where the vertices can be divided into $k$ layers. The $i$-th layer contains $n_i$ vertices. The first layer and the $k$-th layer have the **same number of vertices**, i.e., $n_1 = n_k$, and for the $j$-th layer ($2 \\leq j \\leq k-1$), $n_1 \\leq n_j \\leq 2n_1$. For vertices in the $j$-th layer ($1 \\leq j < k$), edges originating from them are only connected to vertices in the $(j+1)$-th layer. No edges are connected to vertices in the first layer, and vertices in the $k$-th layer do not have outgoing edges.\n\nNow, Little L wants to select $n_1$ paths from the graph, each starting at a vertex in the first layer and ending at a vertex in the $k$-th layer, with the condition that **every vertex in the graph appears in at most one path**. Specifically, each path can be written as a $k$-tuple $(p_1, p_2, \\ldots, p_k)$, where the path sequentially traverses the $p_j$-th vertex of the $j$-th layer ($1 \\leq p_j \\leq n_j$). Additionally, for the $p_j$-th vertex in the $j$-th layer ($1 \\leq j < k$), there is an edge to the $p_{j+1}$-th vertex in the $(j+1)$-th layer.\n\nLittle L drew these paths on paper and noticed that they could produce intersection points. For two paths $P$ and $Q$, assume their edges between the $j$-th and $(j+1)$-th layers are $(P_j, P_{j+1})$ and $(Q_j, Q_{j+1})$, respectively. If,\n\n$$\n(P_j - Q_j) \\times (P_{j+1} - Q_{j+1}) < 0\n$$\n\nthen it is said that the two paths intersect after the $j$-th layer. The number of intersections between two paths is the total number of intersections they produce after the $1, 2, \\ldots, k-1$ layers. For the entire path scheme, the intersection count is the **sum of intersection counts between every pair of distinct paths**. For example, the following figure shows an example with 3 paths and 3 intersections, with the red dots representing intersection points:\n\n![](https://img.loj.ac.cn/2021/07/26/60fe2a7bd4aa0.png)\n\nLittle L wants to know how many more path schemes with an even number of intersections there are than path schemes with an odd number of intersections. Two path schemes are considered identical if and only if the $n_1$ paths, represented as $k$-tuples sorted by the starting vertex's index in the first layer, can correspond to the same scheme. Since the final result may be large, please output the result modulo $998244353$ (a large prime number).\n\n### Input Format\n\nData is read from the file `xpath.in`.\n\nThe input consists of multiple test cases. The first line contains a positive integer $T$, indicating the number of test cases. For each test case:\n\n- The first line contains a positive integer $k$, indicating the number of layers of vertices.\n- The second line contains $k$ integers $n_1, n_2, \\ldots, n_k$, indicating the number of vertices in each layer. It is guaranteed that $n_1 = n_k$, and $n_1 \\leq n_i \\leq 2n_1$ ($2 \\leq i \\leq k-1$).\n- The third line contains $k-1$ integers $m_1, m_2, \\ldots, m_{k-1}$, indicating the number of edges from the $j$-th layer to the $(j+1)$-th layer. It is guaranteed that $m_j \\leq n_j \\times n_{j+1}$.\n- The next $k-1$ segments of input describe the edges between layers. The $j$-th segment ($1 \\leq j < k$) contains $m_j$ lines, each with two integers $u, v$, representing an edge from the $u$-th vertex in the $j$-th layer to the $v$-th vertex in the $(j+1)$-th layer.\n\nIt is guaranteed that there are no duplicate edges in the graph.\n\n### Output Format\n\nWrite the output to the file `xpath.out`.\n\nThe output consists of $T$ lines, each containing a single integer, which represents the answer for the corresponding test case modulo $998244353$.\n\n### Example\n\nPath schemes with an even number of intersections: $2$. \nPath schemes with an odd number of intersections: $1$. \nThus, the result is $1$.\n\nExchanging the schemes of path $1$ and path $2$ results in identical schemes. For instance, a scheme where path $1$ is $(2, 3, 1)$ and path $2$ is $(1, 1, 2)$ is the same as scheme $1$. Such schemes are not counted again in the answer.\n\n| Path Scheme | Path $1$ | Path $2$ | Total Intersections |\n| :----------: | :------: | :------: | :-----------------: |\n| $1$ | $(1,1,2)$ | $(2,3,1)$ | $1$ |\n| $2$ | $(1,2,1)$ | $(2,1,2)$ | $2$ |\n| $3$ | $(1,2,1)$ | $(2,3,2)$ | $0$ |\n\n### Constraints and Hints\n\nFor all test cases: $2 \\leq k \\leq 100$, $2 \\leq n_1 \\leq 100$, $1 \\leq T \\leq 5$. \n\nFor each test case, there is only one input with $n_1 > 10$. \n\n| Test Case ID | $k=$ | $n_1 \\leq$ | Special Properties |\n| :----------: | :---: | :--------: | :----------------: |\n| $1 \\sim 4$ | $2$ | $10$ | None |\n| $5 \\sim 6$ | $10$ | $10$ | A, B |\n| $7 \\sim 8$ | $10$ | $10$ | A |\n| $9 \\sim 10$ | $10$ | $10$ | None |\n| $11 \\sim 13$ | $2$ | $100$ | None |\n| $14 \\sim 15$ | $100$ | $100$ | A, B |\n| $16 \\sim 17$ | $100$ | $100$ | A |\n| $18 \\sim 20$ | $100$ | $100$ | None |\n\nSpecial Property A: For all $i$ ($2 \\leq i \\leq k-1$), $n_i = n_1$. \nSpecial Property B: The total number of path schemes is guaranteed to be at most $1$. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2598, "prompt": "### Problem Description\n\n**Mayan Puzzle** is a recently popular game. The game interface consists of a $7$-row by $5$-column grid populated with blocks. Blocks cannot hover; they must be placed either on the bottommost row or stacked on top of other blocks. The goal of the game is to clear all the blocks within a specified number of moves. The block elimination rules are as follows:\n\n1. Each move allows you to drag a single block one step horizontally, either to the left or right.\n\n * If the target position (the position a block moves to) already contains a block, the dragged block and the block in the target position will switch places (refer to the transition from Diagram $6$ to Diagram $7$ in the input-output example illustration).\n \n * If the target position is empty, the dragged block will be pulled out of its original column and will fall straight down to the target position until it rests on a surface (refer to the transition from Diagram $1$ to Diagram $2$ below).\n\n ![](https://img.loj.ac.cn/2019/09/22/5d87356ada259.png)\n\n2. Blocks are eliminated when there are three or more blocks of the same color consecutively aligned in a row or column. Blocks are removed immediately when this condition is met (refer to the transition from Diagram $1$ to Diagram $3$).\n\n**Important Notes:**\n\na) If multiple sets of blocks meet the elimination criteria simultaneously, all qualifying sets will be eliminated at the same time. For example, in Diagram $4$, three blocks of color $1$ and three blocks of color $2$ will be eliminated simultaneously, leaving only one block of color $2$.\n\nb) If both a row and a column meet the elimination criteria, and they share one or more blocks, all the qualifying blocks in that row and column will be eliminated simultaneously. For example, in the scenario shown in Diagram $5$, $5$ blocks will be eliminated at the same time.\n\n ![](https://img.loj.ac.cn/2019/09/22/5d87356b5e9cf.png)\n\n3. After blocks are eliminated, blocks above the eliminated positions will fall straight down to fill the empty spaces. Further eliminations may occur after blocks have settled. Notably, no blocks are eliminated during the falling process.\n\nThe process of moving a block and the changes to the grid are illustrated in Diagrams $1$ to $3$. The bottom-left corner of the grid is assigned the coordinates $(0,0)$. Starting with the configuration depicted in Diagram $1$, dragging the block at $(3,3)$ to the left transforms the grid into the state shown in Diagram $2$. At this point, a vertical column of three consecutive blocks of color $4$ forms and is eliminated. After elimination, the color $3$ block above them falls downward, resulting in the grid state depicted in Diagram $3$.\n\n---\n\n### Input Format\n\n1. The first line contains a single positive integer $n$, which represents the number of moves required to clear the game.\n2. The following $5$ lines describe the $7 \\times 5$ game grid. Each line contains a set of integers separated by spaces, ending with a $0$. These numbers, read from bottom to top, represent the colors of the blocks in each column (where color types are numbered consecutively starting from $1$ and at most $10$ different colors are used). Blocks with the same number correspond to blocks of the same color.\n\nThe input is guaranteed that, in the initial grid configuration, there are no blocks that can be immediately eliminated.\n\n---\n\n### Output Format\n\nIf a solution exists, output $n$ lines, each containing three integers $x, y, g$, which represent a single move. The integers $x, y$ specify the coordinates of the block to be moved, and $g$ specifies the direction of the move ($1$ for moving to the right and $-1$ for moving to the left). Each pair of integers should be separated by a single space. In case of multiple solutions, output the lexicographically smallest solution, prioritizing $x$ as the primary key, $y$ as the secondary key, and $1$ before $-1$ for the direction.\n\nIf no solution exists, output a single line containing the integer `-1`.\n\nThe game's grid uses $(0,0)$ as the coordinates for the bottom-left corner.\n\n---\n\n### Example\n\nAs shown in the sequence of diagrams labeled $6$ through $11$, the grid's initial configuration is as depicted in the first image. The game is solved in three steps:\n\n1. Move the block at $(2,1)$ to the right.\n2. Move the block at $(3,1)$ to the right.\n3. Move the block at $(3,0)$ to the right.\n\nFollowing these steps, all the blocks on the grid are eliminated.\n\n---\n\n#### Sample Input\n```\n3\n3 4 1 0\n3 4 2 2 0\n3 4 2 1 0\n1 0\n2 3 0\n0\n```\n\n#### Sample Output\n```\n2 1 1\n3 1 1\n3 0 1\n```\n\n---\n\n### Constraints and Hints\n\n1. For $30\\%$ of the data, all the blocks in the initial grid are located in the bottommost row.\n2. For $100\\%$ of the data, $0 < n \\leq 5$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2087, "prompt": "### Problem Description\n\nThere are $n$ cities in the Flea Kingdom. The great Flea King resides in the capital city of the Flea Kingdom, which is City $1$.\n\nThe biggest problem in the Flea Kingdom is the water supply issue. Due to the large population in the capital city, the benevolent Flea King allocates his own water to the residents of the Flea Kingdom, often leaving the Flea King without water to drink.\n\nTo address this issue, the Flea Kingdom has built cylindrical water tanks in every city. These tanks are identical and tall enough to hold any amount of water. After a rainy day, City $i$ collected water with a height of $h_i$. Due to geographical and weather factors, the water levels collected by any two cities are distinct.\n\nThe Flea King has also engaged the Ant Artisans to construct an extensive underground connection system. Whenever the Flea King uses this underground system, he can designate any number of cities to connect their water tanks. Upon closing the underground connection system after sufficient time, the water levels in all the connected cities' water tanks will equalize. The final height of water in these connected tanks will be the average of the initial heights of the connected tanks.\n\nDue to the complexity of the underground system, the Flea King can use the system at most $k$ times.\n\nThe Flea King wants you to tell him the maximum water level that can be achieved in the water tank of the capital, City $1$.\n\n---\n\n### Input Format\n\nThe first line contains three positive integers $n$, $k$, and $p$, representing the number of cities in the Flea Kingdom, the maximum number of times the Flea King can use the underground connection system, and the precision required for the output, respectively. The meaning of $p$ will be explained in the output section.\n\nThe second line contains $n$ distinct positive integers, describing the water levels of the cities' water tanks after the rain. The $i$-th integer $h_i$ represents the water level in City $i$'s tank. It is guaranteed that the $h_i$ values are distinct and that $1 \\leq h_i \\leq 10^5$.\n\n---\n\n### Output Format\n\nOutput a single line containing a real number, representing the maximum water level that can be achieved in the water tank of City $1$.\n\nThe real number can only contain a non-negative integer part, a decimal point, and a fractional part. The integer part is mandatory and should not include a sign. If a fractional part exists, it must be separated from the integer part by a decimal point. If there is no fractional part, the decimal point should not be included.\n\nThe output real number must have no more than $2p$ digits after the decimal point, and it is recommended to retain at least $p$ digits. It is guaranteed that the reference answer and the true answer have an absolute error of less than $10^{-2p}$. \n\nYour output will be considered correct if and only if the absolute error between your output and the reference answer is less than $10^{-p}$.\n\nIf the absolute error between your output and the reference answer is not less than $10^{-p}$ but less than $10^{-5}$, you will earn $40\\%$ of the points for that test case.\n\n---\n\n### Example 1\n\n#### Input\n```\n3 1 2\n1 4 2\n```\n\n#### Explanation\n\nWith at most one use of the underground connection system, the possible scenarios are:\n1. Not using the connection system: The water level in City $1$ remains $1$.\n2. Using the system once to connect Cities $1$ and $2$: The water level in City $1$ becomes $5/2$.\n3. Using the system once to connect Cities $1$ and $3$: The water level in City $1$ becomes $2/2$.\n4. Using the system once to connect Cities $2$ and $3$: The water level in City $1$ remains $1$.\n5. Using the system once to connect Cities $1$, $2$, and $3$: The water level in City $1$ becomes $8/3$.\n\n#### Output\n```\n2.6667\n```\n\n---\n\n### Example 2\n\n#### Input\n```\n3 2 5\n1 4 2\n```\n\n#### Explanation\n\nThe optimal solution is to use the connection system twice: first connecting Cities $1$ and $3$, and then connecting Cities $1$ and $2$.\n\n#### Output\n```\n3.00000\n```\n\n---\n\n### Notes and Constraints\n\n#### Notes\nTo ensure accuracy, it is generally recommended to maintain greater precision than required during calculations. Specifically, it can be proven that in any reference solution for all subtasks, maintaining at least $\\frac{6}{5}p$ digits of precision throughout the computation process guarantees that the absolute error between the output and the reference answer will always be less than $10^{-p}$.\n\nFor convenience, a fixed-point high-precision decimal class is provided. Contestants may refer to and use this class as needed, or implement their own solution. Details on how to use this class can be found in the attached document `decimal.pdf`.\n\n#### Constraints\n\n\n| Test Case Number | $n$ | $k$ | $p$ |\n|-|-|-|-|\n| 1 | $\\leq 2$ | $\\leq 5$ | $=5$ |\n| 2 | $\\leq 4$ | $\\leq 5$ | $=5$ |\n| 3 | $\\leq 4$ | $\\leq 5$ | $=5$ |\n| 4 | $\\leq 10$ | $=1$ | $=5$ |\n| 5 | $\\leq 10$ | $=10^9$ | $=5$ |\n| 6 | $\\leq 10$ | $\\leq 10$ | $=5$ |\n| 7 | $\\leq 10$ | $\\leq 10$ | $=5$ |\n| 8 | $\\leq 100$ | $=1$ | $=5$ |\n| 9 | $\\leq 100$ | $=10^9$ | $=40$ |\n| 10 | $\\leq 100$ | $\\leq 10^9$ | $=40$ |\n| 11 | $\\leq 100$ | $\\leq 10^9$ | $=40$ |\n| 12 | $\\leq 100$ | $\\leq 10^9$ | $=40$ |\n| 13 | $\\leq 250$ | $\\leq 10^9$ | $=100$ |\n| 14 | $\\leq 500$ | $\\leq 10^9$ | $=200$ |\n| 15 | $\\leq 700$ | $\\leq 10^9$ | $=300$ |\n| 16 | $\\leq 700$ | $\\leq 10^9$ | $=300$ |\n| 17 | $\\leq 700$ | $\\leq 10^9$ | $=300$ |\n| 18 | $\\leq 2500$ | $\\leq 10^9$ | $=1000$ |\n| 19 | $\\leq 4000$ | $\\leq 10^9$ | $=1500$ |\n| 20 | $\\leq 8000$ | $\\leq 10^9$ | $=3000$ |\n\n---\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3339, "prompt": "### Problem Description\n\nAfter repelling the invasion of the Disaster Army, the Elven Kingdom on the continent of Bzeroth has flourished over the past decade, attracting tourists from all directions. Little W, a renowned gourmet who has traveled around the world, is now visiting the Elven Kingdom.\n\nThe Elven Kingdom consists of $n$ cities, numbered from $1$ to $n$. The delicacies in city $i$ can bring $c_i$ happiness points to Little W. The cities are connected by $m$ **one-way roads**, numbered from $1$ to $m$. Road $i$ starts from city $u_i$, ends at city $v_i$, and takes $w_i$ days to traverse. That is, if Little W departs from city $u_i$ along road $i$ on day $d$, he will arrive at city $v_i$ on day $d + w_i$.\n\nLittle W plans to undertake a journey in the Elven Kingdom lasting $T$ days. Specifically:\n- He will start his journey on day $0$ from city $1$.\n- After $T$ days of traveling, he must end his journey **exactly on day $T$** back at city $1$.\n\nAs an avid gourmet, Little W tastes the delicacies of a city every time he arrives (including city $1$ on day $0$ and day $T$), gaining the associated happiness points. If Little W revisits a city multiple times, he gains happiness points multiple times. **Note that Little W cannot stay in a city during his journey**: whenever he arrives at a city without finishing his journey, he must leave immediately for another city on the same day.\n\n![](https://img.loj.ac.cn/2020/08/18/5f3bb2b598679.png)\n\n
Figure 1: Sample 1
\n\nFor the diagram above, one feasible $11$-day travel plan for Little W is $1 \\rightarrow 2 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 1$:\n\n- On day $0$, Little W starts from city $1$, gains happiness points $1$, and departs for city $2$.\n- On day $1$, Little W arrives at city $2$, gains happiness points $3$, and departs for city $1$.\n- On day $4$, Little W arrives at city $1$, gains happiness points $1$, and departs for city $2$.\n- On day $5$, Little W arrives at city $2$, gains happiness points $3$, and departs for city $3$.\n- On day $7$, Little W arrives at city $3$, gains happiness points $4$, and departs for city $1$.\n- On day $11$, Little W arrives at city $1$, gains happiness points $1$, and ends his journey.\n\n- The total happiness points Little W gains from this journey is $13$.\n\nAdditionally, the Elven Kingdom hosts **distinct** food festivals $k$ times at different times. Specifically, the $i$th food festival will be held on day $t_i$ in city $x_i$. If Little W arrives at city $x_i$ exactly on day $t_i$, he gains **additional happiness points** $y_i$. Now, Little W asks you, as the official host representing the Elven Kingdom, to calculate the **maximum total happiness points** he can obtain from his journey.\n\n---\n\n### Input Format\n\nRead the input from the file `delicacy.in`.\n\nThe first line contains four integers $n, m, T, k$, which represent the number of cities, the number of roads, the number of travel days, and the number of food festivals, respectively.\n\nThe second line contains $n$ integers $c_i$, which represent the happiness points provided by the delicacies of each city.\n\nThe next $m$ lines each contain three integers $u_i, v_i, w_i$, which represent the start city, end city, and transit days of each road.\n\nThe final $k$ lines each contain three integers $t_i, x_i, y_i$, which represent the festival day, festival city, and additional happiness points provided by each food festival.\n\nThe problem guarantees:\n- For all $1 \\leq i \\leq m$, $u_i \\neq v_i$. However, there may be duplicate **one-way roads**; that is, it is possible for $1 \\leq i < j \\leq m$, such that $u_i = u_j$ and $v_i = v_j$.\n\n- For every city, there exists at least one one-way road starting from that city.\n\n- Each food festival day $t_i$ is unique.\n\n---\n\n### Output Format\n\nWrite the output to the file `delicacy.out`.\n\nOutput a single integer, which represents the maximum happiness points Little W can achieve through his journey.\n\nIf **Little W cannot return to city $1$ exactly on day $T$, output** $-1$.\n\n---\n\n### Example 1\n\nThis example is from the problem description. The optimal journey plan is shown in the description.\n\n---\n\n### Example 2\n\nThe optimal plan is $1\\rightarrow 3\\rightarrow 4\\rightarrow 2\\rightarrow 3\\rightarrow 4\\rightarrow 1$:\n\n- On day $0$, Little W starts from city $1$, gains happiness points $3$, and travels using road $3$.\n- On day $2$, Little W arrives at city $3$, gains happiness points $2$, and travels using road $4$.\n- On day $5$, Little W arrives at city $4$, gains happiness points due to the food festival $20 + 4$, and travels using road $7$.\n- On day $6$, Little W arrives at city $2$, gains happiness points $1$, and travels using road $5$.\n- On day $8$, Little W arrives at city $3$, gains happiness points $2$, and travels using road $4$.\n- On day $11$, Little W arrives at city $4$, gains happiness points $4$, and travels using road $8$.\n- On day $16$, Little W arrives at city $1$, gains happiness points $3$, and ends his journey.\n\n- The total happiness points Little W gains from this journey is $39$.\n\nRefer to the additional files `delicacy3.in` and `delicacy3.ans` for input and output examples.\n\n---\n\n### Constraints & Hints\n\nFor all test cases:\n\n$1 \\leq n \\leq 50$, $n \\leq m \\leq 501$, $0 \\leq k \\leq 200$, $1 \\leq t_i \\leq T \\leq 10^9$.\n\n$1 \\leq w_i \\leq 5$, $1 \\leq c_i \\leq 52501$, $1 \\leq u_i, v_i, x_i \\leq n$, $1 \\leq y_i \\leq 10^9$.\n\nThe specific constraints for each test case are listed below:\n\n| Test Case ID | $n$ | $m$ | $T$ | Special Constraint |\n| :------------: | :--------: | :--------: | :---------: | :-----------------: |\n| $1\\sim 4$ | $\\leq 5$ | $\\leq 50$ | $\\leq 5$ | |\n| $5\\sim 8$ | $\\leq 50$ | $\\leq 50$ | $\\leq 52501$| |\n| $9\\sim 10$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | A |\n| $11\\sim 13$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | $k=0$ |\n| $14\\sim 15$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | $k\\leq 10$ |\n| $16 \\sim 17$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | |\n| $18 \\sim 20$ | $\\leq 50$ | $\\leq 501$ | $\\leq 10^9$ | |\n\nSpecial Constraint A: $n = m$ and $u_i = i$, $v_i = (i \\bmod n) + 1$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3564, "prompt": "### Problem Description\n\nThe counting game is a widely popular casual game. Each participant, in a predetermined order, calls out numbers sequentially. However, if the next number is a multiple of $7$ or contains the digit $7$ in its decimal representation, they must skip that number; otherwise, they lose the game.\n\nOne pleasant afternoon, after finishing the SPC20nn competition, little r and little z decided to play this counting game out of boredom. However, with only two players, the calculations were relatively simple, so they played the game for a long time without determining a winner. At this point, little z had a sudden inspiration and decided to augment the game: for any number that contains the digit $7$ in its decimal representation, all of its multiples also cannot be counted!\n\nFormally, let $p(x)$ indicate whether $x$ contains the digit $7$ in its decimal representation. If so, $p(x) = 1$; otherwise, $p(x) = 0$. A positive integer $x$ cannot be called out if and only if there exist positive integers $y$ and $z$ such that $x = yz$ and $p(y) = 1$.\n\nFor example:\n- If little r calls out $6$, since $7$ cannot be called, little z will need to call out $8$ next.\n- If little r calls out $33$, then $34 = 17 \\times 2$ and $35 = 7 \\times 5$ cannot be called, so little z must call out $36$ next.\n- If little r calls out $69$, since all numbers from $70$ to $79$ contain the digit $7$, little z must call out $80$ next.\n\nNow, given that little r's last number was $x$, little z wants to quickly figure out the next number he needs to call. However, he quickly realizes that this augmented game is much harder to calculate than the original game, so he needs your help. If little r calls out a number $x$ that itself cannot be called, you must also quickly determine that little r has lost the game.\n\nSince little r and little z have played the game for a long time, little z has many such queries that you need to answer.\n\n### Input Format\n\nThe first line contains a positive integer $T$, indicating the number of queries little z makes.\n\nThe next $T$ lines each contain a positive integer $x$, representing the number little r calls out in this round.\n\n### Output Format\n\nOutput $T$ lines. For each query:\n- If little r's number cannot be called, output $-1$.\n- Otherwise, output the next number that little z needs to call.\n\n### Sample Input\n```plaintext\n4\n6\n33\n69\n300\n```\n\n### Sample Output\n```plaintext\n8\n36\n80\n-1\n```\n\n### Sample Explanation\n\nThe explanations for the first three queries are already provided in the problem description.\n\nFor the fourth query:\n- Since $300 = 75 \\times 4$, and $75$ contains the digit $7$, little r loses the game.\n\n### Constraints\n\n- For $10\\%$ of the cases: $T \\leq 10$, $x \\leq 100$. \n- For $30\\%$ of the cases: $T \\leq 100$, $x \\leq 1000$. \n- For $50\\%$ of the cases: $T \\leq 1000$, $x \\leq 10000$. \n- For $70\\%$ of the cases: $T \\leq 10000$, $x \\leq 2 \\times 10^5$. \n- For $100\\%$ of the cases: $1 \\leq T \\leq 2 \\times 10^5$, $1 \\leq x \\leq 10^7$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2299, "prompt": "### Problem Description\n\nIn the year 3030, Macsy is deploying a group of robots on Mars.\n\nDuring the 1st second, Macsy transports Robot #1 to Mars. Robot #1 can produce other robots. \nIn the 2nd second, Robot #1 produces its first robot\u2014Robot #2. \nIn the 3rd second, Robot #1 produces another robot\u2014Robot #3.\n\nFrom then on, Robot #1 produces a new robot every second. The robot produced in the $m$-th second is numbered $m$. We can call it Robot #$m$.\n\nOnce a robot is produced, it begins working immediately. Robot #$m$ takes a rest every $m$ seconds. For example, Robot #3 takes a rest in the 6th, 9th, 12th, $\\ldots$ seconds, and works the rest of the time.\n\nWhen a robot takes a rest, its memory is transplanted into the brain of the robot that is born at that moment. For example, when Robot #6 is born, Robots #2 and #3 are both resting, so Robot #6 inherits the memories of Robots #2 and #3. We call Robots #2 and #3 the **teachers** of Robot #6.\n\nIf two robots are neither in a teacher-student relationship nor share any common teachers, they are considered to have **independent knowledge**. **Note:** Robot #1 has independent knowledge with all other robots (because only Robot #1 produces other robots), and it is not the teacher of any robot.\n\nThe **independence count** of a robot is defined as the number of robots with smaller numbers that have independent knowledge from it. For example: \n- The independence count of Robot #1 is $0$. \n- The independence count of Robot #2 is $1$ (Robot #1 is independent of it). \n- The independence count of Robot #6 is $2$ (Robots #1 and #5 are independent of it; Robots #2 and #3 are its teachers, and Robot #4 shares a common teacher\u2014Robot #2\u2014with it).\n\nThere are three different professions for newly created robots: \n- For a robot numbered $m$, if $m$ can be expressed as the product of an **even number of distinct odd prime factors**, then it is a **Politician**, e.g., Robot #15. \n- Otherwise, if $m$ is an odd prime number itself or can be expressed as the product of an **odd number of distinct odd prime factors**, then it is a **Soldier**, e.g., Robot #3 or Robot #165. \n- Robots whose numbers belong to none of the above are **Scholars**, e.g., Robot #2, Robot #6, Robot #9.\n\nRobot #$m$, born in the $m$-th second, wants to know the sum of the independence counts of all **Politicians**, **Soldiers**, and **Scholars** among itself and its teachers. However, Robot #$m$ is too busy working to calculate this, and needs your help.\n\nFor convenience, Macsy has already performed the prime factorization of $m$. To simplify the output, your task is to return all sums **modulo $10000$**.\n\n---\n\n### Input Format\n\nThe first line of the input contains a positive integer $k$, representing the number of distinct prime factors of $m$.\n\nThe following $k$ lines each contain two integers $p_i$ and $e_i$, representing the $i$-th prime factor of $m$ and its exponent $(i=1,2,\\ldots,k)$. \nThe numbers $p_1, p_2, \\ldots, p_k$ are distinct primes where $\\prod_{i=1}^k p_i^{e_i} = m$. \nThe prime factors are given in increasing order: $p_1 < p_2 < \\ldots < p_k$.\n\n---\n\n### Output Format\n\nPrint the output in three lines:\n\n1. The first line contains the sum of the independence counts of all **Politicians** among Robot #$m$ and its teachers, modulo $10000$. \n2. The second line contains the sum of the independence counts of all **Soldiers** among Robot #$m$ and its teachers, modulo $10000$. \n3. The third line contains the sum of the independence counts of all **Scholars** among Robot #$m$ and its teachers, modulo $10000$.\n\n---\n\n### Example\n\nGiven $m = 2 \\times 3^2 \\times 5 = 90$, Robot #90 has 10 teachers, and including itself, there are 11 robots in total: \n- Politicians: Robot #15 \n- Soldiers: Robots #3 and #5 \n- Scholars: Robots #2, #6, #9, #10, #18, #30, #45, and #90.\n\n**Input**: \n```\n3 \n2 1 \n3 2 \n5 1\n```\n\n**Output**: \n```\n15 \n16 \n38\n```\n\n---\n\n### Constraints and Notes\n\nFor all test cases: \n- $1 \\leq k \\leq 1000$ \n- $2 \\leq p_i < 10000$ \n- $1 \\leq e_i \\leq 10^6$\n\nYour score for a test case depends on how many of the three outputs you correctly calculate, as shown in the following table:\n\n| $x$ | Score |\n| :--: | :--: |\n| 3 | 10 |\n| 2 | 7 |\n| 1 | 4 |\n| 0 | 0 |\n\n**Note**: Even if you cannot solve a particular case, please make sure to output one number per line (even if it's incorrect), or else the checker will not grade your solution.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2500, "prompt": "### Problem Description\n\nFlappy Bird is a popular casual mobile game in which players must control the frequency of tapping the screen to adjust the bird's flight height, allowing it to pass through the gaps between the pipes on the right side of the screen. If the bird accidentally hits a pipe or falls to the ground, the game ends unsuccessfully. \n\nTo simplify the problem, the game's rules have been simplified and modified as follows:\n\n1. The game is played on a 2D plane with a width of $n$ and a height of $m$, and there are $k$ pipes in the game (pipe width can be ignored). \n2. The bird always moves within the game interface. The bird starts at an arbitrary integer height on the leftmost side of the game interface and finishes the game upon reaching the rightmost side.\n3. At each unit of time, the bird moves 1 unit distance horizontally along the x-axis. Its vertical movement is controlled by the player. If the screen is tapped, the bird rises by a certain height $X$. Multiple taps per unit time are allowed, and their effects are additive. If the screen is not tapped, the bird descends by a certain height $Y$. The rise height $X$ and fall height $Y$ may vary depending on the bird\u2019s x-coordinate position.\n4. The game ends unsuccessfully if the bird\u2019s height becomes $0$ or if it hits a pipe. When the bird's height reaches $m$, it cannot rise further.\n\nYour goal is to determine whether the game can be completed successfully. If it can, output the minimum number of screen taps required; otherwise, output the maximum number of pipe gaps the bird can pass through.\n\n---\n\n### Input Format\n\nThe first line contains 3 integers $n$, $m$, and $k$, representing the length and height of the game interface and the number of pipes, respectively, separated by a space.\n\nThe next $n$ lines each contain 2 integers $X$ and $Y$, separated by a space, representing the height $X$ the bird rises after tapping the screen and the height $Y$ the bird falls if the screen is not tapped, for each x-coordinate position from $0$ to $n-1$. \n\nThe following $k$ lines each contain 3 integers $P$, $L$, and $H$, separated by a space. Each line represents a pipe where $P$ is the x-coordinate of the pipe, $L$ is the lower bound of the pipe gap, and $H$ is the upper bound of the pipe gap (the input guarantees that the $P$ values are distinct but not necessarily sorted in order).\n\n---\n\n### Output Format\n\nThe output consists of two lines:\n\nThe first line contains a single integer. Output $1$ if the game can be successfully completed; otherwise, output $0$. \n\nThe second line contains a single integer. If the first line is $1$, output the minimum number of screen taps required to successfully complete the game; otherwise, output the maximum number of pipe gaps the bird can pass through.\n\n---\n\n### Example 1\n\n```\nInput:\n\n[Example Input]\n\nOutput:\n\n[Example Output]\n```\n\n---\n\n### Example 2\n\n```\nInput:\n\n[Example Input]\n\nOutput:\n\n[Example Output]\n```\n\n---\n\n### Constraints and Hints\n\n- For $30\\%$ of the test cases: $5 \\leq n \\leq 10, 5 \\leq m \\leq 10, k = 0$, and it is guaranteed that there exists an optimal solution where the maximum number of screen taps per unit time is $3$. \n- For $50\\%$ of the test cases: $5 \\leq n \\leq 20, 5 \\leq m \\leq 10$, and it is guaranteed that there exists an optimal solution where the maximum number of screen taps per unit time is $3$. \n- For $70\\%$ of the test cases: $5 \\leq n \\leq 1000, 5 \\leq m \\leq 100$. \n- For $100\\%$ of the test cases: $5 \\leq n \\leq 10000$, $5 \\leq m \\leq 1000$, $0 \\leq k < n$, $0 < X < m$, $0 < Y < m$, $0 < P < n$, $0 \\leq L < H \\leq m$, $L + 1 < H$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2588, "prompt": "### Problem Description\n\nCountries R and S are currently at war, with both deploying spies to infiltrate the other side's territory and take action when the opportunity arises. \nAfter a perilous journey, spy C from R successfully uncovered the cipher rules used for military communication in country S:\n\n1. The original message intended to be sent internally by S's military is encrypted before being transmitted on the network. Both the original message and the encrypted message consist of uppercase letters $A-Z$ (no spaces or other characters).\n2. Each letter has a corresponding \"cipher letter\" defined by S's military. The encryption process replaces every letter in the original message with its corresponding \"cipher letter.\"\n3. Each letter has a unique corresponding cipher letter, and different letters correspond to different cipher letters. A cipher letter may be the same as the original letter.\n\nFor example, if $\\texttt{A}$ is encrypted to $\\texttt{A}$, and $\\texttt{B}$ is encrypted to $\\texttt{C}$ (other letters and their cipher letters omitted), then the original message $\\texttt{ABA}$ is encrypted to $\\texttt{ACA}$.\n\nWith access to one encrypted message along with its corresponding original message, spy C hopes to decode the military cipher rules used by S. Spy C's deciphering process involves scanning the original message, identifying each letter $x$ (any uppercase letter) in the original message, and mapping it to its corresponding letter $y$ in the encrypted message. Thus, $y$ is considered the cipher letter for $x$. The process stops when the deciphering results in one of the following states:\n\n1. The entire message has been scanned, and all $26$ letters $\\texttt{A,B,...,Z}$ in the original message have been successfully mapped to their corresponding \"cipher letters.\"\n2. The entire message has been scanned, but some letters do not appear in the original message.\n3. Contradictions or errors are identified in the scanned information that violate the cipher rules of country S. For example, an encrypted message $\\texttt{XYZ}$ translated into $\\texttt{ABA}$ violates the rule that \"different letters correspond to different cipher letters.\"\n\nAmidst the hectic deciphering process, R's headquarters sent a telegram to Spy C asking him to translate another newly intercepted encrypted message from S. \nPlease help Spy C: Decode the cipher using the intercepted information and use it to translate the encrypted message.\n\n---\n\n### Input Format\n\nThe input consists of $3$ lines, each containing a string. \n- The $1^\\text{st}$ line is the encrypted message intercepted by Spy C.\n- The $2^\\text{nd}$ line is the original message corresponding to the encrypted message from the $1^\\text{st}$ line.\n- The $3^\\text{rd}$ line is the encrypted message to be translated, as requested by R's headquarters.\n\n---\n\n### Output Format\n\nThe output contains $1$ line. \nIf the decoding process stops at states $2$ or $3$, output `Failed` (note: the first letter must be uppercase, and the rest must be lowercase). \nOtherwise, output the translated original message of the encrypted message specified in the $3^\\text{rd}$ line.\n\n---\n\n### Sample\n\n#### Sample Input 1 \n```plain\nAA\nAB\nEOWIE\n```\n\n#### Sample Output 1 \n```plain\nFailed\n```\n\n#### Explanation for Sample 1\n\nIn the original message, letters $\\texttt{A}$ and $\\texttt{B}$ correspond to the same cipher letter, violating the rules. Hence, the output is `Failed`.\n\n---\n\n#### Sample Input 2\n```plain\nQWERTYUIOPLKJHGFDSAZXCVBN\nABCDEFGHIJKLMNOPQRSTUVWXY\nDSLIEWO\n```\n\n#### Sample Output 2\n```plain\nFailed\n```\n\n#### Explanation for Sample 2\n\nThe letter $\\texttt{Z}$ does not appear in the original message. Hence, the output is `Failed`.\n\n---\n\n#### Sample Input 3\n```plain\nMSRTZCJKPFLQYVAWBINXUEDGHOOILSMIJFRCOPPQCEUNYDUMPP\nYIZSDWAHLNOVFUCERKJXQMGTBPPKOIYKANZWPLLVWMQJFGQYLL\nFLSO\n```\n\n#### Sample Output 3\n```plain\nNOIP\n```\n\n---\n\n### Constraints and Notes\n\nFor all test cases:\n- All strings consist only of uppercase English letters.\n- The length of each string is between $1$ and $100$.\n- The lengths of the strings in the $1^\\text{st}$ and $2^\\text{nd}$ lines are guaranteed to be equal.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 2357, "prompt": "### Problem Description\nIn the Magic Land, a notorious thief named Frank has surfaced, stealing confidential documents from government agencies across the kingdom. Some suspect that Frank might be an enemy spy. \nTo apprehend Frank, Magic Land's Security Bureau has launched a decisive operation!\n\nMagic Land consists of $N$ cities connected exactly by $N-1$ roads, ensuring that any two cities can be reached via the roads. From a data structure perspective, the $N$ cities and $N-1$ roads form a **tree**. \nFor instance, the diagram below shows a possible layout of Magic Land (4 cities denoted by numbers, connected by 3 roads denoted by letters):\n\n![Capture.JPG](https://i.loli.net/2018/02/12/5a8151a539c8f.jpg)\n\nFrank can move along the roads at any speed he desires. \nFor example, in the layout above, Frank can travel from city $1$ to city $4$ via city $2$ in $0.00001$ seconds (or within any arbitrarily small time), traversing two roads.\n\nCapturing Frank alive is a daunting task, so the Security Bureau has dispatched highly skilled detectives with extraordinary tracking abilities:\n- If a detective and Frank are in the same city, the detective will immediately detect and capture Frank.\n- Although Frank can move quickly along the roads, a detective will still detect and capture Frank if they encounter him while traveling on the same road.\n\nThe Security Bureau has no information about Frank's exact location\u2014he could be hiding in any city or traveling along any road. Therefore, a detailed capture plan must be devised consisting of several steps. During each step, you can perform one of the following actions:\n- **Deploy a detective at a city.** A detective can directly parachute into any city in Magic Land from headquarters. This operation is denoted by ```L x```, meaning a detective is deployed to city $x$. This takes $1$ second.\n- **Recall a detective from a city.** A detective stationed at a city can be summoned back to headquarters for re-deployment later. This operation is denoted by ```B x```, meaning a detective is recalled from city $x$. This takes $1$ second.\n- **Move a detective along a road.** A detective stationed at city $x$ can move along a connected road to city $y$. This operation is denoted by ```M x y```, meaning the detective moves from city $x$ to city $y$. This takes $1$ second. If Frank happens to be traveling along the same road at the same time, he will be captured.\n\nYour task is to devise a capture plan comprising several steps, ensuring that:\nNo matter where Frank initially hides or how cleverly he moves (Frank may even acquire the capture plan, so he will try his best to evade capture), he will inevitably be captured. \nThe number of involved detectives should be minimized because experienced detectives are scarce.\n\nFor instance, consider the example layout above. A possible valid capture plan:\n1. ```L 2```: Deploy a detective to city $2$. After this step, Frank cannot be hiding in city $2$, or he would already have been captured.\n2. ```L 2```: Deploy another detective to city $2$.\n3. ```M 2 1```: Have one detective from city $2$ move to city $1$. Note that one detective still remains in city $2$. After this step, Frank cannot be hiding in city $1$ or traveling along road $A$. Thus, if Frank has not been captured yet, he must be hiding in city $3$ or city $4$, or traveling along road $B$ or road $C$.\n4. ```B 1```: Recall a detective from city $1$. Although the detective has been recalled, one detective stationed at city $2$ ensures Frank cannot travel to city $1$ or road $A$.\n5. ```L 3```: Deploy a detective to city $3$. This could be the detective recalled earlier. After this step, Frank cannot be hiding in city $3$, or he would already have been captured.\n6. ```M 3 2```: Have one detective from city $3$ move back to city $2$. After this step, if Frank has not been captured yet, he must be traveling along road $C$ or hiding in city $4$. Note that after this step, two detectives are stationed at city $2$.\n7. ```M 2 4```: Have one detective from city $2$ move to city $4$. After this step, Frank will surely be captured, unless he was never in Magic Land to begin with. \nThis plan involves a total of $2$ detectives and guarantees capturing Frank. It can be proven that using $1$ or fewer detectives is insufficient for capturing Frank.\n\nYour simple mission: Given an input representing Magic Land's layout, determine $S$, the minimum number of detectives required to apprehend Frank, and provide the detailed steps for the capture plan.\n\n---\n\n### Input Format\nThe input describes the layout of Magic Land: \nThe first line contains an integer $N$, representing the number of cities, numbered $1, 2, \\dots, N$. \nThe next $N-1$ lines each contain two integers $x_i, y_i$, indicating that cities $x_i$ and $y_i$ are connected by a road. It is guaranteed that $1 \\leqslant x_i, y_i \\leqslant N$.\n\n---\n\n### Output Format\nOutput the devised capture plan as follows: \nThe first line should contain an integer $S$, representing the minimum number of detectives required. \nThe second line should contain an integer $T$, representing the total number of steps in the capture plan. \nThe next $T$ lines should describe the steps in the plan, where each line will be one of the following:\n- ```L x```, where ```L``` is a capital letter followed by a space and then an integer $x$, indicating a detective being deployed to city $x$. Ensure $1 \\le x \\le N$.\n- ```B x```, where ```B``` is a capital letter followed by a space and then an integer $x$, indicating a detective being recalled from city $x$. Ensure $1 \\le x \\le N$, and ensure city $x$ has at least one detective present before this step.\n- ```M x y```, where ```M``` is a capital letter followed by a space, an integer $x$, another space, and an integer $y$, indicating a detective moving from city $x$ to city $y$. Ensure $1 \\leq x, y \\leq N$, and ensure city $x$ has at least one detective before this step, and that cities $x$ and $y$ are directly connected by a road.\n\nOutput must ensure that $S$ matches the actual number of detectives involved in the capture plan.\n\n---\n\n### Example \n\n#### Input\n```\n4\n1 2\n2 3\n2 4\n```\n\n#### Output\n```\n2\n7\nL 2\nL 2\nM 2 1\nB 1\nL 3\nM 3 2\nM 2 4\n```\n\n---\n\n### Constraints and Hints \n#### Data Constraints\nThe input is guaranteed to represent a connected tree with $N$ nodes, $1 \\le N \\le 1000$. \n\n#### Scoring Standards\nFor each test case:\n- If the output plan is invalid, the total number of steps $T$ exceeds $20000$, or the plan fails to guarantee Frank's capture, the case scores $0$. \n- Otherwise, compare your output $S$ with the known optimal solution $S^*$:\n - If $S < S^*$: **100% of points**.\n - If $S = S^*$: **100% of points**.\n - If $S^* < S \\leq S^* + 2$: **60% of points**.\n - If $S^* + 2 < S \\leq S^* + 4$: **40% of points**.\n - If $S^* + 4 < S \\leq S^* + 8$: **20% of points**.\n - If $S > S^* + 8$: **10% of points**.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3850, "prompt": "### Problem Description\n\nZhu Youyang is a laid-back university student who still dreams of solving NPC problems in polynomial time every day.\n\nIn class, Zhu Youyang learned that the subgraph isomorphism problem is an NPC problem. He plans to present a polynomial-time decision algorithm for the subgraph isomorphism problem as indirect evidence to prove \\( P = NP \\). If successful, he could win the prestigious Turing Award for this groundbreaking work! Unfortunately, Zhu Youyang\u2019s knowledge is limited, and he hasn\u2019t even figured out why the subgraph isomorphism problem belongs to NPC. Thus, he decided to settle for solving a simpler problem:\n\nGiven two rooted trees \\( G \\) and \\( H \\), where \\( \\lvert G \\rvert \\) represents the number of nodes in tree \\( G \\). These two trees satisfy the following constraints: \\( 1 \\leq \\lvert H \\rvert \\leq \\lvert G \\rvert \\leq \\lvert H \\rvert + k \\). Here \\( k \\) is guaranteed by Zhu Youyang to be a small constant.\n\nZhu Youyang can delete any nodes from \\( G \\), resulting in a subgraph \\( G' \\). He wants to know whether there exists a way of deleting nodes such that the resulting subgraph \\( G' \\) meets the following conditions:\n\n- \\( G' \\) is connected.\n- \\( G' \\) includes the root node of \\( G \\) (i.e., the root node of \\( G \\) is not deleted).\n- \\( G' \\) is isomorphic to \\( H \\) (i.e., there exists a way to relabel the nodes of \\( G' \\) such that the relabeled graph is identical to \\( H \\), and the root node of \\( G \\) maps to the root node of \\( H \\)).\n\n---\n\n### Input Format\n\nRead input data from the file `iso.in`.\n\nThe problem contains multiple test cases.\n\nThe first line of input contains two positive integers \\( C, T \\) and one non-negative integer \\( k \\). These three numbers represent the test point number, the number of test data cases, and a given constant in the problem. If the current test case is a sample, then \\( C = 0 \\). It is guaranteed that \\( T \\leq 500 \\) and \\( k \\leq 5 \\).\n\nFor each test case:\n\n- The first line contains a positive integer \\( n_1 \\), representing the number of nodes in tree \\( G \\). It is guaranteed that \\( 1 \\leq n_1 \\leq 10^5 \\), and \\( \\sum n_1 \\leq 5 \\times 10^5 \\).\n- The second line contains \\( n_1 \\) integers describing the structure of tree \\( G \\). Specifically, the \\( i \\)-th (\\( 1 \\leq i \\leq n_1 \\)) integer \\( a_i \\) represents the parent node of node \\( i \\) in \\( G \\). If the node is the root, then \\( a_i = -1 \\). It is guaranteed that under these rules, the input forms a connected rooted tree.\n- The third line contains a positive integer \\( n_2 \\), representing the number of nodes in tree \\( H \\). For all test cases, it is guaranteed that \\( \\max(1, n_1 - k) \\leq n_2 \\leq n_1 \\).\n- The fourth line contains \\( n_2 \\) integers describing the structure of tree \\( H \\). Specifically, the \\( i \\)-th (\\( 1 \\leq i \\leq n_2 \\)) integer \\( b_i \\) represents the parent node of node \\( i \\) in \\( H \\). If the node is the root, then \\( b_i = -1 \\). It is guaranteed that under these rules, the input forms a connected rooted tree.\n\n---\n\n### Output Format\n\nWrite output data to the file `iso.out`.\n\nFor each test case:\n\nOutput a single string. If there exists a way to delete nodes from \\( G \\) such that the three conditions above are simultaneously satisfied, output `Yes`; otherwise, output `No`.\n\n---\n\n### Sample 1\n\nIn the first test point, we delete node \\( 1 \\) from the first tree. The remaining tree is isomorphic to the second tree, both being rooted trees with two nodes; hence the output is `Yes`.\n\n![iso1.png](https://img.loj.ac.cn/2022/08/30/110da22a49785.png)\n\nIn the second test point, the depth of the first input tree is \\( 1 \\), but the depth of the second input tree is \\( 2 \\). Thus, no matter how we delete nodes from the first tree, its depth will not increase to \\( 2 \\). Therefore, the output is `No`.\n\n![iso2.png](https://img.loj.ac.cn/2022/08/30/5ad431b49689b.png)\n\nIn the third test point, both input trees are isomorphic to the tree shown below; hence the output is `Yes`.\n\n![iso3.png](https://img.loj.ac.cn/2022/08/30/58fdaeb100c53.png)\n\n---\n\n### Sample 2\n\nSee the files `iso/iso2.in` and `iso/iso2.ans` provided in the attachment. This sample data corresponds to test points \\( 7 \\sim 8 \\).\n\n---\n\n### Sample 3\n\nSee the files `iso/iso3.in` and `iso/iso3.ans` provided in the attachment. This sample data corresponds to test points \\( 9 \\sim 10 \\).\n\n---\n\n### Sample 4\n\nSee the files `iso/iso4.in` and `iso/iso4.ans` provided in the attachment. This sample data corresponds to test point \\( 13 \\).\n\n---\n\n### Constraints and Notes\n\nFor all test cases, \\( 1 \\leq T \\leq 500 \\), \\( 1 \\le n_2 \\leq n_1 \\leq 10^5 \\), \\( \\sum n_1 \\leq 5 \\times 10^5 \\), \\( 0 \\leq k \\leq 5 \\).\n\nThe data has no **targeted adversarial construction against any reasonable hash algorithm**, meaning that you don\u2019t need to worry excessively about losing points due to hash collisions.\n\nThe additional constraints for specific test points are as follows:\n\n| \\( n_1, n_2 \\) | \\( \\sum n_1 \\) | Test Points | \\( k \\) | Special Properties |\n|:----------------:|:-----------------------:|:---------------------:|:------------:|:---------------------------:|\n| \\( \\leq 8 \\) | \\( \\leq 500 \\) | \\( 1 \\sim 3 \\) | \\( \\leq 0 \\) | None |\n| \\( \\leq 8 \\) | \\( \\leq 500 \\) | \\( 4 \\sim 6 \\) | \\( \\leq 5 \\) | None |\n| \\( \\leq 16 \\) | \\( \\leq 10^3 \\) | \\( 7 \\sim 8 \\) | \\( \\leq 0 \\) | None |\n| \\( \\leq 16 \\) | \\( \\leq 10^3 \\) | \\( 9 \\sim 10 \\) | \\( \\leq 5 \\) | None |\n| \\( \\leq 150 \\) | \\( \\leq 10^4 \\) | \\( 11 \\) | \\( \\leq 0 \\) | None |\n| \\( \\leq 150 \\) | \\( \\leq 10^4 \\) | \\( 12 \\) | \\( \\leq 1 \\) | None |\n| \\( \\leq 150 \\) | \\( \\leq 10^4 \\) | \\( 13 \\) | \\( \\leq 5 \\) | None |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 14 \\sim 16 \\) | \\( \\leq 0 \\) | A |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 17 \\sim 20 \\) | \\( \\leq 0 \\) | B |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 21 \\) | \\( \\leq 1 \\) | None |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 22 \\sim 23 \\) | \\( \\leq 3 \\) | None |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 24 \\sim 25 \\) | \\( \\leq 5 \\) | None |\n\nThe special properties mentioned above are described as follows:\n\n- **Special Property A**: The rooted tree \\( G \\) ensures that each node is either a leaf node or has exactly \\( 1 \\) child node; equivalently, \\( G \\) forms a chain, and the root node is one end of the chain.\n- **Special Property B**: The rooted tree \\( G \\) ensures that each node is either a leaf node or has exactly \\( 2 \\) child nodes, and all leaf nodes have the same depth; equivalently, \\( G \\) forms a complete binary tree, and the root node is the root of the complete binary tree.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3536, "prompt": "### Problem Description\n\nYelekastee is a renowned archaeologist in the country U. During his recent archaeological expedition, he unearthed an ancient safe. After meticulous research, Yelekastee discovered that the password to the safe is associated with a sequence $\\{ a_n \\}$. The sequence $\\{ a_n \\}$ can be constructed as follows:\n\n1. Initially, the sequence has a length of $2$, with $a_0 = 0$ and $a_1 = 1$.\n2. The sequence undergoes a series of operations, where each operation is one of the following two types:\n - `W` type: Add $1$ to the **last element** of the sequence.\n - `E` type: If the **last element** of the sequence is $1$, add $1$ to the second-to-last element. Otherwise, subtract $1$ from the **last element**, then append two elements to the sequence, both with a value of $1$.\n\nDue to technical constraints, the safe cannot examine the entire sequence. Instead, the password is determined by applying a function $f$ to the sequence $\\{ a_n \\}$, where $f$ is defined as follows:\n\n$$ f(a_0, \\ldots , a_{k - 1}, a_k) = \\begin{cases} a_0, & k = 0 \\\\ f \\! \\left( a_0, a_1, \\ldots , a_{k - 2}, a_{k - 1} + \\frac{1}{a_k} \\right) \\! , & k \\ge 1 \\end{cases} $$\n\nYelekastee is not skilled in calculations, so he sought your help to compute the password of the safe based on a sequence of operations he provides. Unfortunately, his memory is not very reliable, and he may change the operation sequence at any time. These changes are of the following three types:\n\n- `APPEND c`: Append an operation of type `c` to the end of the current sequence, where `c` is a character `W` or `E`.\n- `FLIP l r`: Reverse the type of every operation from the $l$-th to the $r$-th (inclusive, 1-based index) in the current sequence \u2014 in other words, change all `W` to `E` and all `E` to `W`.\n- `REVERSE l r`: Reverse the order of operations from the $l$-th to the $r$-th (inclusive, 1-based index) in the current sequence.\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $q$, representing the initial length of the operation sequence and the number of modifications.\n\nThe second line contains a string of length $n$ consisting only of uppercase letters `W` and `E`, representing the initial operation sequence.\n\nThe following $q$ lines each describe one modification, formatted as described in the problem description.\n\n### Output Format\n\nOutput a total of $q + 1$ lines. The first line contains two integers representing the password of the safe for the initial operation sequence. The next $q$ lines each contain two integers, representing the password of the safe after each modification.\n\nThe password is guaranteed to be a positive rational number. If the actual password is $\\frac{a}{b}$, where $a, b > 0$ and $\\gcd(a, b) = 1$, then you must output $a$ and $b$ modulo $998244353$ on the corresponding line.\n\n**Explanation of Sample #1**\n\n| | Operation Sequence | Sequence $\\{ a_n \\}$ | Password |\n|:-:|:-:|:-:|:-:|\n| Initial | `WE` | $(0, 1, 1, 1)$ | $\\frac{2}{3}$ |\n| After 1st modification | `WEE` | $(0, 1, 2, 1)$ | $\\frac{3}{4}$ |\n| After 2nd modification | `EWE` | $(1, 1, 1, 1)$ | $\\frac{5}{3}$ |\n| After 3rd modification | `EEW` | $(2, 2)$ | $\\frac{5}{2}$ |\n\n**Sample #2**\n\nSee the file `code/code2.in` and `code/code2.ans`.\n\nThis sample satisfies the same constraints as test cases $1 \\sim 4$.\n\n**Sample #3**\n\nSee the file `code/code3.in` and `code/code3.ans`.\n\nThis sample satisfies the same constraints as test cases $5 \\sim 7$.\n\n**Sample #4**\n\nSee the file `code/code4.in` and `code/code4.ans`.\n\nThis sample satisfies the same constraints as test cases $8 \\sim 10$.\n\n**Sample #5**\n\nSee the file `code/code5.in` and `code/code5.ans`.\n\nThis sample satisfies the same constraints as test cases $15 \\sim 20$.\n\n---\n\n### Constraints\n\nFor all test cases: $1 \\le n \\le {10}^5$, $1 \\le q \\le {10}^5$.\n\nFor the `APPEND` operation, it is guaranteed that `c` is either the uppercase English letter `W` or `E`.\n\nFor the `FLIP` and `REVERSE` operations, it is guaranteed that $1 \\le l \\le r \\le L$ where $L$ is the current length of the operation sequence.\n\nNote that due to the `APPEND` operation, the length of the operation sequence can grow up to a maximum of $2 \\times {10}^5$.\n\n| Test Case Range | $n, q \\le$ | Special Constraints |\n|:-:|:-:|:-:|\n| $1 \\sim 4$ | $2000$ | None |\n| $5 \\sim 7$ | ${10}^5$ | A |\n| $8 \\sim 10$ | ${10}^5$ | B, C |\n| $11 \\sim 14$ | ${10}^5$ | C |\n| $15 \\sim 20$ | ${10}^5$ | None |\n\nSpecial Constraint A: The operation sequence never contains two consecutive identical characters at any time.\n\nSpecial Constraint B: No `FLIP` modification occurs in this case.\n\nSpecial Constraint C: No `REVERSE` modification occurs in this case.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2590, "prompt": "### Problem Description\nCountry C has $n$ major cities and $m$ roads, where each road connects two of these cities. There is at most one road directly connecting any pair of cities. Among these $m$ roads, some are one-way roads, while others are two-way roads. Note that a two-way road is also counted as one road in the total count.\n\nCountry C spans a vast territory, with resources distributed unevenly across different regions. This results in the price of a particular commodity not necessarily being the same in different cities. However, the buying and selling price of the same commodity in the same city is always the same.\n\nA merchant, Alon, is visiting Country C for tourism. Upon learning that the price of the same commodity can differ among cities, he decides to make some extra money to cover his travel expenses by taking advantage of the price differences while traveling. Suppose the cities in Country C are numbered from $1$ to $n$. Alon plans to start his journey in City $1$ and end it at City $n$. During his journey, he may visit any city multiple times but is not required to visit all $n$ cities.\n\nAlon earns travel expenses by trading in his favorite commodity\u2014a crystal ball. He will select a city that he passes through to purchase the crystal ball and then sell it in a subsequent city he visits, making a profit from the price difference. Since Alon\u2019s primary purpose is tourism, he decides to perform this trade at most once. If he cannot make a profit, he will opt not to trade.\n\nConsider an example where Country C has $5$ cities, and the roads connecting them are depicted in the diagram below. A unidirectional arrow represents a one-way road, while a bidirectional arrow represents a two-way road.\n\n![27.png](https://i.loli.net/2018/05/22/5b03da6422dfe.png)\n\nSuppose the crystal ball prices for Cities $1$ through $n$ are $4,3,5,6,1$ respectively.\n\nAlon can choose the route $1 \\to 2 \\to 3 \\to 5$, where he buys a crystal ball in City $2$ at a price of $3$ and sells it in City $3$ at a price of $5$, earning a profit of $2$.\n\nAlternatively, Alon could choose the route $1 \\to 4 \\to 5 \\to 4 \\to 5$. In this case, he buys the crystal ball at City $5$ for $1$ upon his first visit there and sells it at City $4$ for $6$ during his second visit, earning a profit of $5$.\n\nGiven the crystal ball prices in all $n$ cities and the information about the $m$ roads (the cities they connect and their transport direction), your task is to determine the maximum profit Alon can earn. If no profit can be made, output $0$.\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, separated by a space, representing the number of cities and the number of roads, respectively.\n\nThe second line contains $n$ positive integers, separated by spaces, representing the commodity prices in the $n$ cities in order of their city numbers.\n\nThe next $m$ lines each contain three positive integers $x, y, z$, separated by spaces:\n- If $z=1$, it indicates a one-way road from City $x$ to City $y$.\n- If $z=2$, it indicates a two-way road between City $x$ and City $y$.\n\n---\n\n### Output Format\nOutput a single integer: the maximum profit Alon can earn. If no profitable trade can be made, output $0$.\n\n---\n\n### Sample Input\n```plain\n5 5\n4 3 5 6 1\n1 2 1\n1 4 1\n2 3 2\n3 5 1\n4 5 2\n```\n\n### Sample Output\n```plain\n5\n```\n\n---\n\n### Constraints and Hints\n- The input guarantees that City $1$ can reach City $n$.\n- For $10\\%$ of the cases, $n \\leq 6$.\n- For $30\\%$ of the cases, $n \\leq 100$.\n- For $50\\%$ of the cases, it is guaranteed that there does not exist a travel route that starts and ends at the same city.\n- For $100\\%$ of the cases:\n - $1 \\leq n \\leq 100,000$\n - $1 \\leq m \\leq 500,000$\n - $1 \\leq x, y \\leq n$\n - $1 \\leq z \\leq 2$\n - $1 \\leq$ price of crystal balls in each city $\\leq 100$\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2362, "prompt": "### Problem Description\n> Cricket Kingdom is currently suffering from a rampant outbreak of earthworms! The fleas from Flea Kingdom next door are also helpless against the earthworms, so the King of Cricket Kingdom decided to enlist the help of the Divine Sword Master to eliminate the earthworms.\n\nIn this problem, the symbol $ \\lfloor c \\rfloor $ is used to denote the floor function, which rounds $ c $ down to the nearest integer. For example: $ \\lfloor 3.0 \\rfloor = \\lfloor 3.1 \\rfloor = \\lfloor 3.9 \\rfloor = 3 $.\n\nThere are a total of $ n $ earthworms in Cricket Kingdom (where $ n $ is a positive integer). Each earthworm has a length, and the $ i $-th earthworm's length is denoted by $ a_i $ ($ i = 1, 2, \\ldots, n $). All lengths are guaranteed to be non-negative integers (i.e., an earthworm with a length of $ 0 $ is possible).\n\nEvery second, the Divine Sword Master will find the longest earthworm among all the earthworms (if there are ties, any one of the longest earthworms may be chosen) and cut it into two pieces. The position where the worm is cut is determined by a constant $ p $ (a rational number satisfying $ 0 < p < 1 $). If the worm's length is $ x $, it will be split into two new worms with lengths $ \\lfloor px \\rfloor $ and $ x - \\lfloor px \\rfloor $, respectively. Notably, if either of these two numbers equals $ 0 $, the new worm of length $ 0 $ will also be retained. Additionally, all other earthworms grow in length by $ q $ (a non-negative constant) every second except for the two newly generated worms.\n\nThe King of Cricket Kingdom knows that this situation cannot be sustained indefinitely because the number of worms and their lengths will only increase. He plans to seek aid from a mysterious figure with mystical powers, but the help will arrive only after $ m $ seconds\u2026\u2026 (where $ m $ is a non-negative integer).\n\nThe King of Cricket Kingdom wants to know what will happen during the $ m $ seconds before help arrives. Specifically, he wants the following information:\n\n* The lengths of the earthworms that were cut at each second during the $ m $ seconds (a total of $ m $ numbers).\n* The lengths of all the earthworms $ m $ seconds later (a total of $ n + m $ numbers).\n\nThe King of Cricket Kingdom obviously knows how to figure this out! But he wants to test your skills\u2026\n\n---\n\n### Input Format\nThe first line consists of six integers: $ n $, $ m $, $ q $, $ u $, $ v $, $ t $. Here:\n\n- $ n $, $ m $, and $ q $ have the same meaning as described in the \"Problem Description\".\n- $ u $ and $ v $ are both positive integers. You need to calculate $ p = \\frac{u}{v} $ (it is guaranteed that $ 0 < u < v $).\n- $ t $ is a positive integer, and its meaning will be explained in the \"Output Format\" section.\n\nThe second line contains $ n $ non-negative integers, representing the initial lengths of the $ n $ earthworms: $ a_1, a_2, \\ldots, a_n $.\n\nThe integers on the same line are separated by a single space.\n\nIt is guaranteed that:\n- $ 1 \\leq n \\leq 10 ^ 5$\n- $ 0 < m < 7 \\times 10 ^ 6 $\n- $ 0 < u < v < 10 ^ 9 $\n- $ 0 \\leq q \\leq 200 $\n- $ 1 < t < 71 $\n- $ 0 < a_i < 10 ^ 8 $\n\n---\n\n### Output Format\nThe first line should output $ \\lfloor \\frac{m}{t} \\rfloor $ integers. These integers represent the lengths of the earthworms that were cut at the $ t $-th second, $ 2t $-th second, $ 3t $-th second, and so on, in chronological order.\n\nThe second line should output $ \\lfloor \\frac{(n+m)}{t} \\rfloor $ integers. These integers represent the lengths of the earthworms after $ m $ seconds, sorted in descending order, and correspond to the $ t $-th largest length, $ 2t $-th largest length, $ 3t $-th largest length, and so on.\n\nThe integers on the same line should be separated by a single space. Even if a specific line contains no integers to output, you must still output an empty line.\n\nPlease refer to the examples below for a better understanding of the format.\n\n---\n\n### Sample 1\nBefore the Divine Sword Master arrives, the lengths of the 3 earthworms are $ 3, 3, 2 $.\n\n- After 1 second: One earthworm of length $ 3 $ is cut into two new earthworms of lengths $ 1 $ and $ 2 $. The remaining earthworms' lengths increase by $ 1 $. The final lengths of the 4 earthworms are $ (1, 2), 4, 3 $, where parentheses indicate the newly generated worms.\n \n- After 2 seconds: One earthworm of length $ 4 $ is cut into $ 1 $ and $ 3 $. The lengths of the resulting 5 earthworms are: $ 2, 3, (1, 3), 4 $.\n\n- After 3 seconds: One earthworm of length $ 4 $ is cut. The lengths of the resulting 6 earthworms are: $ 3, 4, 2, 4, (1, 3) $.\n\n- After 4 seconds: One earthworm of length $ 4 $ is cut. The lengths of the resulting 7 earthworms are: $ 4, (1, 3), 3, 5, 2, 4 $.\n\n- After 5 seconds: One earthworm of length $ 5 $ is cut. The lengths of the resulting 8 earthworms are: $ 5, 2, 4, 4, (1, 4), 3, 5 $.\n\n- After 6 seconds: One earthworm of length $ 5 $ is cut. The lengths of the resulting 9 earthworms are: $ (1, 4), 3, 5, 5, 2, 5, 4, 6 $.\n\n- After 7 seconds: One earthworm of length $ 6 $ is cut. The lengths of the resulting 10 earthworms are: $ 2, 5, 4, 6, 6, 3, 6, 5, (2, 4) $.\n\nThus, during these 7 seconds, the lengths of the earthworms that were cut are $ 3, 4, 4, 4, 5, 5, 6 $. After 7 seconds, the lengths of all the earthworms sorted in descending order are $ 6, 6, 6, 5, 5, 4, 4, 3, 2, 2 $.\n\n---\n\n### Sample 2\nIn this test case, only $ t = 2 $ differs from the previous test case. The output will include numbers at intervals of every two seconds instead of one.\n\nEven if the first line's last number $ 6 $ is not output, the second line must recompute and output the results starting from the second number onward.\n\n---\n\n### Sample 3\nIn this test case, only $ t = 9 $ differs from the previous test case.\n\nNote that the first line may have no numbers to output, but an empty line must still be printed.\n\n---\n\n### Constraints and Hints\n- $ 1 \\leq n \\leq 10 ^ 5 $\n- $ 0 \\leq m \\leq 7 \\times 10 ^ 6 $\n- $ 1 \\leq t \\leq 71 $\n- $ 0 \\leq a_i \\leq 10 ^ 8 $\n- $ 1 \\leq v \\leq 10 ^ 9 $\n- $ 0 \\leq q \\leq 200 $\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 4002, "prompt": "### Problem Description\n\nToday, Little L learned Kleene's three-valued logic.\n\nIn three-valued logic, the value of a variable can be: true ($\\mathit{True}$, abbreviated as $\\mathit{T}$), false ($\\mathit{False}$, abbreviated as $\\mathit{F}$), or unknown ($\\mathit{Unknown}$, abbreviated as $\\mathit{U}$).\n\nLogical operations can also be defined in three-valued logic. Since Little L learned at a slow pace, he only grasped the logic NOT operation $\\lnot$. Its rules of execution are:\n$$\\lnot \\mathit{T} = \\mathit{F}, \\lnot \\mathit{F} = \\mathit{T}, \\lnot\\mathit{U} = \\mathit{U}.$$\n\nNow, Little L has $n$ three-valued logic variables $x_1,\\cdots, x_n$. Little L decided to conduct some interesting experiments, so he wrote $m$ statements. The statements take the following three forms, where $\\leftarrow$ represents assignment:\n\n1. $x_i \\leftarrow v$, where $v$ is one of $\\mathit{T}, \\mathit{F}, \\mathit{U}$;\n2. $x_i \\leftarrow x_j$;\n3. $x_i \\leftarrow \\lnot x_j$.\n\nInitially, Little L will assign initial values to these variables, and then execute these $m$ statements sequentially.\n\nLittle L hopes that after all the statements are executed, the final values of all variables are the same as their initial values. Under this premise, Little L hopes to minimize the number of variables with $\\mathit{Unknown}$ initial values.\n\nIn this problem, you need to help Little L find an initial assignment scheme with the minimum number of $\\mathit{Unknown}$ variables, such that after executing all the statements, all variables\u2019 final values are the same as their initial values. Little L guarantees that for all the test cases in this problem, such an assignment scheme always exists.\n\n### Input Format\n\n**This problem\u2019s test cases include multiple groups of test data.**\n\nThe first line of input contains two integers $c$ and $t$, representing the test point ID and the number of test data groups respectively. In the samples, $c$ indicates that this sample has the same constraints as test point $c$.\n\nFor each group of test data:\n\n- The first line contains two integers $n$ and $m$, representing the number of variables and the number of statements respectively.\n- The next $m$ lines describe each statement in execution order:\n - The first character $v$ specifies the type of the statement. It is guaranteed that $v$ is one of `TFU+-`.\n - If $v$ is one of `TFU`, one integer $i$ follows, indicating the statement $x_i \\leftarrow v$;\n - If $v$ is `+`, two integers $i, j` follow, indicating the statement $x_i \\leftarrow x_j$;\n - If $v$ is `-`, two integers $i, j` follow, indicating the statement $x_i \\leftarrow \\lnot x_j$.\n\n### Output Format\n\nFor each test data group, output one integer on a separate line, representing the minimum number of $\\mathit{Unknown}$ variables in all valid initial assignment schemes.\n\n**\u3010Sample Explanation #1\u3011**\n\nIn the first group of test data, the $m$ statements are:\n\n- $x_2 \\leftarrow \\lnot x_1$;\n- $x_3 \\leftarrow \\lnot x_2$;\n- $x_1 \\leftarrow x_3$.\n\nA valid initial assignment scheme is $x_1 = \\mathit{T}, x_2 = \\mathit{F}, x_3 = \\mathit{T}$, with $0$ $\\mathit{Unknown}$ variables. Since no scheme has fewer than $0$ $\\mathit{Unknown}$ variables, the output is $0$.\n\nIn the second group of test data, the $m$ statements are:\n\n- $x_2 \\leftarrow \\lnot x_1$;\n- $x_3 \\leftarrow \\lnot x_2$;\n- $x_1 \\leftarrow \\lnot x_3$.\n\nThe only valid initial assignment scheme is $x_1 = x_2 = x_3 = \\mathit{U}$, with $3$ $\\mathit{Unknown}$ variables. Therefore, the output is $3$.\n\nIn the third group of test data, the $m$ statements are:\n\n- $x_2 \\leftarrow \\mathit{T}$;\n- $x_2 \\leftarrow \\mathit{U}$;\n\nOne valid assignment scheme minimizing the number of $\\mathit{Unknown}$ variables is $x_1 = \\mathit{T}, x_2 = \\mathit{U}$. $x_1 = x_2 = \\mathit{U}$ is also valid but does not minimize the number of $\\mathit{Unknown}$ variables.\n\n**\u3010Sample Explanation #2\u3011**\n\nThis sample satisfies the constraints of test point $2$.\n\n**\u3010Sample Explanation #3\u3011**\n\nThis sample satisfies the constraints of test point $5$.\n\n**\u3010Sample Explanation #4\u3011**\n\nThis sample satisfies the constraints of test point $8$.\n\n### Constraints\n\nFor all test data, it is guaranteed that:\n\n- $1 \\le t \\le 6$, $1 \\le n,m \\le 10 ^ 5$;\n- For each operation, $v$ is one of `TFU+-`, $1 \\le i,j \\le n$.\n\n| Test Point ID | $n,m\\leq$ | Possible Values of $v$ |\n| :------------: | :-------: | :--------------------: |\n| $1,2$ | $10$ | $\\mathit{TFU+-}$ |\n| $3$ | $10^3$ | $\\mathit{TFU}$ |\n| $4$ | $10^5$ | $\\mathit{TFU}$ |\n| $5$ | $10^3$ | $\\mathit{U+}$ |\n| $6$ | $10^5$ | $\\mathit{U+}$ |\n| $7$ | $10^3$ | $\\mathit{+-}$ |\n| $8$ | $10^5$ | $\\mathit{+-}$ |\n| $9$ | $10^3$ | $\\mathit{TFU+-}$ |\n| $10$ | $10^5$ | $\\mathit{TFU+-}$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3980, "prompt": "### Problem Description\n\nEight years ago, Xiao B saw an osmanthus tree which was a tree $T$ with $n$ nodes, where **it is guaranteed that the parent node of any non-root node has a smaller ID than that node itself**. Given an integer $k$, a tree $T^{\\prime}$ with $(n+m)$ nodes is called *prosperous* if and only if it satisfies all the following conditions:\n\n1. For any pair $(i, j)$ satisfying $1 \\le i, j \\le n$, the lowest common ancestor (LCA) of nodes $i$ and $j$ in both $T$ and $T^{\\prime}$ must have the same ID.\n2. For any pair $(i, j)$ satisfying $1 \\le i, j \\le n+m$, the LCA of nodes $i$ and $j$ in $T^{\\prime}$ must not exceed $\\max(i, j) + k$.\n\n**Note:** All tree nodes in this problem use 1-based indexing, and the root node is indexed as 1. Tree $T^{\\prime}$ is not required to satisfy the condition where the parent ID of a non-root node is smaller than its own ID.\n\nXiao B wants to know how many different trees with $(n+m)$ nodes are prosperous. Two trees are considered different if and only if there exists a node whose parent ID in the two trees is different. You should output the number of such prosperous trees modulo $(10^9 + 7)$.\n\n---\n\n### Input Format\n\n**This problem contains multiple test cases.**\n\nThe first line contains two integers $c, t$, indicating the test point index and the number of test cases respectively. If $c = 0$, the test point corresponds to the stated examples.\n\nFor each test case, the input is formatted as follows:\n\n- The first line of each test case contains three integers $n, m, k$.\n- The second line contains $(n-1)$ integers $f_2, f_3, \\dots, f_n$, where $f_i$ indicates the parent ID of node $i$ in $T$.\n\n---\n\n### Output Format\n\nFor each test case, output a single line containing one integer, which is the number of prosperous trees modulo $(10^9 + 7)$.\n\n---\n\n### **Sample Explanation #1**\n\nFor the first test case in the sample, there are three prosperous trees. The sequences of parent IDs $\\{f_2, f_3\\}$ for these trees are $\\{1,1\\}$, $\\{3,1\\}$, and $\\{1,2\\}$. Note that the second line of the input for this test case is empty.\n\nFor the second and third test cases in the sample, there are a total of $16$ prosperous trees that satisfy the first condition, but only those with a parent sequence $\\{4,4,1\\}$ fail to satisfy the second condition in the third test case.\n\n---\n\n### **Sample Explanation #2**\n\nFor this sample, $n \\leq 100$. Across the five test cases, the value of $m$ does not exceed $0, 1, 1, 2, 2$, respectively.\n\n---\n\n### **Sample Explanation #3**\n\nFor this group of test cases, $k = 0$. In the five test cases, both the first and second test cases satisfy $n = 1$, while the first, third, and fourth test cases satisfy $n, m \\leq 100$.\n\n---\n\n### **Sample Explanation #4**\n\nFor this group of test cases, the first two test cases satisfy $n = 1$, while the first, third, and fourth test cases satisfy $n, m \\leq 100$.\n\n---\n\n### **Constraints**\n\nFor all test data, the following conditions are guaranteed to hold: \n$1 \\le t \\le 15$, $1 \\le n \\le 3 \\times 10^4$, $0 \\le m \\le 3000$, $0 \\le k \\le 10$, $1 \\le f_i \\le i - 1$.\n\n| Test Point Index | $n \\leq$ | $m \\leq$ | $k \\leq$ |\n| :---: | :---: | :---: | :---: |\n| $1,2$ | $4$ | $4$ | $10$ |\n| $3$ | $3 \\times 10^4$ | $0$ | $10$ |\n| $4$ | $10^2$ | $1$ | $10$ |\n| $5$ | $3 \\times 10^4$ | $1$ | $10$ |\n| $6$ | $10^2$ | $2$ | $10$ |\n| $7$ | $3 \\times 10^4$ | $2$ | $10$ |\n| $8,9$ | $1$ | $10^2$ | $0$ |\n| $10$ | $1$ | $3,000$ | $0$ |\n| $11$ | $1$ | $10^2$ | $10$ |\n| $12$ | $1$ | $3,000$ | $10$ |\n| $13,14$ | $10^2$ | $10^2$ | $0$ |\n| $15,16$ | $3 \\times 10^4$ | $3,000$ | $0$ |\n| $17,18$ | $10^2$ | $10^2$ | $10$ |\n| $19,20$ | $3 \\times 10^4$ | $3,000$ | $10$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2952, "prompt": "### Problem Description\nCity C is planning to host a series of racing events. Before the events, it is necessary to construct $m$ tracks in the city.\n\nCity C consists of $n$ intersections, numbered as $1, 2, \\cdots, n$, connected by $n-1$ bidirectional roads that are suitable for track construction. Each road connects two intersections. Specifically, the $i$-th road connects intersections $a_i$ and $b_i$, and the length of the road is $l_i$. With the help of these $n-1$ roads, it is possible to travel between any two intersections.\n\nA track is defined as a sequence of distinct roads $e_1, e_2, \\cdots, e_k$ that allows one to start from a certain intersection and travel along roads $e_1, e_2, \\cdots, e_k$ (visiting each road once, without reversing direction) to reach another intersection. The length of a track is the total sum of the lengths of all roads it traverses. To ensure safety, each road can belong to at most one track.\n\nThe specific track construction plan has not yet been finalized. Your task is to design a plan to construct $m$ tracks such that the length of the shortest track among the $m$ tracks is maximized.\n\n---\n\n### Input Format\nThe name of the input file is `track.in`.\n\nThe first line of the input contains two space-separated positive integers $n$ and $m$, representing the number of intersections and the number of tracks to be constructed, respectively. \n\nThe next $n-1$ lines each contain three positive integers $a_i$, $b_i$, and $l_i$, representing that the $i$-th road connects intersections $a_i$ and $b_i$, and the length of the road is $l_i$. It is guaranteed that any two intersections can be reached from one another through these $n-1$ roads. Each line contains space-separated integers.\n\n---\n\n### Output Format\nThe name of the output file is `track.out`.\n\nThe output contains a single integer, representing the maximum value of the minimum track length among the constructed tracks.\n\n---\n\n### Sample 1\nAll intersections and roads suitable for track construction are shown in the following figure:\n\n![track1.png](https://i.loli.net/2018/11/25/5bfa35d26f803.png)\n\nThe numbers in parentheses indicate the road's index, and the other numbers represent the road's length.\n\nOne track needs to be constructed. A possible solution is constructing a track passing through roads $3, 1, 2, 6$ (from intersection $4$ to intersection $7$). The length of this track is $9 + 10 + 5 + 7 = 31$, which is the maximum value among all possible solutions.\n\n---\n\n### Sample 2\nAll intersections and roads suitable for track construction are shown in the following figure:\n\n![track2.png](https://i.loli.net/2018/11/25/5bfa35d282f80.png)\n\nThree tracks need to be constructed. A possible solution is constructing the following three tracks:\n1. A track passing through roads $1$ and $6$ (from intersection $1$ to intersection $7$) with a length of $6 + 9 = 15$;\n2. A track passing through roads $5, 2, 3, 8$ (from intersection $6$ to intersection $9$) with a length of $4 + 3 + 5 + 4 = 16$;\n3. A track passing through roads $7$ and $4$ (from intersection $8$ to intersection $5$) with a length of $7 + 10 = 17$.\n\nThe shortest track among the above three tracks has a length of $15$, which is the maximum possible value for the smallest track length.\n\n---\n\n### Constraints and Hints\nThe constraints and characteristics of the input data across all test cases are summarized in the following table:\n\n\n\n| Test Case ID | $n$ | $m$ | $a_i=1$ | $b_i=a_i+1$ | Branch Count $\\leq 3$ |\n|:-:|:-:|:-:|:-:|:-:|:-:|\n| $1$ | $\\leq 5$ | $=1$ | No | No | Yes |\n| $2$ | $\\leq 10$ | $\\leq n-1$ | No | Yes | Yes |\n| $3$ | $\\leq 15$ | $\\leq n-1$ | Yes | No | No |\n| $4$ | $\\leq 10^3$ | $=1$ | No | No | Yes |\n| $5$ | $\\leq 3\\times 10^4$ | $=1$ | Yes | No | No |\n| $6$ | $\\leq 3\\times 10^4$ | $=1$ | No | No | No |\n| $7$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | Yes | No | No |\n| $8$ | $\\leq 5\\times 10^4$ | $\\leq n-1$ | Yes | No | No |\n| $9$ | $\\leq 10^3$ | $\\leq n-1$ | No | Yes | Yes |\n| $10$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | No | Yes | Yes |\n| $11$ | $\\leq 5\\times 10^4$ | $\\leq n-1$ | No | Yes | Yes |\n| $12$ | $\\leq 50$ | $\\leq n-1$ | No | No | Yes |\n| $13$ | $\\leq 50$ | $\\leq n-1$ | No | No | Yes |\n| $14$ | $\\leq 200$ | $\\leq n-1$ | No | No | Yes |\n| $15$ | $\\leq 200$ | $\\leq n-1$ | No | No | Yes |\n| $16$ | $\\leq 10^3$ | $\\leq n-1$ | No | No | Yes |\n| $17$ | $\\leq 10^3$ | $\\leq n-1$ | No | No | No |\n| $18$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | No | No | No |\n| $19$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | No | No | No |\n| $20$ | $\\leq 5\\times 10^4$ | $\\leq n-1$ | No | No | No |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3156, "prompt": "### Problem Description\n\nIn the Cat Kingdom's railway system, there are $n$ stations, numbered from $1$ to $n$. Little Cat plans to depart from Station $1$ and take a train back to Cat Home at Station $n$. She has queried the train schedule, which includes $m$ trains numbered from $1$ to $m$. Little Cat will arrive at Station $1$ at time $0$. For Train $i$, it departs from Station $x_i$ at time $p_i$ and directly arrives at Station $y_i$ at time $q_i$. Little Cat can only board Train $i$ precisely at time $p_i$ and disembark at time $q_i$. She can reach Station $n$ by making multiple transfers between trains. \n\nA transfer between trains is defined as follows: For two trains $u$ and $v$, if $y_u = x_v$ and $q_u \\leq p_v$, then Little Cat can disembark from Train $u$ at Station $y_u$, wait for $p_v - q_u$ units of time at Station $y_u$, and then board Train $v$ at time $p_v$.\n\nLittle Cat wishes to minimize the hassle during her journey, which is measured using \"irritation value\".\n\n- Waiting at a station increases irritation value. For a waiting period of $t$ ($t \\geq 0$) units of time, the irritation value increases by $At^2 + Bt + C$, where $A, B, C$ are given constants. Note that waiting at Station $1$ from time $0$ until boarding the first train also counts as a waiting period.\n\n- If Little Cat finally reaches Station $n$ at time $z$, her irritation value further increases by $z$.\n\nFormally, if she takes a total of $k$ trains in sequential order specified by the sequence $s_1, s_2, \\cdots, s_k$, then this sequence is called a feasible route back home if and only if it satisfies the following two conditions:\n\n1. $x_{s1} = 1$, $y_{sk} = n$\n2. For all $j$ ($1 \\leq j < k$), $y_{sj} = x_{s_{j+1}}$ and $q_{sj} \\leq p_{s_{j+1}}$\n\nThe irritation value for such a route can be calculated as:\n\n$$q_{s_k}+(A \\times p_{s_1}^2 + B \\times p_{s_1} + C)+\\sum_{j=1}^{k-1}(A(p_{s_{j+1}} - q_{s_j})^2 + B(p_{s_{j+1}} - q_{s_j}) + C)$$\n\nLittle Cat wants to minimize her irritation value among all feasible routes back home. You are guaranteed that at least one feasible route exists.\n\n### Input Format\n\nThe first line contains five integers $n, m, A, B, C$, whose meanings are described in the problem statement.\n\nThe next $m$ lines each contain four integers $x_i, y_i, p_i, q_i$, indicating the starting station, destination station, departure time, and arrival time of the $i$-th train, respectively.\n\n### Output Format\n\nOutput a single integer, representing the minimum irritation value among all feasible routes.\n\n### Additional Samples\n\nYou can find extra samples through the accompanying files.\n\n#### Sample 3\n\nSee the attached file `route/route3.in` and its output `route/route3.ans`.\n\nThis sample has the same data types as final test cases $5 \\sim 8$.\n\n#### Sample 4\n\nSee the attached file `route/route4.in` and its output `route/route4.ans`.\n\nThis sample has the same data types as final test cases $11 \\sim 14$.\n\n#### Sample 5\n\nSee the attached file `route/route5.in` and its output `route/route5.ans`.\n\nThis sample has the same data types as final test cases $18 \\sim 20$.\n\n### Sample 1 Explanation\n\nThere are three feasible routes back home:\n\n- Take trains 1 and 4 in sequence, resulting in an irritation value of: $10 + (1 \\times 3^2 + 5 \\times 3 + 10) + (1 \\times (9 - 4)^2 + 5 \\times (9 - 4) + 10) = 104$\n- Take trains 2 and 4 in sequence, resulting in an irritation value of: $10 + (1 \\times 5^2 + 5 \\times 5 + 10) + (1 \\times (9 - 7)^2 + 5 \\times (9 - 7) + 10) = 94$\n- Take trains 3 and 4 in sequence, resulting in an irritation value of: $10 + (1 \\times 6^2 + 5 \\times 6 + 10) + (1 \\times (9 - 8)^2 + 5 \\times (9 - 8) + 10) = 102$\n\nThe second route produces the smallest irritation value, which is $94$.\n\n### Constraints\n\nFor all test cases: $2 \\leq n \\leq 10^5, 1 \\leq m \\leq 2 \\times 10^5, 0 \\leq A \\leq 10, 0 \\leq B, C \\leq 10^6, 1 \\leq x_i, y_i \\leq n, x_i \\neq y_i, 0 \\leq p_i < q_i \\leq 10^3$.\n\nSpecific constraints for each test case are as follows:\n\n| Test Case ID | $n$ | $m$ | Special Conditions for $A, B, C$ | Other Conditions |\n| :----------: | :-------------------: | :-------------------: | :-----------------------------: | :-------------------: |\n| $1 \\sim 2$ | $\\leq 100$ | $= n - 1$ | None | $y_i = x_i + 1$ |\n| $3 \\sim 4$ | $\\leq 100$ | $\\leq 100$ | $A = B = C = 0$ | $y_i = x_i + 1$ |\n| $5 \\sim 8$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | $A = B = C = 0$ | $x_i < y_i$ |\n| $9$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | $A = B = 0$ | $x_i < y_i$ |\n| $10$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | $A = 0$ | $x_i < y_i$ |\n| $11 \\sim 14$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | None | None |\n| $15$ | $\\leq 10^5$ | $\\leq 2 \\times 10^5$ | $A = B = 0$ | None |\n| $16 \\sim 17$ | $\\leq 10^5$ | $\\leq 2 \\times 10^5$ | $A = 0$ | None |\n| $18 \\sim 20$ | $\\leq 10^5$ | $\\leq 2 \\times 10^5$ | None | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 4003, "prompt": "### Problem Description\nWe say that a sequence $B = \\{b_1,b_2,\\cdots,b_n\\}$ is an **expansion** of another sequence $A = \\{a_1,a_2,\\cdots,a_m\\}$ if and only if a sequence of **positive integers** $L = \\{l_1,l_2,\\cdots,l_m\\}$ exists, such that replacing $a_i$ with $l_i$ copies of $a_i$ results in sequence $B$. For example:\n\n- $\\{1,3,3,3,2,2,2\\}$ is an expansion of $\\{1,3,3,2\\}$, with $L = \\{1,1,2,3\\}$ or $L = \\{1,2,1,3\\}$;\n- However, $\\{1,3,3,2\\}$ is not an expansion of $\\{1,3,3,3,2\\}$, and $\\{1,2,3\\}$ is not an expansion of $\\{1,3,2\\}$.\n\nLittle R gives you two sequences $X$ and $Y$, and he hopes that you can find an expansion $F = \\{f_i\\}$ of $X$ with length $l_0 = 10^{100}$ and an expansion $G = \\{g_i\\}$ of $Y$ with length $l_0$, such that for any $1 \\le i, j \\le l_0$, the following condition is satisfied: $(f_i - g_i)(f_j - g_j) > 0$. Given how long these sequences are, you only need to tell Little R whether such sequences exist.\n\nTo prevent coin-flipping or random guessing, Little R has provided $q$ additional queries. In each query, Little R modifies a certain number of elements in $X$ and $Y$. You need to make the determination described above for each modified $X$ and $Y$.\n\n**The queries are independent, and all modifications in each query are applied to the original sequence.**\n\n### Input Format\nThe first line contains four integers $c, n, m, q$, which represent the sample ID, the length of sequence $X$, the length of sequence $Y$, and the number of additional queries. Here, $c$ indicates that the sample has the same constraints as test case $c$.\n\nThe second line contains $n$ integers $x_1,x_2,\\cdots,x_n$, describing sequence $X$.\n\nThe third line contains $m$ integers $y_1,y_2,\\cdots,y_m$, describing sequence $Y$.\n\nThe next $q$ groups describe the additional queries. For each query:\n\n- The first line contains two integers $k_x$ and $k_y$, representing the number of modifications made to sequences $X$ and $Y$, respectively.\n- The next $k_x$ lines each contain two integers $p_x$ and $v_x$, indicating that $x_{p_x}$ is modified to $v_x$.\n- The next $k_y$ lines each contain two integers $p_y$ and $v_y$, indicating that $y_{p_y}$ is modified to $v_y$.\n\n### Output Format\nOutput a single line containing a binary sequence of length $(q+1)$. The first element of the sequence corresponds to the answer for the initial inquiry, and the subsequent $q$ elements correspond to the answers for each additional query in order. For each inquiry, output `1` if the required sequences $F$ and $G$ exist, and `0` otherwise.\n\n**Example Explanation #1** \n\nBecause $F$ and $G$ are very long, their repeated elements are represented using ellipses. For example, $\\{1,2,3,3,\\cdots\\}$ means that the sequence repeats the last element starting from the third position to reach length $l_0$. \n\nThe following describes the four inquiries, including the initial one and three additional ones:\n\n1. $A = \\{8,6,9\\}$, $B = \\{1,7,4\\}$, taking $F = \\{8,8,6,9,\\cdots\\}, G = \\{1,7,4,4,\\cdots\\}$;\n2. $A = \\{8,6,0\\}$, $B = \\{1,7,4\\}$, it can be proven that no valid solution exists;\n3. $A = \\{8,6,9\\}$, $B = \\{8,7,5\\}$, it can be proven that no valid solution exists;\n4. $A = \\{8,8,9\\}$, $B = \\{7,7,4\\}$, taking $F = \\{8,8,9,\\cdots\\}, G = \\{7,7,4,\\cdots\\}$.\n\n**Example Explanation #2**\n\nThis example satisfies the constraints of test case $4$.\n\n**Example Explanation #3**\n\nThis example satisfies the constraints of test case $7$.\n\n**Example Explanation #4**\n\nThis example satisfies the constraints of test case $9$.\n\n**Example Explanation #5**\n\nThis example satisfies the constraints of test case $18$.\n\n### Constraints\nFor all test data, the following are guaranteed:\n\n- $1 \\le n, m \\le 5 \\times 10 ^ 5$;\n- $0 \\le q \\le 60$;\n- $0 \\le x_i, y_i < 10 ^ 9$;\n- $0 \\le k_x, k_y \\le 5 \\times 10 ^ 5$, and the sum of $(k_x + k_y)$ across all queries does not exceed $5 \\times 10 ^ 5$;\n- $1 \\le p_x \\le n$, $1 \\le p_y \\le m$, $0 \\le v_x, v_y < 10 ^ 9$;\n- In each query, $p_x$ values are pairwise distinct, and $p_y$ values are pairwise distinct.\n\n|Sample ID|$n, m \\le$|Special Properties|\n|:-:|:-:|:-:|\n|$1$|$1$|No|\n|$2$|$2$|No|\n|$3, 4$|$6$|No|\n|$5$|$200$|No|\n|$6, 7$|$2000$|No|\n|$8, 9$|$4 \\times 10 ^ 4$|Yes|\n|$10, 11$|$1.5 \\times 10 ^ 5$|Yes|\n|$12 \\sim 14$|$5 \\times 10 ^ 5$|Yes|\n|$15, 16$|$4 \\times 10 ^ 4$|No|\n|$17, 18$|$1.5 \\times 10 ^ 5$|No|\n|$19, 20$|$5 \\times 10 ^ 5$|No|\n\nSpecial Property: For each inquiry (including the initial inquiry and additional queries), it is guaranteed that $x_1 < y_1$, and $x_n$ is the only smallest value in sequence $X$, while $y_m$ is the only largest value in sequence $Y$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 4004, "prompt": "### Problem Description\nStudent T is very enthusiastic about running. To make running more enjoyable, he decides to create a software called **\"Daily Check-in Challenge\"**, allowing users to log their running activities every day.\n\nAfter completing development, Student T plans to conduct trial runs and invites Student Y to help. There are a total of $n$ trial days, numbered from $1$ to $n$.\n\nFor Student Y, if he chooses to log his running activity on a certain day, his energy level will decrease by $d$. Initially, his energy level is $0$, and during the trial period, his **energy level can be negative**.\n\nMoreover, Student Y will not **continuously log running activities** for **more than** $k$ consecutive days. In other words, there cannot exist $1\\leq x\\leq n-k$ such that he logs his running activity from day $x$ to day $x+k$ inclusively.\n\nStudent T has designed $m$ challenges in the software. The $i$-th ($1\\leq i \\leq m$) challenge is described by three positive integers $(x_i, y_i, v_i)$, which indicate that if the user has continuously logged running activities for at least $y_i$ days up to day $x_i$ (i.e., from day $x_i-y_i+1$ to day $x_i$, all days logged), then Student T will treat the user to a meal, thereby increasing the user's energy level by $v_i$.\n\nNow, Student Y wants to know the **maximum** energy level he can achieve after $n$ trial days in the software.\n\n### Input Format\n**This problem contains multiple test cases.**\n\nThe first line of the input contains two integers $c$ and $t$, which represent the test case identifier and the number of test cases, respectively. For the examples, $c$ indicates that this example shares the same constraints as test case $c$.\n\nFollowing this, for each test case:\n\n- The first line contains four positive integers $n, m, k, d$, which represent the number of trial days, the number of challenges, the maximum consecutive days Student Y can log running activities, and the energy decrease due to logging running activity, respectively.\n- The next $m$ lines each contain three positive integers $x_i, y_i, v_i$, which describe a challenge.\n\n### Output Format\nOutput one integer, representing the answer for each test case.\n\n**\u3010Sample Explanation #1\u3011**\n\nRunning activity is logged on days $1, 2$, and not logged on day $3$. Ultimately, an energy level of $(-1)+(-1)+4=2$ is achieved.\n\n**\u3010Sample Explanation #2\u3011**\n\nThis test case satisfies the constraints of test case $3$.\n\n**\u3010Sample Explanation #3\u3011**\n\nThis test case satisfies the constraints of test case $5$.\n\n**\u3010Sample Explanation #4\u3011**\n\nThis test case satisfies the constraints of test case $15$.\n\n**\u3010Sample Explanation #5\u3011**\n\nThis test case satisfies the constraints of test case $17$.\n\n**\u3010Sample Explanation #6\u3011**\n\nThis test case satisfies the constraints of test case $19$.\n\n### Constraints\n\nLet $l_i = x_i - y_i + 1$, $r_i = x_i$;\n\nFor all test cases, it is guaranteed that: \n$1\\leq t\\leq 10$, $1\\leq k\\leq n\\leq 10^9$, $1\\leq m\\leq 10^5$, $1\\leq l_i\\leq r_i\\leq n$, $1\\leq d, v_i\\leq 10^9$.\n\n|Test Case ID|$n \\leq$|$m \\leq$|Special Properties|\n|:-:|:-:|:-:|:-:|\n|$1, 2$|$18$|$10 ^ 2$|None|\n|$3, 4$|$10 ^ 2$|$10 ^ 2$|None|\n|$5 \\sim 7$|$10 ^ 3$|$10 ^ 3$|None|\n|$8, 9$|$10 ^ 3$|$10 ^ 5$|None|\n|$10, 11$|$10 ^ 5$|$10 ^ 3$|None|\n|$12 \\sim 14$|$10 ^ 5$|$10 ^ 5$|None|\n|$15, 16$|$10 ^ 9$|$10 ^ 5$|A|\n|$17, 18$|$10 ^ 9$|$10 ^ 5$|B|\n|$19 \\sim 21$|$10 ^ 9$|$10 ^ 5$|C|\n|$22 \\sim 25$|$10 ^ 9$|$10 ^ 5$|None|\n\nSpecial Property A: $k \\leq 10^2$; \n\nSpecial Property B: $\\forall 1\\leq i\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 3389, "prompt": "### Problem Description\n\nC loves running and enjoys competing on the WeChat step leaderboard. To this end, he has devised a plan for racking up steps on WeChat.\n\nHe arrives at an open area where the position of a person in the field can be represented by $k$-dimensional integer coordinates $(a_1, a_2, \\ldots, a_k)$. The field has size constraints\u2014specifically, in the $i$-th dimension, its size is $w_i$. Thus, for a person to be within the field, their coordinates must satisfy $1 \\leq a_i \\leq w_i$ ($1 \\leq i \\leq k$). \n\nC plans to pick a new starting position from the field every day for the next $P = w_1 \\times w_2 \\times \\cdots \\times w_k$ days and execute his walking routine from each of these positions (in other words, he will start his routine once from every position in the field). \n\nThe plan is very simple. Each day, he follows a pre-defined walking route consisting of $n$ steps. Each step is defined using $c_i$ and $d_i$. If he is currently at position $(a_1, a_2, \\ldots, a_{c_i}, \\ldots, a_k)$, this step will move him to $(a_1, a_2, \\ldots, a_{c_i} + d_i, \\ldots, a_k)$. Here, $1 \\leq c_i \\leq k$, and $d_i \\in \\{-1, 1\\}$. C will repeat this route continuously until stepping out of the field bounds, upon which he stops his routine for the day (i.e., if C is still within bounds after completing the $n$ steps, he will restart the route from the first step again). \n\nC is very confident about his speed and does not care about the time spent. He only wants to know how many total steps he will accumulate on WeChat after $P$ days. Please help him calculate this. \n\n### Input Format\nThe first line contains two space-separated integers $n$ and $k$, representing the number of steps in the route and the number of dimensions of the field, respectively. \nThe second line contains $k$ space-separated integers $w_i$, indicating the size of the field in each dimension. \nThe next $n$ lines each contain two space-separated integers $c_i$ and $d_i$, representing the direction of each step, as described in the problem description. \n\n### Output Format\nOutput a single integer representing the answer. Since the answer may be very large, output it modulo ${10}^9 + 7$. \nIf C's plan causes him to get stuck in the field forever on any day (i.e., he cannot step out of the field), print a single integer $-1$. \n\n### Sample Input\n\n```\n2 2\n3 3\n2 1\n1 -1\n```\n\n### Sample Output\n\n```\n21\n```\n\n### **Sample #1 Explanation**\n\nStarting from $(1, 1)$, C will take $2$ steps. Starting from $(1, 2)$, C will take $4$ steps. Starting from $(1, 3)$, C will take $4$ steps. \nStarting from $(2, 1)$, C will take $2$ steps. Starting from $(2, 2)$, C will take $3$ steps. Starting from $(2, 3)$, C will take $3$ steps. \nStarting from $(3, 1)$, C will take $1$ step. Starting from $(3, 2)$, C will take $1$ step. Starting from $(3, 3)$, C will take $1$ step. \nA total of $21$ steps. \n\n### **Constraints**\n\n| Test Case Range | $n \\leq$ | $k \\leq$ | $w_i \\leq$ |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 3$ | $5$ | $5$ | $3$ |\n| $4 \\sim 6$ | $100$ | $3$ | $10$ |\n| $7 \\sim 8$ | ${10}^5$ | $1$ | ${10}^5$ |\n| $9 \\sim 12$ | ${10}^5$ | $2$ | ${10}^6$ |\n| $13 \\sim 16$ | $5 \\times {10}^5$ | $10$ | ${10}^6$ |\n| $17 \\sim 20$ | $5 \\times {10}^5$ | $3$ | ${10}^9$ |\n\nFor all test cases, it is guaranteed that $1 \\leq n \\leq 5 \\times {10}^5$, $1 \\leq k \\leq 10$, $1 \\leq w_i \\leq {10}^9$, and $d_i \\in \\{-1, 1\\}$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 4001, "prompt": "### Problem Description\n\nLittle S has a dictionary containing $n$ distinct words, each of length $m$: $w_1, w_2, \\cdots, w_n$. Each word is a string composed of lowercase English letters.\n\nLittle S can perform the following operation any number of times (including zero times): Select any word from the dictionary and swap any two characters in it.\n\nFor each $1 \\le i \\le n$, Little S wants to determine if it is possible to perform the above operations to obtain a new set of $n$ words $w'_1, w'_2, \\cdots , w'_n$ such that for every $j \\neq i$, the lexicographical order of $w'_i$ is smaller than all $w'_j$. **For the case where $n=1$, we assume that this property is naturally satisfied.**\n\nFor two strings of the same length $s = s_1s_2\\cdots s_L$ and $t = t_1t_2 \\cdots t_L$, we say that $s$ has a smaller lexicographical order than $t$ if and only if the following condition is met: There exists a position $i$ such that $s$ and $t$ are identical up to position $i-1$, and $s_i < t_i$, where the lowercase letter $s_i$ comes before $t_i$ in the alphabetical order.\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $m$, representing the number of words and the length of each word, respectively.\n\nThe next $n$ lines each contain a lowercase string of length $m$, denoted as $w_i$, representing a word in the dictionary.\n\n### Output Format\n\nOutput one line containing a binary string of length $n$, denoted as $a$. For each $1 \\le i \\le n$, if the property mentioned in the problem description holds, set $a_i = 1$; otherwise, set $a_i = 0$.\n\n### Example Explanation #1\n\n- Without performing any operations, the first word is already lexicographically smallest, so the first character of the output is `1`.\n- By swapping the first two characters of `bananaa` and the third and sixth characters of `abandon`, you can obtain the following: `abondan`, `abnanaa`, `baannaa`, `notnotn`. In this case, the second word becomes lexicographically smallest, so the second character of the output is `1`.\n- By swapping the first and last characters of `baannaa`, you can obtain `aaannab`, while the other words remain unchanged. In this case, the third word becomes lexicographically smallest, so the third character of the output is `1`.\n- However, no matter what operations you perform, the fourth word will not become smaller than the second word, so the fourth character of the output is `0`.\n\n### Example Explanation #2\n\nThis example satisfies the constraints of Test Case $4$.\n\n### Example Explanation #3\n\nThis example satisfies the constraints of Test Case $7$.\n\n### Example Explanation #4\n\nThis example satisfies the constraints of Test Case $10$.\n\n### Constraints\n\nFor all test cases, it is guaranteed that $1 \\le n \\le 3000$, $1 \\le m \\le 3000$, and each $w_i$ is a unique lowercase string of length $m$.\n\n| Test Case ID | $n\\leq$ | $m\\leq$ |\n| :----------: | :----------: | :----------: |\n| $1$ | $1$ | $1$ |\n| $2\\sim 4$ | $26$ | $1$ |\n| $5\\sim 7$ | $15$ | $2$ |\n| $8$ | $300$ | $300$ |\n| $9$ | $10^3$ | $10^3$ |\n| $10$ | $3000$ | $3000$ | \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "easy"} +{"id": 3899, "prompt": "### Problem Description\nXiao N and Xiao O will participate in the grand programming competition NOIP in November 2022! Xiao P will host the competition as the judge. Both Xiao N and Xiao O lead a team of $n$ members, where the players in each team are numbered from $1$ to $n$. Each player has a specific programming skill level. Specifically, in Xiao N's team, the programming skill level of the player numbered $i$ ($1 \\leq i \\leq n$) is $a _ i$; in Xiao O's team, the programming skill level of the player numbered $i$ ($1 \\leq i \\leq n$) is $b _ i$. Moreover, $\\{a _ i\\}$ and $\\{b _ i\\}$ are permutations of the integers from $1$ to $n$.\n\nBefore each match, considering factors such as travel distance and consecutive participation in matches, Xiao P will select two parameters $l$ and $r$ ($1 \\leq l \\leq r \\leq n$), indicating that players from both teams whose numbers are within the range $[l, r]$ will be invited to the venue to prepare for the match. At the venue, Xiao N and Xiao O use dice rolls to choose the parameters $p$ and $q$ ($l \\leq p \\leq q \\leq r$), and only players within the range $[p, q]$ will participate in the match. To provide the audience with the most exciting competition, both teams will send the players in $[p, q]$ who have the highest programming skill levels to compete. Assuming the skill level of Xiao N's player is $m _ a$, and the skill level of Xiao O's player is $m _ b$, the excitement of the match is calculated as $m _ a \\times m _ b$.\n\nThere are $Q$ matches in total in NOIP. For each match, the parameters $l$ and $r$ are already determined, but $p$ and $q$ have not been selected yet. Xiao P wants to know, for each match, the sum of the excitement values for all possible $p$ and $q$ ($l \\leq p \\leq q \\leq r$). Since the result could be extremely large, you only need to output the result modulo $2 ^ {64}$ for each match.\n\n### Input Format\nThe first line contains two positive integers $T$ and $n$, representing the test point number and the number of participants. If the data is a sample, it is guaranteed that $T = 0$.\n\nThe second line contains $n$ positive integers, where the $i$-th integer is $a _ i$, representing the programming skill level of the player numbered $i$ in Xiao N's team.\n\nThe third line contains $n$ positive integers, where the $i$-th integer is $b _ i$, representing the programming skill level of the player numbered $i$ in Xiao O's team.\n\nThe fourth line contains a positive integer $Q$, representing the number of matches.\n\nThe next $Q$ lines, the $i$-th line contains two positive integers $l _ i$ and $r _ i$, indicating the parameters $l$ and $r$ of the $i$-th match.\n\n### Output Format\nOutput $Q$ lines. The $i$-th line contains a non-negative integer, representing the result of the sum of all possible match excitement values modulo $2 ^ {64}$ for the $i$-th match.\n\n**\u3010Example 1 Explanation\u3011**\n\nWhen $p = 1, q = 2$, Xiao N will send player $1$, Xiao O will send player $2$, and the excitement of the match is $2 \\times 2 = 4$.\n\nWhen $p = 1, q = 1$, Xiao N will send player $1$, Xiao O will send player $1$, and the excitement of the match is $2 \\times 1 = 2$.\n\nWhen $p = 2, q = 2$, Xiao N will send player $2$, Xiao O will send player $2$, and the excitement of the match is $1 \\times 2 = 2$.\n\n**\u3010Example 2\u3011**\n\nThis example satisfies the constraints of test points $1 \\sim 2$.\n\n**\u3010Example 3\u3011**\n\nThis example satisfies the constraints of test points $3 \\sim 5$.\n\n### Data Constraints\n\nFor all data, guaranteed:\n- $1 \\leq n, Q \\leq 2.5 \\times 10 ^ 5$\n- $1 \\leq l _ i \\leq r _ i \\leq n$\n- $1 \\leq a _ i, b _ i \\leq n$, and $\\{a _ i\\}$ and $\\{b _ i\\}$ are permutations of the integers from $1$ to $n$.\n\n| Test Point | $n$ | $Q$ | Special Property A | Special Property B |\n| :----------: | :----------: | :----------: | :----------: | :----------: |\n| $1, 2$ | $\\leq 30$ | $\\leq 30$ | Yes | Yes |\n| $3, 4, 5$ | $\\leq 3,000$ | $\\leq 3,000$ | Yes | Yes |\n| $6, 7$ | $\\leq 10 ^ 5$ | $\\leq 5$ | Yes | Yes |\n| $8, 9$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 5$ | Yes | Yes |\n| $10, 11$ | $\\leq 10 ^ 5$ | $\\leq 5$ | No | No |\n| $12, 13$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 5$ | No | No |\n| $14, 15$ | $\\leq 10 ^ 5$ | $\\leq 10 ^ 5$ | Yes | Yes |\n| $16, 17$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 2.5 \\times 10 ^ 5$ | Yes | Yes |\n| $18, 19$ | $\\leq 10 ^ 5$ | $\\leq 10 ^ 5$ | Yes | No |\n| $20, 21$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 2.5 \\times 10 ^ 5$ | Yes | No |\n| $22, 23$ | $\\leq 10 ^ 5$ | $\\leq 10 ^ 5$ | No | No |\n| $24, 25$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 2.5 \\times 10 ^ 5$ | No | No |\n\nSpecial Property A: Guarantees $a$ is a uniformly random permutation of integers from $1 \\sim n$.\n\nSpecial Property B: Guarantees $b$ is a uniformly random permutation of integers from $1 \\sim n$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3981, "prompt": "### Problem Description\n\nDepth-First Search (DFS) is a common traversal algorithm. Using this algorithm, starting from a connected undirected graph without multi-edges and self-loops $G = (V, E)$, and a specified starting point $s$, we can obtain a DFS tree $T$.\n\nThe algorithm proceeds as follows:\n\n1. Initialize an empty stack $S$, and set $T = (V, \\emptyset)$, meaning that the edge set of $T$ is initially empty.\n2. Push the starting point $s$ into the stack $S$.\n3. Visit the top node $u$ of the stack, marking $u$ as \"visited.\"\n4. If there exists an unvisited node adjacent to $u$, randomly pick one of these nodes and denote it as $v$. Add the edge $(u, v)$ to the edge set of $T$, push $v$ into $S$, and **return to step 3**. If no such node exists, pop the node $u$ from the stack.\n\nIt can be proven that when the graph $G$ is connected, this algorithm will result in a spanning tree $T$ for the graph. However, **the tree $T$ obtained by this algorithm may not be unique, as it depends on the search sequence, particularly the choice of nodes in step 4**. For a specified starting point $s$, if a specific search sequence can be chosen such that the algorithm produces exactly the tree $T$, we call **$T$ an $s$-dfs tree of $G$**.\n\nNow, given a tree $T$ with $n$ vertices numbered $1 \\sim n$, and an additional $m$ edges, we guarantee that the $m$ edges are distinct, connect different vertices, and do not overlap with the $n - 1$ edges in the tree $T$. These $m$ edges are referred to as **non-tree edges**. Among these $n$ vertices, $k$ vertices are designated as **key vertices**.\n\nYou want to know how many ways there are to select the $m$ non-tree edges (possibly choosing none), such that: after constructing the graph $G$ by combining the edges of the tree $T$ and the selected non-tree edges, there exists a **key vertex** $s$ such that $T$ is an $s$-dfs tree of $G$.\n\nSince the answer can be very large, report the number of ways modulo $(10 ^ 9 + 7)$. \n\n### Input Format\n\nThe first line of input contains an integer $c$, indicating the test point number. $c = 0$ signifies that this test point is a sample test case.\n\nThe second line contains three positive integers $n, m, k$, representing the number of vertices, the number of non-tree edges, and the number of key vertices, respectively.\n\nThe next $n - 1$ lines each contain two positive integers $u, v$, representing an edge from the tree $T$. These $n - 1$ edges form a connected tree structure.\n\nThe next $m$ lines each contain two positive integers $a, b$, representing a non-tree edge. It is guaranteed that $(a, b)$ does not overlap with the edges in the tree and that there are no duplicate edges.\n\nThe last line contains $k$ positive integers $s_1, s_2, \\dots, s_k$, representing the indices of the $k$ key vertices. It is guaranteed that $s_1, s_2, \\dots, s_k$ are distinct.\n\n### Output Format\n\nOutput a single line containing a non-negative integer representing the number of valid ways to select the non-tree edges, modulo $(10 ^ 9 + 7)$. \n\n### **Sample Explanation #1**\n\nIn this sample, there are three ways to select the non-tree edges: choosing only the edge $(1, 3)$, choosing only the edge $(2, 4)$, or choosing none of the non-tree edges.\n\n1. If only the edge $(1, 3)$ is selected, or if no non-tree edges are chosen, it can be observed that $T$ is an $s$-dfs tree of $G$, where the key vertex $s = 3$. The specific DFS sequence is as follows:\n 1. Push $3$ into the stack $S$. Now $S = [3]$.\n 2. Mark $3$ as \"visited.\"\n 3. Since $3$ is connected to $2$, and $2$ is \"unvisited,\" add $(3, 2)$ to $T$, push $2$ into the stack $S$. Now $S = [3, 2]$.\n 4. Mark $2$ as \"visited.\"\n 5. Since $2$ is connected to $1$, and $1$ is \"unvisited,\" add $(2, 1)$ to $T$, push $1$ into the stack $S$. Now $S = [3, 2, 1]$.\n 6. As all vertices connected to $1$ are \"visited,\" pop $1$ from the stack. Now $S = [3, 2]$.\n 7. As all vertices connected to $2$ are \"visited,\" pop $2$ from the stack. Now $S = [3]$.\n 8. Since $3$ is connected to $4$, and $4$ is \"unvisited,\" add $(3, 4)$ to $T$, push $4$ into the stack $S$. Now $S = [3, 4]$.\n 9. As all vertices connected to $4$ are \"visited,\" pop $4$ from the stack. Now $S = [3]$.\n 10. As all vertices connected to $3$ are \"visited,\" pop $3$ from the stack. The stack becomes empty.\n\n2. If only the edge $(2, 4)$ is selected, it can be shown that $T$ is an $s$-dfs tree of $G$, where the key vertex $s = 2$. The specific DFS sequence is as follows:\n 1. Push $2$ into the stack $S$. Now $S = [2]$.\n 2. Mark $2$ as \"visited.\"\n 3. Since $2$ is connected to $3$, and $3$ is \"unvisited,\" add $(2, 3)$ to $T$, push $3$ into the stack $S$. Now $S = [2, 3]$.\n 4. Mark $3$ as \"visited.\"\n 5. Since $3$ is connected to $4$, and $4$ is \"unvisited,\" add $(3, 4)$ to $T$, push $4$ into the stack $S$. Now $S = [2, 3, 4]$.\n 6. As all vertices connected to $4$ are \"visited,\" pop $4$ from the stack. Now $S = [2, 3]$.\n 7. As all vertices connected to $3$ are \"visited,\" pop $3$ from the stack. Now $S = [2]$.\n 8. Since $2$ is connected to $1$, and $1$ is \"unvisited,\" add $(2, 1)$ to $T$, push $1$ into the stack $S$. Now $S = [2, 1]$.\n 9. As all vertices connected to $1$ are \"visited,\" pop $1$ from the stack. Now $S = [2]$.\n 10. As all vertices connected to $2$ are \"visited,\" pop $2$ from the stack. The stack becomes empty.\n\n### **Sample Explanation #2**\n\nThis sample satisfies constraints from test points $4 \\sim 6$.\n\n### **Sample Explanation #3**\n\nThis sample satisfies constraints from test points $10 \\sim 11$.\n\n### **Sample Explanation #4**\n\nThis sample satisfies constraints from test points $12 \\sim 13$.\n\n### **Sample Explanation #5**\n\nThis sample satisfies constraints from test points $14 \\sim 16$.\n\n### **Sample Explanation #6**\n\nThis sample satisfies constraints from test points $23 \\sim 24$.\n\n---\n\n### **Constraints**\n\nFor all test cases, it is guaranteed that $1 \\le k \\le n \\le 5 \\times 10 ^ 5$, $1 \\le m \\le 5 \\times 10 ^ 5$.\n\n| Test Point | $n \\le$ | $m \\le$ | $k \\le$ | Special Properties |\n|:-:|:-:|:-:|:-:|:-:|\n| $1 \\sim 3$ | $6$ | $6$ | $n$ | None |\n| $4 \\sim 6$ | $15$ | $15$ | $6$ | None |\n| $7 \\sim 9$ | $300$ | $300$ | $6$ | None |\n| $10 \\sim 11$ | $300$ | $300$ | $n$ | A |\n| $12 \\sim 13$ | $300$ | $300$ | $n$ | B |\n| $14 \\sim 16$ | $300$ | $300$ | $n$ | None |\n| $17 \\sim 18$ | $2 \\times 10 ^ 5$ | $2 \\times 10 ^ 5$ | $n$ | A |\n| $19 \\sim 21$ | $2 \\times 10 ^ 5$ | $2 \\times 10 ^ 5$ | $n$ | B |\n| $22$ | $2 \\times 10 ^ 5$ | $2 \\times 10 ^ 5$ | $n$ | None |\n| $23 \\sim 25$ | $5 \\times 10 ^ 5$ | $5 \\times 10 ^ 5$ | $n$ | None |\n\nSpecial Property A: In the tree $T$, vertex $i$ is connected to vertex $i + 1$ ($1 \\le i < n$).\n\nSpecial Property B: If all $m$ non-tree edges are added to graph $G$ along with the edges of $T$, $T$ is guaranteed to be a $1$-dfs tree of $G$.\n\n**Note:** Vertex $1$ is not necessarily one of the $k$ key vertices.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3983, "prompt": "### Problem Description\nXiao Y is a college student who has recently been researching problems related to strings.\n\nXiao Y has learned the following definitions about strings:\n\n- Given a string $s[1: n]$ of length $n$, we define its substring $s[l: r]$ ($1 \\leq l \\leq r \\leq n$) as the string obtained by concatenating $s[l], s[l+1], \\dots, s[r]$ in order.\n- Given a string $s[1: n]$ of length $n$, we define its reversed version $R(s)$ as the string obtained by concatenating $s[n], s[n-1], \\dots, s[1]$ in reverse order.\n- Given two strings $a[1: n]$ and $b[1: n]$ both of length $n$, we define $a$ as lexicographically smaller than $b$ if and only if there exists $1 \\leq i \\leq n$, such that for all $1 \\leq j < i$, $a[j] = b[j]$, and $a[i] < b[i]$.\n\nAfter understanding the above definitions, Xiao Y thought of this problem:\n\nGiven a string $s[1: n]$ of length $n$, there are $q$ queries, and for each query you are given two parameters $i$ and $r$. You need to find how many values of $l$ satisfy the following conditions:\n- $1 \\leq l \\leq r$.\n- $s[i: i+l-1]$ is lexicographically smaller than $R(s[i+l: i+2l-1])$.\n\nXiao Y asks for your help in solving this problem.\n\n### Input Format\n**This problem contains multiple test cases.**\n\nThe first line of the input contains two integers $c$ and $t$, which represent the test case identifier and the number of test cases respectively. $c=0$ indicates that this is a sample test case.\n\nFor each test case:\n\nThe first line contains two positive integers $n$ and $q$, representing the length of the string and the number of queries.\n\nThe second line contains a string $s$ of length $n$ consisting of lowercase English letters only.\n\nThe next $q$ lines contain two positive integers $i$ and $r$, representing a query. It is guaranteed that $i + 2r - 1 \\leq n$.\n\n### Output Format\nFor each query in each test case, output a single integer in one line representing the number of values of $l$ that satisfy the conditions.\n\n### **Sample Explanation #1**\n\nFor the first query of the first test case:\n- When $l = 1$, $s[i: i + l - 1] = \\texttt{a}$, $R(s[i + l: i + 2l - 1]) = \\texttt{b}$.\n- When $l = 2$, $s[i: i + l - 1] = \\texttt{ab}$, $R(s[i + l: i + 2l - 1]) = \\texttt{ca}$.\n- When $l = 3$, $s[i: i + l - 1] = \\texttt{aba}$, $R(s[i + l: i + 2l - 1]) = \\texttt{bac}$.\n- When $l = 4$, $s[i: i + l - 1] = \\texttt{abac}$, $R(s[i + l: i + 2l - 1]) = \\texttt{baba}$.\n\nIn all four cases, $s[i: i + l - 1]$ is lexicographically smaller than $R(s[i + l: i + 2l - 1])$. Thus, the answer is $4$.\n\n### **Sample Explanation #2**\n\nThis sample satisfies the conditions for test case $5$.\n\n### **Sample Explanation #4**\n\nThis sample satisfies the conditions for test cases $24 \\sim 25$.\n\n### **Constraints**\n\nFor all test cases:\n$1 \\leq t \\leq 5$, $1 \\leq n \\leq 10 ^ 5$, $1 \\leq q \\leq 10 ^ 5$, $1 \\leq i + 2r - 1 \\leq n$, and the string $s$ contains only lowercase letters.\n\n|Test Case Identifier|$n \\leq$|$q \\leq$|Special Properties|\n|:-:|:-:|:-:|:-:|\n|$1$|$5$|$5$|A|\n|$2$|$10$|$10$|A|\n|$3$|$20$|$20$|A|\n|$4$|$50$|$50$|A|\n|$5$|$10^2$|$10^2$|A|\n|$6$|$10^3$|$10^3$|None|\n|$7$|$2,000$|$2,000$|None|\n|$8$|$3,000$|$3,000$|None|\n|$9$|$4,000$|$4,000$|None|\n|$10$|$23,333$|$23,333$|A|\n|$11$|$5 \\times 10 ^ 4$|$5 \\times 10 ^ 4$|A|\n|$12$|$75,000$|$75,000$|A|\n|$13$|$9 \\times 10 ^ 4$|$9 \\times 10 ^ 4$|A|\n|$14$|$10 ^ 5$|$10 ^ 5$|A|\n|$15$|$23,333$|$23,333$|B|\n|$16$|$75,000$|$75,000$|B|\n|$17$|$9 \\times 10 ^ 4$|$9 \\times 10 ^ 4$|B|\n|$18$|$10 ^ 5$|$10 ^ 5$|B|\n|$19$|$23,333$|$23,333$|None|\n|$20$|$5 \\times 10 ^ 4$|$5 \\times 10 ^ 4$|None|\n|$21$|$75,000$|$75,000$|None|\n|$22$|$9 \\times 10 ^ 4$|$9 \\times 10 ^ 4$|None|\n|$23$|$95,000$|$95,000$|None|\n|$24 \\sim 25$|$10 ^ 5$|$10 ^ 5$|None|\n\nSpecial Property A: The string contains only characters $\\texttt{a}$ and $\\texttt{b}$, and each character is independently chosen with equal probability between $\\texttt{a}$ and $\\texttt{b}$.\n\nSpecial Property B: Adjacent characters in the string are guaranteed to be different.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2356, "prompt": "### Problem Description\nRecently, Xiao Dong has made remarkable progress in calculating the number of spanning trees in undirected connected graphs. He discovered that:\n\n- The number of spanning trees of a ring graph with $n$ nodes is $n$.\n- The number of spanning trees of a complete graph with $n$ nodes is $n^{n-2}$.\n\nThese two findings made Xiao Dong ecstatic, and he became even more motivated to continue his research on counting spanning trees for various graphs. \nOne day, during a gathering with his classmates, everyone sat around a large round table. Xiao Dong looked around and was reminded of the spanning tree problem. He thought that if each classmate was treated as a node and an edge was added between neighboring classmates (nodes with a distance of $1$), the resulting graph would form a ring. However, since Xiao Dong had already mastered counting the number of spanning trees for ring graphs and found it uninteresting, he decided to modify the graph: not only did he connect adjacent classmates, but also those sitting at a distance of $2$, treating both cases as having an edge between the nodes, as shown in Figure 1.\n\n![count.png](https://img.loj.ac.cn/2021/12/29/94344181076fa.png)\n\nXiao Dong had never calculated the number of spanning trees for this type of graph before. However, he recalled a method his teacher taught for calculating spanning trees for any graph: \nConstruct an $n \\times n$ matrix $A = \\{a_{ij}\\}$, where:\n\n$$ \n\\begin{equation}\na_{ij}= \n\\begin{cases} \nd_i & i=j \\\\\n-1 & (i,j)\\in V \\\\\n0 & (i,j)\\notin V, \\, i \\neq j \n\\end{cases} \n\\end{equation} \n$$ \n\nHere, $d_i$ represents the degree of node $i$. The matrix $A$ corresponding to Figure 1 is shown below. To calculate the number of spanning trees corresponding to Figure 1, remove the last row and column of the matrix $A$, resulting in a $(n-1) \\times (n-1)$ matrix $B$. The determinant of matrix $B$ gives the number of spanning trees for Figure 1.\n\n$$\n\\mathbf{A} =\n\\begin{matrix}\n4 & -1 & -1 & 0 & 0 & 0 & -1 & -1 \\\\\n-1 & 4 & -1 & -1 & 0 & 0 & 0 & -1 \\\\\n-1 & -1 & 4 & -1 & -1 & 0 & 0 & 0 \\\\\n0 & -1 & -1 & 4 & -1 & -1 & 0 & 0 \\\\\n0 & 0 & -1 & -1 & 4 & -1 & -1 & 0 \\\\\n0 & 0 & 0 & -1 & -1 & 4 & -1 & -1 \\\\\n-1 & 0 & 0 & 0 & -1 & -1 & 4 & -1 \\\\\n-1 & -1 & 0 & 0 & 0 & -1 & -1 & 4\n\\end{matrix}\n\\quad\n\\mathbf{B} =\n\\begin{matrix}\n4 & -1 & -1 & 0 & 0 & 0 & -1 \\\\\n-1 & 4 & -1 & -1 & 0 & 0 & 0 \\\\\n-1 & -1 & 4 & -1 & -1 & 0 & 0 \\\\\n0 & -1 & -1 & 4 & -1 & -1 & 0 \\\\\n0 & 0 & -1 & -1 & 4 & -1 & -1 \\\\\n0 & 0 & 0 & -1 & -1 & 4 & -1 \\\\\n-1 & 0 & 0 & 0 & -1 & -1 & 4\n\\end{matrix}\n$$\n\nThus, the number of spanning trees is $|B| = 3528$. Xiao Dong found that the general method was too computationally complex, and other methods failed to provide a simpler formula for calculation. Therefore, he simplified the graph by breaking the round table at one point, forming a linear chain. In this case, every classmate is represented as a node, with edges between nodes at a distance of $1$ and $2$. For example, for eight nodes, the graph looks like this:\n\n![3(2).png](https://i.loli.net/2018/02/12/5a814c7f75f3e.png)\n\nThis significantly reduces the number of spanning trees. Xiao Dong continued thinking about it until the end of the gathering and finally found a quick way to calculate the number of spanning trees for this graph. However, if nodes at a distance of $3$ are also connected, Xiao Dong found himself unable to determine the total number of spanning trees efficiently. Now, he needs your help to calculate the number of spanning trees for such graphs.\n\n### Input Format\nThe input consists of two integers $k$ and $n$, separated by a space. Here:\n- $k$ indicates connecting all pairs of nodes whose distance does not exceed $k$ (inclusive).\n- $n$ indicates the total number of nodes.\n\n### Output Format\nOutput an integer representing the number of spanning trees. Since the result can be very large, output the remainder when the result is divided by $65521$.\n\n### Example\nThe graph corresponding to the example input is shown below:\n\n![\u6355\u83b7.JPG](https://i.loli.net/2018/02/12/5a814d9247c63.jpg)\n\n$$\n\\mathbf{A} =\n\\begin{matrix}\n3 & -1 & -1 & -1 & 0 \\\\\n-1 & 4 & -1 & -1 & -1 \\\\\n-1 & -1 & 4 & -1 & -1 \\\\\n-1 & -1 & -1 & 4 & -1 \\\\\n0 & -1 & -1 & -1 & 3\n\\end{matrix}\n\\quad\n\\mathbf{B} =\n\\begin{matrix}\n3 & -1 & -1 & -1 \\\\\n-1 & 4 & -1 & -1 \\\\\n-1 & -1 & 4 & -1 \\\\\n-1 & -1 & -1 & 4\n\\end{matrix}\n\\quad\n|B| = 75\n$$\n\n### Data Constraints\n#### Scale and Assumptions\nFor all test cases, $2 \\le k \\le n$.\n\n\n\n| Case ID | $k$ Range | $n$ Range | Case ID | $k$ Range | $n$ Range |\n|-|-|-|-|-|-|\n| 1 | $k = 2$ | $n \\le 10$ | 6 | $k \\le 5$ | $n \\le 100$ |\n| 2 | $k = 3$ | $n = 5$ | 7 | $k \\le 3$ | $n \\le 2000$ |\n| 3 | $k = 4$ | $n \\le 10$ | 8 | $k \\le 5$ | $n \\le 10000$ |\n| 4 | $k = 5$ | $n = 10$ | 9 | $k \\le 3$ | $n \\le 10^{15}$ |\n| 5 | $k \\le 3$ | $n \\le 100$ | 10 | $k \\le 5$ | $n \\le 10^{15}$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3344, "prompt": "### Problem Description\n\nCountry C consists of $n$ cities connected by $m$ bidirectional roads. The cities are numbered from $1$ to $n$, and the roads are numbered from $1$ to $m$. The $i^{th}$ road connects city $u_i$ and city $v_i$ with a length of $w_i$ meters. Through these roads, it is possible to travel from any city to any other city in Country C.\n\nThe citizens of Country C enjoy circular tours but dislike passing through too many roads. To accommodate this preference, the roads in Country C are constructed with special properties. Specifically, for a simple cycle that consists of $l$ roads (i.e., a cycle that does not pass through any city more than once except for the start and end city), such a cycle can be expressed as:\n\n$c_{1} \\rightarrow c_{2} \\rightarrow \\cdots \\rightarrow c_{l} \\rightarrow c_{1}$ \n\n(where for all $1 \\leq i < l$, city $c_i$ and city $c_{i+1}$ are connected by a road; $c_l$ and $c_1$ are also connected by a road; and for all $1 \\leq i < j \\leq l$, $c_{i} \\neq c_{j}$). If $l > 3$, the roads of Country C satisfy the following condition:\n - There exist two **non-adjacent** cities $u$ and $v$ in the cycle that are directly connected by a road. In other words, there exist $1 \\leq u < v \\leq l$ such that $v - u \\geq 2$, $u$ and $v$ are not simultaneously $1$ and $l$, and city $c_u$ is directly connected to city $c_v$ by a road.\n\nThe government of Country C now has a renovation plan, which requires finding a path between city $s$ and city $t$ to be renovated. During the renovation, all roads on the selected path will become inaccessible. To ensure the daily life of citizens is unaffected during this process, the remaining roads (i.e., those not included in the renovated path) must still satisfy the property that: **it is possible to travel from any city to any other city in Country C**.\n\nAs a master engineer, you are tasked with helping Country C find a renovation path that satisfies the above requirements and has the **minimum total length**.\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, representing the number of cities and the number of roads, respectively.\n\nThe next $m$ lines each contain three integers $u_i$, $v_i$, and $w_i$, representing the two endpoints of the $i^{th}$ road and its length.\n\nIt is guaranteed that every road connects two distinct cities, i.e., $u_i \\neq v_i$.\n\nThe last line contains two integers $s$ and $t$, representing the endpoints of the path to be renovated.\n\n### Output Format\n\nOutput a single integer, representing the minimum possible total length of the renovation path that satisfies the requirements. \n\n**If no such path exists, output a single integer $-1$.**\n\n### Example 1 Explanation\n\nThe path $(1, 2, 1), (2, 3, 1), (3, 4, 1)$ is the shortest path between city $1$ and city $4$, but it does not meet the requirements.\n\nThe path $(1, 3, 5), (3, 4, 1)$ meets the requirements, with a total length of $6$.\n\nThe path $(1, 2, 1), (2, 4, 6)$ also meets the requirements, with a total length of $7$.\n\nNo other paths satisfy the requirements.\n\n### Example 3\n\nSee the file `road/road3.in` and `road/road3.ans` in the contestant's directory. This example corresponds to constraints in test cases $1\\sim6$.\n\n### Example 4\n\nSee the file `road/road4.in` and `road/road4.ans` in the contestant's directory. This example corresponds to constraints in test cases $7\\sim10$.\n\n### Example 5\n\nSee the file `road/road5.in` and `road/road5.ans` in the contestant's directory. This example corresponds to constraints in test cases $11\\sim15$.\n\n### Example 6\n\nSee the file `road/road6.in` and `road/road6.ans` in the contestant's directory. This example corresponds to constraints in test cases $16\\sim20$.\n\n*However, the last three examples are too large to upload\u2026*\n\n---\n\n### Constraints\n\nFor all test cases: $2 \\leq n \\leq 5 \\times 10^{5}$, $2 \\leq m \\leq 10^{6}$, and $s \\neq t$.\n\n$1 \\leq u_{i}, v_{i} \\leq n$, $u_{i} \\neq v_{i}$, $1 \\leq w_{i} \\leq 10^{9}$. It is guaranteed that any two roads do not have the exact same endpoints. \n\nIt is also guaranteed that the given roads satisfy the property described in the second paragraph of the problem description.\n\nThe specific constraints for each test case are shown in the table below:\n\n| Test Case | $n\\le $ | $m\\le $ | Special Constraints |\n| :-: | :-: | :-:| :-: |\n| $1\\sim6$ | $2 \\times 10^3$ | $4 \\times 10^3$ | None |\n| $7\\sim10$ | $5 \\times 10^5$ | $10^6$ | $\\text{A}$ |\n| $11\\sim15$ | $5 \\times 10^5$ | $10^6$ | $\\text{B}$ |\n| $16\\sim20$ | $5 \\times 10^5$ | $10^6$ | None |\n\nSpecial Constraints A: The lengths of all roads are equal.\n\nSpecial Constraints B: All roads with $w_i = 1$ form exactly one path from $s$ to $t$, and all other roads with $w_i \\neq 1$ have endpoints that are at a distance of $2$ from each other on this path.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3851, "prompt": "### Problem Description\nThe sequences studied by Xiao Z are composed of non-negative integers. Each sequence has a length of $n$ and must satisfy $m$ additional conditions. The $i$-th condition specifies that the numbers at indices within $[L_i, R_i]$, i.e., $a_{L_i}, a_{L_{i+1}}, \\dots, a_{R_i}$, must have a minimum value **equal to $\\boldsymbol{V_i}$**.\n\nXiao Z knows that bubble sort often results in excessive time consumption. Therefore, he wants to determine the minimum number of swap operations required during bubble sort among all sequences that satisfy the additional conditions.\n\n### Input Format\nThis problem contains multiple test cases.\n\nThe first line of input contains a positive integer $T$.\n\nFor each test case, the first line contains two positive integers $n$ and $m$. It is guaranteed that $1 \\leq n, m \\leq 10^6$.\n\nThe following $m$ lines each contain three non-negative integers $L_i, R_i, V_i$, representing an additional condition. It is guaranteed that $1 \\leq L_i \\leq R_i \\leq n$ and $0 \\leq V_i \\leq 10^9$.\n\n### Output Format\nOutput $T$ lines in total, one for each test case.\n\nFor each test case, if there exists a sequence that satisfies all $m$ additional conditions, output the minimum number of swaps required during bubble sort among all such sequences. If no sequence satisfies all the conditions, output $-1$.\n\n### **Sample Explanation #1**\n\nThe conditions for this test case are $a_1 = 2022, \\min\\{a_2, a_3\\} = 39$.\n\n- If $a_2 = 39$, and $39 \\leq a_3 < 2022$, bubble sort requires only one round of swapping. In this round, $a_1$ and $a_2$ are swapped, followed by $a_2$ and $a_3$, totaling $2$ swaps.\n- If $a_2 = 39$, and $a_3 \\geq 2022$, bubble sort requires only one round of swapping. In this round, only $a_1$ and $a_2$ are swapped, totaling $1$ swap.\n- If $a_3 = 39$, and $39 < a_2 < 2022$, bubble sort requires swapping $a_1$ and $a_2$, followed by $a_2$ and $a_3$ in the first round, then swapping $a_1$ and $a_2$ again in the second round, totaling $3$ swaps.\n- If $a_3 = 39$, and $a_2 \\geq 2022$, bubble sort swaps $a_2$ and $a_3$ in the first round, followed by $a_1$ and $a_2$ in the second round, totaling $2$ swaps.\n\nThe minimum number of swaps is therefore $1$.\n\n----\n\n### **Sample #2**\n\nRefer to the files `bubble/bubble2.in` and `bubble/bubble2.ans`.\n\n----\n\n### **Sample #3**\n\nRefer to the files `bubble/bubble3.in` and `bubble/bubble3.ans`.\n\nThis sample satisfies the conditions of test points $8$ to $10$.\n\n----\n\n### **Sample #4**\n\nRefer to the files `bubble/bubble4.in` and `bubble/bubble4.ans`.\n\nThis sample satisfies the conditions of test points $13$ to $14$.\n\n----\n\n### **Sample #5**\n\nRefer to the files `bubble/bubble5.in` and `bubble/bubble5.ans`.\n\nThis sample satisfies the conditions of test points $15$ to $16$.\n\n----\n\n### **Sample #6**\n\nRefer to the files `bubble/bubble6.in` and `bubble/bubble6.ans`.\n\nThis sample satisfies the conditions of test points $23$ to $25$.\n\n----\n\n### **Constraints**\n\nThis problem contains $25$ test points. All test points satisfy the constraints: $1 \\leq T \\leq 1000$, $1 \\leq \\sum n, \\sum m \\leq 10^6$, $1 \\leq L_i \\leq R_i \\leq n$, $0 \\leq V_i \\leq 10^9$.\n\nHere, $\\sum n$ and $\\sum m$ represent the total sum of $n$ and $m$ across all test points, respectively. $\\sum n^2$, $\\sum m^2$, $\\sum n^3$, and $\\sum m^3$ have similar meanings.\n\n| Test Points | Data Range | Special Properties |\n|:-------------:|:-----------------------------------------------------:|:------------------:|\n| $1 \\sim 4$ | $n,m \\leq 7$, and at most $2$ test cases exceed $n, m \\leq 5$ | |\n| $5 \\sim 7$ | $n,m \\leq 17$, and at most $3$ test cases exceed $n, m \\leq 9$ | A |\n| $8 \\sim 10$ | $n,m \\leq 100$, $\\sum n^3, \\sum m^3 \\leq 4 \\times 10^7$ | A |\n| $11 \\sim 12$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| A |\n| $13 \\sim 14$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| B |\n| $15 \\sim 16$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| C |\n| $17 \\sim 18$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| |\n| $19$ | $\\sum n,\\sum m \\leq 10^6$ | A |\n| $20$ | $\\sum n,\\sum m \\leq 10^6$ | B |\n| $21 \\sim 22$ | $\\sum n,\\sum m \\leq 10^6$ | C |\n| $23 \\sim 25$ | $\\sum n,\\sum m \\leq 10^6$ | |\n\nSpecial Property A: For $1 \\leq i \\leq m$, $0 \\leq V_i \\leq 1$. \nSpecial Property B: For $1 \\leq i \\leq m$, $L_i = R_i$. \nSpecial Property C: The $m$ intervals $[L_i, R_i]$ given in input are pairwise non-overlapping.\n\n----\n\n### **Hint**\n\nSome test cases have large input sizes. It is recommended to use a fast input method.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2954, "prompt": "### Problem Description\n\nLittle D loves playing games. One day, he is playing a number-filling game.\n\nThe board of this number-filling game is an $n\\times m$ rectangular grid. Players need to fill each cell of the grid with either the number $0$ or $1$, while meeting certain constraints. Let's describe these constraints in detail.\n\nTo facilitate the description, we first define some terms:\n- Each cell is represented by its row and column coordinates $(x, y)$, where $x$ is the row index and $y$ is the column index (note: both indices start from $0$).\n- Valid Path $P$: A path is valid if and only if:\n 1. The path starts from the top-left cell of the grid $(0,0)$ and ends at the bottom-right cell of the grid $(n-1,m-1)$;\n 2. For each step along the path, you can either move to the cell immediately to the right of the current cell or to the cell immediately below the current cell.\n\nFor example, in the grid shown below, there are only two valid paths: $P_1:(0,0)\\to (0,1)\\to (1,1)$, and $P_2:(0,0)\\to (1,0)\\to (1,1)$.\n\n![game.png](https://i.loli.net/2018/11/25/5bfa4a3e042ef.png)\n\nFor a valid path $P$, we can represent it using a string $w(P)$. The length of $w(P)$ is $n+m-2$, and it consists only of characters `R` and `D`. The $i$-th character records the $i$-th move in the path $P$: `R` indicates moving to the cell immediately to the right, and `D` indicates moving to the cell immediately below. For example, in the figure above, for the path $P_1$, $w(P_1)=\\texttt{RD}$; and for the other path $P_2$, $w(P_2)=\\texttt{DR}$.\n\nAt the same time, for any valid path $P$, if you concatenate the numbers filled in each cell along the path, it forms a binary string of length $n+m-1$, denoted as $s(P)$. For example, if you fill the number $0$ in cells $(0,0)$ and $(1,0)$, and the number $1$ in cells $(0,1)$ and $(1,1)$ (as shown by the red numbers in the figure above), then for the path $P_1$, $s(P_1)=\\texttt{011}$, and for the path $P_2$, $s(P_2)=\\texttt{001}$.\n\nThe goal of the game is to find a way to fill the numbers $0$ and $1$ into the grid such that for any two paths $P_1$ and $P_2$, if $w(P_1) > w(P_2)$, then it must satisfy $s(P_1) \\leq s(P_2)$. A string $a$ is considered smaller than a string $b$ if and only if $a$ is lexicographically smaller than $b$. The definition of lexicographical order can be found in [Problem 1](https://loj.ac/problem/2953).\n\nHowever, simply finding one valid solution does not satisfy Little D's curiosity. Little D wants to know how many different ways there are to fill the grid such that the game requirements are met. \n\nSince the answer can be very large, you need to output the result modulo $10^9+7$.\n\n### Input Format\n\nThe input file is named `game.in`. \nThe input consists of a single line containing two positive integers $n$ and $m$, separated by a space, representing the size of the rectangular grid. Here, $n$ is the number of rows, and $m$ is the number of columns.\n\n### Output Format\n\nThe output file is named `game.out`. \nThe output consists of a single line containing one positive integer, the number of ways to fill the grid with $0$s and $1$s that meet the game's requirements. \nThe answer should be output modulo $10^9+7$.\n\n### Example 1\n\nGrid for a $2 \\times 2$ board: \n![game2.png](https://i.loli.net/2018/11/25/5bfa4bb92d884.png)\n\nFor a $2\\times 2$ grid, there are 12 valid ways to fill the grid that satisfy the requirements.\n\n### Example 2\n\n### Example 3\n\n### Constraints and Hints\n\n| Test Case ID | $n \\leq$ | $m \\leq$ |\n| :----------: | :------: | :------: |\n| $1\\sim 4$ | $3$ | $3$ |\n| $5\\sim 10$ | $2$ | $10^6$ |\n| $11\\sim 13$ | $3$ | $10^6$ |\n| $14\\sim 16$ | $8$ | $8$ |\n| $17\\sim 20$ | $8$ | $10^6$ |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3984, "prompt": "### Problem Description\n\nLittle C has $n$ books, each with a specific weight. He decides to combine them into a single stack.\n\nIn each merging operation, Little C can stack one pile of books onto another, thereby merging them into one pile. If Little C places the $i$-th pile of books on top of the $j$-th pile, the energy consumption for this operation is calculated as **the weight of the $i$-th pile** plus **the sum of the wear values of the two piles**.\n\nInitially, each book forms its own pile, and the wear value of each pile is $0$. After Little C merges two piles, the newly formed pile's wear value is **twice the larger of the two original wear values, plus one**, and its weight is **the sum of the weights of the two original piles**.\n\nYour task is to design a merging sequence that minimizes Little C's total energy consumption and output this minimum energy consumption.\n\n### Input Format\n\n**This problem has multiple test cases.**\n\nThe first line of input contains a positive integer $t$, the number of test cases.\n\nThe following lines contain the data for each test case. For each test case:\n\n- The first line contains a positive integer $n$, the number of books.\n- The second line contains $n$ positive integers, where the $i$-th number $w_i$ represents the weight of the $i$-th book.\n\n### Output Format\n\nFor each test case, output one line containing a single integer \u2014 the minimum energy consumption required to combine $n$ books into one pile.\n\n**Example Explanation #1**\n\nIf Little C combines the $4$ books in pairs, then combines the resulting two piles into one pile:\n\n- The energy cost of the first two merges is $1$ each. \n- The third merge involves stacking a pile weighing $2$ onto another pile, with each pile having a wear value of $1$, resulting in an energy cost of $2 + 1 + 1 = 4$.\n\nThus, for this sequence, the total energy consumption is $1 + 1 + 4 = 6$.\n\nIt can be proven that $6$ is the minimum energy consumption for the given example.\n\n### Constraints\n\nFor all test cases:\n\n$1 \\leq t \\leq 10$, $1 \\leq n \\leq 100$, $1 \\leq w_i \\leq 10^9$.\n\n| Test Case ID | $n \\leq$ | Special Properties |\n|:-------------:|:--------:|:------------------:|\n| $1 \\sim 2$ | $7$ | No |\n| $3$ | $11$ | No |\n| $4$ | $13$ | No |\n| $5 \\sim 6$ | $22$ | No |\n| $7 \\sim 8$ | $28$ | No |\n| $9 \\sim 13$ | $50$ | No |\n| $14$ | $60$ | No |\n| $15$ | $70$ | No |\n| $16$ | $80$ | No |\n| $17 \\sim 18$ | $100$ | Yes |\n| $19 \\sim 20$ | $100$ | No |\n\nSpecial Property: Guaranteed $w_i = 1$ for these cases. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3979, "prompt": "### Problem Description\n\nYou are given a chessboard with $n$ columns and $m$ rows, consisting of $n \\times m$ cells. Both rows and columns are indexed starting from $1$, and the cell in the $i$th column and $j$th row is denoted by $(i, j)$. Initially, all cells are white. Now, you are required to perform $q$ coloring operations on the chessboard.\n\nThere are three types of coloring operations:\n\n1. **Coloring a horizontal line:** Specifically, given two cells $(x_1, y_1)$ and $(x_2, y_2)$, where $x_1 \\leq x_2$ and $y_1 = y_2$, all cells between these two (inclusive) are colored black.\n2. **Coloring a vertical line:** Specifically, given two cells $(x_1, y_1)$ and $(x_2, y_2)$, where $x_1 = x_2$ and $y_1 \\leq y_2$, all cells between these two (inclusive) are colored black.\n3. **Coloring a diagonal line:** Specifically, given two cells $(x_1, y_1)$ and $(x_2, y_2)$, where $x_1 \\leq x_2$ and $x_2 - x_1 = y_2 - y_1$, all diagonal cells of the form $(x_1 + i, y_1 + i)$ for $0 \\leq i \\leq x_2 - x_1$ are colored black. **This type of coloring operation will occur at most $5$ times.**\n\nYour task is to determine how many cells on the chessboard are black after $q$ coloring operations.\n\n---\n\n### Input Format\n\nInput data is read from the file `color.in`.\n\nThe first line contains an integer $c$, which represents the test case number. $c = 0$ indicates that this test case is a sample case.\n\nThe second line contains three positive integers $n$, $m$, and $q$, representing the number of columns, rows, and coloring operations, respectively.\n\nThe next $q$ lines describe the coloring operations. Each line contains five positive integers $t$, $x_1$, $y_1$, $x_2$, $y_2$:\n\n- $t = 1$ represents the first type of coloring operation.\n- $t = 2$ represents the second type of coloring operation.\n- $t = 3$ represents the third type of coloring operation.\n- The integers $x_1$, $y_1$, $x_2$, and $y_2$ specify the parameters for the operation.\n\n---\n\n### Output Format\n\nOutput the result to the file `color.out`.\n\nOutput a single line containing a single integer, which represents the number of black cells on the chessboard after all the operations.\n\n---\n\n### Example 1\n\nIn this example, three coloring operations are performed, as shown in the figure below:\n\n![color.png](https://img.loj.ac.cn/2023/07/31/8da82c4679eac.png)\n\n1. In the first operation, the cells $(1, 3), (2, 3), (3, 3), (4, 3), (5, 3)$ are colored black.\n\n2. In the second operation, the cells $(3, 1), (3, 2), (3, 3), (3, 4), (3, 5)$ are colored black.\n\n3. In the third operation, the cells $(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)$ are colored black.\n\n---\n\n### Example 2\n\nSee the attached files `color2.in` and `color2.ans` for further details.\n\nThis example satisfies the conditions for test points $1 \\sim 5$.\n\n---\n\n### Example 3\n\nSee the attached files `color3.in` and `color3.ans` for further details.\n\nThis example satisfies the conditions for test points $6 \\sim 9$.\n\n---\n\n### Example 4\n\nSee the attached files `color4.in` and `color4.ans` for further details.\n\nThis example satisfies the conditions for test points $10 \\sim 13$.\n\n---\n\n### Example 5\n\nSee the attached files `color5.in` and `color5.ans` for further details.\n\nThis example satisfies the conditions for test points $14 \\sim 17$.\n\n---\n\n### Example 6\n\nSee the attached files `color6.in` and `color6.ans` for further details.\n\nThis example satisfies the conditions for test points $18 \\sim 19$.\n\n---\n\n### Example 7\n\nSee the attached files `color7.in` and `color7.ans` for further details.\n\nThis example satisfies the conditions for test point $20$.\n\n---\n\n### Constraints and Hints\n\nFor all test cases:\n\n- $1 \\leq n, m \\leq 10^9$ \n- $1 \\leq q \\leq 10^5$ \n- $1 \\leq x_1, x_2 \\leq n$ \n- $1 \\leq y_1, y_2 \\leq m$ \n- **There will be at most $5$ operations of the third type.**\n\n| Test Case Number | $n, m \\leq$ | $q \\leq$ | Special Properties |\n|:-----------------:|:-----------:|:--------:|:------------------:|\n| $1 \\sim 5$ | $300$ | $300$ | None |\n| $6 \\sim 9$ | $10^5$ | $2000$ | None |\n| $10 \\sim 13$ | $10^5$ | $10^5$ | A |\n| $14 \\sim 17$ | $10^5$ | $10^5$ | B |\n| $18 \\sim 19$ | $10^5$ | $10^5$ | None |\n| $20$ | $10^9$ | $10^5$ | None |\n\nSpecial Property A: Only the first type of coloring operation will occur. \nSpecial Property B: Only the first and second types of coloring operations will occur.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3341, "prompt": "### Problem Description\n\nLittle L enjoys discussing and exchanging ideas with a wise individual, who often presents Little L with challenging problems to think about.\n\nOne day, the wise individual conceived a new problem for Little L. The wise individual first abstracted spacetime into a two-dimensional plane, where an **event** is represented by a point on the plane and an **epoch** is represented by a rectangle on the plane.\n\nTo facilitate the problem, let $(a, b) \\leq (c, d)$ denote two points $(a, b)$ and $(c, d)$ on the plane satisfying $a \\leq c$ and $b \\leq d$.\n\nSpecifically, the wise individual provided $n$ **events**, represented by $n$ **distinct points** $\\{(x_i, y_i)\\}^n_{i=1}$ on the plane;\n\nThe wise individual also provided $m$ **epochs**, where each epoch is represented by a **rectangle** $(r_{i,1}, r_{i,2}, c_{i,1}, c_{i,2})$, where $(r_{i,1}, c_{i,1})$ is the bottom-left corner of the rectangle and $(r_{i,2}, c_{i,2})$ is the top-right corner, ensuring $(r_{i,1}, c_{i,1}) \\leq (r_{i,2}, c_{i,2})$. Epoch $i$ is said to **contain** event $j$ if and only if $(r_{i,1}, c_{i,1}) \\leq (x_j, y_j) \\leq (r_{i,2}, c_{i,2})$.\n\nThe wise individual considers two events $i$ and $j$ to form a **regret** if $(x_i, y_i) \\leq (x_j, y_j)$. For all events included in a single epoch, the regrets they form are referred to as the **tears** of that epoch, and the total number of regrets is referred to as the **size of the tears** of the epoch. Now, the wise individual wants Little L to calculate the **size of the tears** for each epoch.\n\nLittle L understands that if he cannot solve the problem, he will also become a tear of the epoch. Can you help him?\n\n---\n\n### Input Format\nInput is read from the file `tears.in`.\n\nThe first line contains two integers $n$ and $m$, representing the number of events and the number of epochs, respectively.\n\nThe second line contains $n$ integers $p_i$, where the $i$-th integer represents the coordinate of event $i$ as $(i, p_i)$ on the plane. It is guaranteed that $p_i$ is a permutation of $1$ to $n$.\n\nThe next $m$ lines each contain four integers $r_{i,1}, r_{i,2}, c_{i,1}, c_{i,2}$, representing the rectangle corresponding to each epoch.\n\n---\n\n### Output Format\nOutput to the file `tears.out`.\n\nThe output should contain $m$ lines, where the $i$-th line contains a single integer, representing the size of the tears for the $i$-th epoch.\n\n---\n\n### Example\n\nFor epoch $1$, the regrets included are $(6, 7)$ (i.e., event $6$ and event $7$ form a regret, and so on).\n\nFor epoch $2$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epoch $3$, the regrets included are $(5, 6), (5, 8)$.\n\nFor epoch $4$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epoch $5$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epoch $6$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epochs $7, 8, 9$, none of these include any regrets.\n\nRefer to the `tears2.in` and `tears2.ans` files for the input and expected output of this example.\n\n---\n\n### Constraints and Example Explanation\nRefer to the `tears3.in` and `tears3.ans` files for another example.\n\n#### Constraints\nFor all test cases, $1 \\leq n \\leq 10^5$, $1 \\leq m \\leq 2 \\times 10^5$, and $1 \\leq r_{i,1}, r_{i,2}, c_{i,1}, c_{i,2} \\leq n$.\n\nThe specific constraints for each test case are given in the following table:\n\n| Test Case ID | $n \\leq$ | $m \\leq$ | Special Properties |\n|:------------:|:---------:|:---------:|:------------------:|\n| $1\\sim3$ | $10$ | $10$ | |\n| $4$ | $3,000$ | $3,000$ | |\n| $5$ | $4,000$ | $4,000$ | |\n| $6$ | $5,000$ | $5,000$ | |\n| $7$ | $25,000$ | $50,000$ | A |\n| $8$ | $50,000$ | $100,000$ | A |\n| $9$ | $75,000$ | $150,000$ | A |\n| $10$ | $100,000$ | $200,000$ | A |\n| $11$ | $60,000$ | $120,000$ | B |\n| $12$ | $80,000$ | $160,000$ | B |\n| $13$ | $100,000$ | $200,000$ | B |\n| $14$ | $20,000$ | $40,000$ | |\n| $15$ | $30,000$ | $60,000$ | |\n| $16$ | $40,000$ | $80,000$ | |\n| $17$ | $50,000$ | $100,000$ | |\n| $18$ | $60,000$ | $120,000$ | |\n| $19$ | $70,000$ | $140,000$ | |\n| $20\\sim22$ | $100,000$ | $200,000$ | C |\n| $23\\sim25$ | $100,000$ | $200,000$ | |\n\n#### Special Constraints\n- **Constraint A**: For all epochs $i$, $c_{i,1} = 1$ and $c_{i,2} = n$.\n- **Constraint B**: For any two different epochs, their rectangles are either inclusive (one rectangle is inside the other, allowing their boundaries to overlap) or disjoint (rectangles share no common points, and their boundaries do not overlap).\n- **Constraint C**: At most $50$ pairs of events $(i, j)$ ($1 \\leq i < j \\leq n$) **do not satisfy** $(i, p_i) \\leq (j, p_j)$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2303, "prompt": "### Problem Description\nThere are $n$ worms in the Worm Kindergarten. To make management easier, the kindergarten director, \"Shen Daoshou,\" often asks the worms to line up and perform.\n\nAll the worms are numbered consecutively as integers from $1$ to $n$. Each worm's length can be represented by a positive integer, and due to admission criteria, the length of each worm does not exceed $6$. Shen Daoshou hopes to arrange the worms into several teams. Initially, each worm forms a team by itself, where it is both the head and tail of the team.\n\nShen Daoshou will perform $m$ operations one by one, where each operation is one of the following three types:\n\n1. Given $i$ and $j$, merge the teams that $i$-th worm and $j$-th worm belong to into a single team. Specifically, place the $j$-th worm immediately after the $i$-th worm, keeping the relative order of all other worms in both teams unchanged.\n\n2. Given $i$, split the $i$-th worm and the worm immediately following it into two separate teams. Specifically, after the split, the $i$-th worm becomes the tail of one team, and the worm originally immediately following it becomes the head of another team, keeping the relative order of all other worms unchanged.\n\n3. Given a positive integer $k$ and a numeric string $s$ of length at least $k$, for every length-$k$ substring $t$ of $s$ (there are $|s| - k + 1$ such substrings, where $|s|$ is the length of $s$), define a function $f(t)$, and query the **product** of all these $f(t)$ values modulo $998244353$. The function $f(t)$ is defined as follows:\n\nFor the current arrangement of worm teams, define the **backward $k$ digital string** of a worm as follows: Starting from that worm, move backward along the team to find the nearest $k$ worms (including itself), and join their lengths as digits to form a numeric string. If fewer than $k$ worms can be found, that worm does not have a **backward $k$ digital string**. For example, if the worm team is composed of worm $10$ (team head) followed by worm $22$ and worm $3$ (team tail), whose lengths are $4$, $5$, and $6$, respectively, the **backward $3$ digital string** of worm $10$ is `456`; worm $22$ does not have a **backward $3$ digital string**, but its **backward $2$ digital string** is `56`, and its **backward $1$ digital string** is `5`.\n\nMeanwhile, $f(t)$ indicates the count of worms whose **backward $k$ digital string** is exactly equal to $t$.\n\n### Input Format\nThe first line contains two positive integers, $n$ and $m$, which represent the number of worms and the number of operations, respectively.\n\nThe second line contains $n$ positive integers not exceeding $6$, representing the lengths of worms numbered $1, 2, \\dots, n$, in order.\n\nThe next $m$ lines describe the operations, each of which can be in one of the following formats:\n\n* `1` $i$ $j$ ($1 \\leq i, j \\leq n$): This denotes merging the teams of worms $i$ and $j$. In the new team, the $j$-th worm is placed immediately after the $i$-th worm. Prior to this operation, the $i$-th worm is guaranteed to be the tail of its team, while the $j$-th worm is guaranteed to be the head of its team, and the two worms reside in different teams.\n\n* `2` $i$ ($1 \\leq i \\leq n$): This denotes splitting the $i$-th worm and the worm immediately following it into two teams. Before this operation, it is guaranteed that the $i$-th worm is not the tail of its team.\n\n* `3` $s$ $k$ ($k$ is a positive integer, $s$ is a numeric string of length at least $k$): This queries the result of the product of $f(t)$ for each length-$k$ substring $t$ of $s$ modulo $998244353$. The definition of $f(t)$ is provided in the problem description.\n\nAdjacent elements in the same input line are separated by exactly one space.\n\nThe input file might be large; avoid using excessively slow input methods.\n\n### Output Format\nFor each operation of type `3 s k`, output a single integer representing the queried result.\n\n### Constraints\nIt is guaranteed that $n \\leq 2 \\times 10^{5}$, $m \\leq 5 \\times 10^{5}$, and $k \\leq 50$. \n\nLet $\\sum |s|$ represent the sum of the lengths of all queried $s$ strings in a particular input file. It is guaranteed that $\\sum |s| \\leq 10^{7}$. \n\nLet $c$ represent the count of type `2 i` operations in a particular input file. It is guaranteed that $c \\leq 10^{3}$.\n\nDetailed testing point information is provided in the table below:\n\n| Test Point ID | $n$ | $m$ | $k$ | $\\sum |s|$ | $c$ | All $\\texttt{1}$ |\n|:-:|:-:|:-:|:-:|:-:|:-:|:-:|\n| 1 | $=1$ | $\\leq 10^{3}$ | $=1$ | $\\leq 10^{3}$ | $=0$ | No |\n| 2 | $\\leq 20$ | $\\leq 40$ | $\\leq 10$ | $\\leq 10^{3}$ | $=0$ | No |\n| 3 | $\\leq 150$ | $\\leq 2,000$ | $\\leq 50$ | $\\leq 10^{3}$ | $\\leq 10^{3}$ | No |\n| 4 | $\\leq 500$ | $\\leq 600$ | $\\leq 50$ | $\\leq 10^{3}$ | $=0$ | No |\n| 5 | $\\leq 10^{3}$ | $\\leq 2,000$ | $\\leq 50$ | $\\leq 10^{3}$ | $\\leq 10^{3}$ | No |\n| 6 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 5$ | $\\leq 5 \\times 10^{4}$ | $\\leq 10^{3}$ | No |\n| 7 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 50$ | $\\leq 5 \\times 10^{4}$ | $=0$ | Yes |\n| 8 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 50$ | $\\leq 5 \\times 10^{4}$ | $=0$ | No |\n| 9 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 50$ | $\\leq 5 \\times 10^{4}$ | $\\leq 10^{3}$ | No |\n| 10 | $\\leq 5 \\times 10^{4}$ | $\\leq 8 \\times 10^{4}$ | $\\leq 50$ | $\\leq 2.5 \\times 10^{6}$ | $=0$ | No |\n| 11 | $\\leq 5 \\times 10^{4}$ | $\\leq 8 \\times 10^{4}$ | $\\leq 50$ | $\\leq 2.5 \\times 10^{6}$ | $\\leq 10^{3}$ | No |\n| 12 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 6$ | $\\leq 10^{5}$ | $\\leq 10^{3}$ | No |\n| 13 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{5}$ | $=0$ | Yes |\n| 14 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{5}$ | $=0$ | No |\n| 15 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{5}$ | $\\leq 10^{3}$ | No |\n| 16 | $\\leq 10^{5}$ | $\\leq 1.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 5 \\times 10^{6}$ | $=0$ | No |\n| 17 | $\\leq 10^{5}$ | $\\leq 1.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 5 \\times 10^{6}$ | $\\leq 10^{3}$ | No |\n| 18 | $\\leq 2 \\times 10^{5}$ | $\\leq 5 \\times 10^{5}$ | $=1$ | $\\leq 10^{7}$ | $=0$ | No |\n| 19 | $\\leq 2 \\times 10^{5}$ | $\\leq 5 \\times 10^{5}$ | $=1$ | $\\leq 10^{7}$ | $\\leq 10^{3}$ | No |\n| 20 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 7$ | $\\leq 2 \\times 10^{5}$ | $\\leq 10^{3}$ | No |\n| 21 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 2 \\times 10^{5}$ | $=0$ | Yes |\n| 22 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 2 \\times 10^{5}$ | $=0$ | No |\n| 23 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 2 \\times 10^{5}$ | $\\leq 10^{3}$ | No |\n| 24 | $\\leq 2 \\times 10^{5}$ | $\\leq 3 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{7}$ | $=0$ | No |\n| 25 | $\\leq 2 \\times 10^{5}$ | $\\leq 3 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{7}$ | $\\leq 10^{3}$ | No |\n\nIf the \"All $\\texttt{1}$\" column of a test point is `Yes`, it means all worms' lengths are `1`, and every character in each query string $s$ is also `1`.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2133, "prompt": "### Problem Description\n\nThe annual \"Phantom Pavilion Summer Wine Tasting Festival\" has grandly opened. The festival features two sections: tasting and fun challenges, with the titles of \"Top Taster\" and \"Top Hunter\" awarded to the winners, attracting numerous wine tasters.\n\nDuring the festival dinner, Rainbow, the bartender, prepared $n$ glasses of cocktails. These $n$ glasses of cocktails are arranged in a row, with the $i$th glass ($1 \\leq i \\leq n$) labeled as $s_i$, where each label is one of the $26$ lowercase English letters. Let $\\mathrm{Str}(l, r)$ represent the string formed by concatenating the labels of the cocktails from glass $l$ to glass $r$ in sequence for $r - l + 1$ labels. If $\\mathrm{Str}(p, p_0) = \\mathrm{Str}(q, q_0)$, where $1 \\leq p \\leq p_0 \\leq n$, $1 \\leq q \\leq q_0 \\leq n$, $p \\neq q$, and $p_0 - p + 1 = q_0 - q + 1 = r$, then the $p$th glass and $q$th glass of cocktails are considered \"$r$-similar\". Clearly, two \"$r$-similar\" ($r > 1$) cocktails are also \"$1$-similar\", \"$2$-similar\", $\\dots$, \"$(r-1)$-similar\". Specifically, for any $1 \\leq p, q \\leq n$, where $p \\neq q$, the $p$th glass and the $q$th glass of cocktails are always \"$0$-similar\".\n\nIn the tasting section of the festival, Freda the wine taster easily assessed the deliciousness of each glass of wine. Due to her professional skills and experience, she successfully earned the title of \"Top Taster\". The deliciousness of the $i$th glass of wine ($1 \\leq i \\leq n$) is $a_i$. Now, Rainbow revealed the challenge: the cocktails for this festival have one unique feature\u2014if two glasses of cocktails, $p$ and $q$, are mixed, the resulting glass of wine will have a deliciousness of $a_p \\cdot a_q$. Please calculate the following for each $r = 0, 1, 2, \\dots, n - 1$:\n\n1. The number of ways to choose two \"$r$-similar\" glasses of cocktails.\n2. The maximum deliciousness that can be obtained by mixing two \"$r$-similar\" glasses of cocktails.\n\n### Input Format\n\nThe first line of the input contains a positive integer $n$, which represents the number of glasses of cocktails.\n\nThe second line contains a string $S$ of length $n$, where the $i$th character represents the label of the $i$th glass of wine.\n\nThe third line contains $n$ integers, separated by single spaces, where the $i$th integer represents the deliciousness $a_i$ of the $i$th glass of wine.\n\n### Output Format\n\nThe output consists of $n$ lines. The $i$th line contains two integers separated by a single space:\n\n1. The number of ways to select two \"$(i-1)$-similar\" glasses of cocktails.\n2. The maximum deliciousness obtained by mixing two \"$(i-1)$-similar\" glasses of cocktails.\n\nIf no two \"$(i-1)$-similar\" glasses of cocktails exist, both integers in the output should be $0$.\n\n### Example 1\n\nUsing a pair $(p, q)$ to represent the $p$th and $q$th glasses of wine:\n\n- **$0$-similar:** All $45$ pairs are $0$-similar, with the maximum deliciousness being $8 \\times 7 = 56$.\n- **$1$-similar:** $(1,8)$, $(2,4)$, $(2,9)$, $(4,9)$, $(5,6)$, $(5,7)$, $(5,10)$, $(6,7)$, $(6,10)$, $(7,10)$, maximum deliciousness is $8 \\times 7 = 56$.\n- **$2$-similar:** $(1,8)$, $(4,9)$, $(5,6)$, maximum deliciousness is $4 \\times 8 = 32$.\n- **No $3$-, $4$-, $5$-, $\\dots$-, $9$-similar pairs of glasses, so output is $0$ for these cases.\n\n### Example 2\n\n... Add specific input/output details for a second example if needed...\n\n---\n\n### Constraints and Hints\n\n| Case # | Scale of $n$ | Scale of $a_i$ | Remarks |\n|:-:|:-:|:-:|:-:|\n| 1 | $n = 100$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 2 | $n = 200$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 3 | $n = 500$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 4 | $n = 750$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 5 | $n = 1000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 6 | $n = 1000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 7 | $n = 2000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 8 | $n = 2000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 9 | $n = 99991$ | $\\lvert a_i \\rvert \\leq 10^9$ | No \"$10$-similar\" glasses |\n| 10 | $n = 99991$ | $\\lvert a_i \\rvert \\leq 10^9$ | No \"$10$-similar\" glasses |\n| 11 | $n = 100000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 12 | $n = 200000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 13 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 14 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 15 | $n = 100000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 16 | $n = 100000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 17 | $n = 200000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 18 | $n = 200000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 19 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 20 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3537, "prompt": "### Problem Description\n\nLittle R has $m$ ($1 \\le m \\le 1000$) robots and $m$ paper tapes. The $i$-th robot ($1 \\le i \\le m$) is responsible for operating on the $i$-th paper tape. Each paper tape is divided from left to right into $n$ ($1 \\le n \\le 32$) cells, numbered sequentially as $0, 1, \\ldots, n - 1$. Each cell can have one of three states: \n1. The cell contains the digit `0`. \n2. The cell contains the digit `1`. \n3. The cell is empty.\n\nAt any point in time, the robot **must** stand on one of the cells of the paper tape. After initializing the robot's starting position on the paper tape, the $i$-th robot will execute a predetermined operational sequence $S_i$, consisting of the characters `R`, `0`, `1`, and `*`, where:\n\n1. `R` instructs the robot to move one cell to the right. If there are no cells to the right, the robot will explode on the spot. \n2. `0` instructs the robot, if it is on a non-empty cell, to change the content of that cell to `0`. Otherwise, no change is made. \n3. `1` instructs the robot, if it is on a non-empty cell, to change the content of that cell to `1`. Otherwise, no change is made. \n4. `*` instructs the robot, if it is on a non-empty cell, to flip the content of the cell (`0` becomes `1`, and `1` becomes `0`). Otherwise, no change is made.\n\nThe state of the $i$-th paper tape can be represented by a sequence of length $n$, where each element is `0`, `1`, or `-` (for an empty cell), describing the state of each cell. The initial state of the $i$-th paper tape is called the input $X_i$, and the state after the operation sequence has been fully executed is called the output $Y_i$. Note: If a robot explodes, then this robot will not produce any output.\n\nIt can be observed that if a cell is empty, the robot will never modify its state. Therefore, each robot has the following property: If all the cells in the paper tape of the $i$-th robot are empty, the robot will not perform any operations, and the output will also have all cells empty.\n\nNow, Little R provides the input $X_i$ (initial state of each paper tape) and target output $Y_i$ for each robot. Little R wants Little D to find a position $p$ ($0 \\le p < n$) such that **all robots** can start from the $p$-th cell on their respective paper tapes, complete the operations without exploding, and ultimately produce output $Y_i$ for the $i$-th robot.\n\nLittle D solves the problem in a few milliseconds, but he is now curious to know how many combinations of input and output configurations exist such that the above conditions can be satisfied for at least one position $p$ ($0 \\le p < n$). In other words, how many ways can inputs $X_0, X_1, \\ldots, X_{m-1}$ and target outputs $Y_0, Y_1, \\ldots, Y_{m-1}$ be defined such that there exists at least one position $p$ that allows all robots to satisfy the conditions described. Since the final answer can be very large, output the result modulo ${10}^9 + 7$.\n\nTwo configurations are considered different if and only if there exists at least one robot with a different input or target output in the two configurations.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of cells on each paper tape and the number of paper tapes, respectively.\n\nThe next $m$ lines each contain a string $S_i$ consisting only of the characters `R`, `0`, `1`, and `*`. The string $S_i$ represents the operation sequence for the $i$-th robot.\n\n---\n\n### Output Format\n\nOutput a single positive integer representing the result modulo ${10}^9 + 7$.\n\n---\n\n### **Sample Explanation #1**\n\n| Combination No. | Input $X_0$ | Target Output $Y_0$ | Valid Starting Position $p$ |\n|:-:|:-:|:-:|:-:|\n| $1$ | `--` | `--` | $0, 1$ |\n| $2$ | `0-` | `1-` | $0$ |\n| $3$ | `1-` | `1-` | $0$ |\n| $4$ | `-0` | `-1` | $0$ |\n| $5$ | `-1` | `-0` | $0$ |\n| $6$ | `00` | `11` | $0$ |\n| $7$ | `10` | `11` | $0$ |\n| $8$ | `01` | `10` | $0$ |\n| $9$ | `11` | `10` | $0$ |\n\nHere, `-` represents an empty cell. Observe that in combination $1$, both the input and output are entirely empty, so multiple valid starting positions ($p = 0$, $p = 1$) are available. \n\nWhen the input is not entirely empty, only the position $p = 0$ is a valid starting location, as starting from $p = 1$ will cause the robot to explode. For example, in combination $2$, the target output `1-` comes from modifying the first cell to `1` and leaving the second cell unchanged (`-`).\n\n---\n\n### **Sample Explanation #2**\n\nThis sample can be solved using the principle of inclusion-exclusion (details omitted for brevity). The final answer is $1468$.\n\n---\n\n### Constraints\n\nFor all test cases: $1 \\le n \\le 32$, $1 \\le m \\le 1000$, $1 \\le |S_i| \\le 100$.\n\n| Test Case Index | $n$ (Max) | $m$ (Max) | Special Constraints |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 2$ | $1$ | $1$ | None |\n| $3$ | $8$ | $1$ | None |\n| $4$ | $16$ | $1$ | None |\n| $5 \\sim 6$ | $32$ | $1$ | None |\n| $7$ | $16$ | $5$ | None |\n| $8 \\sim 10$ | $32$ | $5$ | None |\n| $11 \\sim 12$ | $16$ | $1000$ | None |\n| $13 \\sim 15$ | $32$ | $1000$ | A |\n| $16 \\sim 21$ | $32$ | $1000$ | B |\n| $22 \\sim 25$ | $32$ | $1000$ | None |\n\nSpecial Constraint A: No `R` exists in any operation sequence. \nSpecial Constraint B: Each operation sequence contains at most $15$ occurrences of `R`. \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3847, "prompt": "### Problem Description\n\n**For a sequence, the mode is defined as the number appearing strictly more than half the times in the sequence. Note that this definition differs from the conventional definition; for this problem, please adhere to the definition provided in the problem statement.**\n\nInitially, there are $n$ sequences of positive integers with varying lengths, numbered $1 \\sim n$. These initial sequences may be empty. The $n$ sequences are considered to exist, while other numbered sequences are considered nonexistent.\n\nThere are $q$ operations, which can be of the following types:\n\n- $1 \\ x \\ y$: Append the number $y$ to the end of sequence $x$. It is guaranteed that sequence $x$ exists, and $1 \\leq x, y \\leq n + q$.\n- $2 \\ x$: Remove the number at the end of sequence $x$. It is guaranteed that sequence $x$ exists, is non-empty, and $1 \\leq x \\leq n + q$.\n- $3 \\ m \\ x_1 \\ x_2 \\ x_m$: Concatenate the $x_1, x_2, \\ldots, x_m$ sequences in order to form a new sequence, and query its mode. If there is no number satisfying the aforementioned conditions, return $-1$. It is guaranteed that for any $1 \\leq i \\leq m$, $x_i$ is a sequence that still exists, $1 \\leq x_i \\leq n + q$, and the concatenated sequence is non-empty. **Note: $x_1, \\ldots, x_m$ are not guaranteed to be distinct, and the concatenation operation during queries will not affect subsequent operations.**\n- $4 \\ x_1 \\ x_2 \\ x_3$: Create a new sequence numbered $x_3$, which is formed by appending the numbers of sequence $x_2$ to the end of sequence $x_1$, then delete the sequences corresponding to $x_1$ and $x_2$. At this point, sequence $x_3$ is considered to exist, while sequences $x_1$ and $x_2$ are considered nonexistent and will no longer be used in subsequent operations. It is guaranteed that $1 \\leq x_1, x_2, x_3 \\leq n + q$, $x_1 \\neq x_2$, sequences $x_1, x_2$ exist before the operation, and no sequence has previously used the number $x_3$.\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $q$, representing the number of sequences and the number of operations, respectively. It is guaranteed that $n \\leq 5 \\times {10}^5$ and $q \\leq 5 \\times {10}^5$.\n\nThe following $n$ lines describe the initial sequences. The $i$-th line starts with a non-negative integer $l_i$, representing the initial number of elements in sequence $i$. This is followed by $l_i$ non-negative integers $a_{i,j}$, representing the numbers in sequence $i$ in order. Let $C_l = \\sum l_i$ represent the sum of the input sequence lengths. It is guaranteed that $C_l \\leq 5 \\times {10}^5$ and $a_{i,j} \\leq n + q$.\n\nThe following $q$ lines describe the operations, each consisting of several positive integers as specified in the problem description.\n\nLet $C_m = \\sum m$ represent the total number of sequences involved in all operations of type $3$. It is guaranteed that $C_m \\leq 5 \\times {10}^5$.\n\n### Output Format\n\nFor each query, output a single integer representing the result.\n\n**\u3010Sample Explanation \\#1\u3011**\n\nThe first query asks for the mode of sequence $1$. Since sequence $1$ contains two $1$s, which exceeds half of the sequence's length, the mode is $1$.\n\nThe second query asks for the mode of sequence $2$. Since sequence $2$ only contains $3$, the mode is $3$.\n\nThe third query asks for the mode of sequence $3$. At this point, sequence $3$ is $(3, 3, 3, 1, 1, 2)$. There is no number that appears more than $3$ times, so the output is $-1$.\n\n----\n\n**\u3010Sample Explanation \\#2\u3011**\n\nThe first query joins sequences $1, 2, 3, 4$ and asks for the mode. The concatenated sequence is $(1, 2, 3, 4)$, where no number appears more than half the length, so the output is $-1$.\n\nThe fourth query joins sequences $1, 2, 3, 4$ and asks for the mode. The concatenated sequence is $(1, 2, 2, 4, 4, 4, 4)$, where the mode is $4$.\n\n----\n\n**\u3010Sample \\#3\u3011**\n\nSee the `major/major3.in` and `major/major3.ans` files provided as attachments.\n\nThis sample satisfies the constraints for test cases $1 \\sim 3$.\n\n----\n\n**\u3010Sample \\#4\u3011**\n\nSee the `major/major4.in` and `major/major4.ans` files provided as attachments.\n\nThis sample satisfies the constraints for test cases $11 \\sim 12$.\n\n----\n\n### Constraints\n\nFor all test data, it is guaranteed that $1 \\leq n, q, C_m, C_l \\leq 5 \\times {10}^5$.\n\n| $n, q$ | $C_m, C_l$ | Test Case Range | Special Property A | Special Property B | Special Property C |\n|:-:|:-:|:-:|:-:|:-:|:-:|\n| $\\leq 300$ | $\\leq 300$ | $1 \\sim 3$ | No | No | Yes |\n| $\\leq 4000$ | $\\leq 4000$ | $4 \\sim 7$ | No | No | Yes |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $8$ | Yes | Yes | Yes |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $9$ | Yes | No | No |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $10$ | No | Yes | No |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $11 \\sim 12$ | No | No | Yes |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $13$ | No | No | No |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $14$ | Yes | Yes | Yes |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $15$ | Yes | No | No |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $16$ | No | Yes | No |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $17 \\sim 18$ | No | No | Yes |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $19 \\sim 20$ | No | No | No |\n\nSpecial Property A: Ensures $n = 1$ and no operations of type $4$. \nSpecial Property B: Ensures that at any time, any sequence only contains the numbers $1$ and $2$. \nSpecial Property C: Ensures no operations of type $2$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2719, "prompt": "### Problem Description\n\nRecently, Little S has developed a keen interest in bubble sort. To simplify the problem, Little S is only studying the bubble sort of **permutations of $1$ to $n$**.\n\nBelow is the algorithm description of bubble sort:\n\n```plain\nInput: A permutation p[1...n] of length n\nOutput: The sorted result of p\nfor i = 1 to n do\n for j = 1 to n - 1 do\n if(p[j] > p[j + 1])\n Swap the values of p[j] and p[j + 1]\n```\n\nThe number of swaps in bubble sort is defined as the number of times the swapping process is executed. It can be proven that a lower bound of the number of swaps is $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$, where $p_i$ is the number in the $i$-th position of permutation $p$. If you are interested in the proof, refer to the hints.\n\nLittle S began focusing on permutations of length $n$ satisfying the condition that the number of swaps is equal to $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$. (For convenience, we'll call all such permutations \"Good\" permutations in the following text.) He further wondered how plentiful are such permutations and whether they are densely distributed.\n\nLittle S wants to calculate, for a given permutation $q$ of length $n$, the number of \"Good\" permutations that are lexicographically greater than $q$. Since he doesn't know how to do this, he seeks your help. Considering that the answer may be very large, you only need to output the result modulo $998244353$.\n\n### Input Format\n\nThe input consists of multiple test cases. \n\nThe first line contains a positive integer $T$, representing the number of test cases.\n\nFor each test case:\n- The first line contains a positive integer $n$, where $n \\leq 6 \\times 10^5$.\n- The second line consists of $n$ positive integers corresponding to $q_i$, which is a permutation of $1$ to $n$, as described in the problem.\n\n### Output Format\n\nThe output contains $T$ lines, one integer per line.\n\nFor each test case, output an integer representing the number of \"Good\" permutations, lexicographically greater than $q$, modulo $998244353$.\n\n### Additional Samples\n\nAdditional samples can be downloaded from the supplementary files.\n\n#### Sample 3\n\nSee the supplementary files `inverse3.in` and `inverse3.ans`.\n\n### Explanation for Sample 1\n\nAmong the permutations lexicographically greater than $1 \\ 3 \\ 2$, all of them except $3 \\ 2 \\ 1$ are \"Good\" permutations. Therefore, the answer is $3$.\n\n### Constraints\n\nBelow is the explanation of input sizes for each test point:\n\nFor all the data, it is guaranteed that $T = 5$ (the sample may not satisfy this).\n\nLet $n_\\mathrm{max}$ denote the maximum value of $n$ among all test cases, and $\\sum n$ denote the sum of all $n$s across test cases.\n\n| Test Point | $n_\\mathrm{max}$ | $\\sum n \\leq$ | Special Property |\n|:-:|:-:|:-:|:-:|\n| 1 | $8$ | $5 \\ n_\\mathrm{max}$ | None |\n| 2 | $9$ | $5 \\ n_\\mathrm{max}$ | None |\n| 3 | $10$ | $5 \\ n_\\mathrm{max}$ | None |\n| 4 | $12$ | $5 \\ n_\\mathrm{max}$ | None |\n| 5 | $13$ | $5 \\ n_\\mathrm{max}$ | None |\n| 6 | $14$ | $5 \\ n_\\mathrm{max}$ | None |\n| 7 | $16$ | $5 \\ n_\\mathrm{max}$ | None |\n| 8 | $16$ | $5 \\ n_\\mathrm{max}$ | None |\n| 9 | $17$ | $5 \\ n_\\mathrm{max}$ | None |\n| 10 | $18$ | $5 \\ n_\\mathrm{max}$ | None |\n| 11 | $18$ | $5 \\ n_\\mathrm{max}$ | None |\n| 12 | $122$ | $700$ | $\\forall i \\enspace q_i = i$ |\n| 13 | $144$ | $700$ | None |\n| 14 | $166$ | $700$ | None |\n| 15 | $200$ | $700$ | None |\n| 16 | $233$ | $700$ | None |\n| 17 | $777$ | $4000$ | $\\forall i \\enspace q_i = i$ |\n| 18 | $888$ | $4000$ | None |\n| 19 | $933$ | $4000$ | None |\n| 20 | $1000$ | $4000$ | None |\n| 21 | $266666$ | $2000000$ | $\\forall i \\enspace q_i = i$ |\n| 22 | $333333$ | $2000000$ | None |\n| 23 | $444444$ | $2000000$ | None |\n| 24 | $555555$ | $2000000$ | None |\n| 25 | $600000$ | $2000000$ | None |\n\n### Hints\n\nHere is a proof that the lower bound for the number of swaps is $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$.\n\nThe essence of sorting is moving numbers, so the total number of swaps should be describable in terms of the total moving distance of numbers. For the $i$-th position, suppose the number in this position in the initial permutation is $p_i$. Then we need to move this number to the $p_i$-th position, and the moving distance is $\\lvert i - p_i \\rvert$. Thus, the total moving distance is $\\sum_{i=1}^n \\lvert i - p_i \\rvert$. Since bubble sort swaps two adjacent numbers in each operation, each swap can reduce the total moving distance by at most $2$. Therefore, $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$ is a lower bound for the number of swaps in bubble sort.\n\nNote that not all permutations achieve this lower bound. For example, when $n = 3$, consider the permutation $3 \\ 2 \\ 1$. The number of swaps required in bubble sort is $3$, but $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$ is only $2$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3158, "prompt": "### Problem Description\n\nGiven two sequences of positive integers $\\{a_i\\}$ and $\\{b_i\\}$, both of length $n$ with indices ranging from $1$ to $n$, you are required to choose **exactly** $K$ indices from each sequence. The goal is to ensure that **at least** $L$ indices are selected from both sequences (i.e., the same indices for both sequences) while maximizing the total sum of the elements corresponding to the selected indices.\n\nFormally, you need to determine two subsequences $\\{c_i\\}$ and $\\{d_i\\}$ of length $K$, subject to the following constraints:\n\n$$\n1 \\leq c_1 < c_2 < \\ldots < c_K \\leq n, \\quad 1 \\leq d_1 < d_2 < \\ldots < d_K \\leq n,\n$$\n\nand\n\n$$\n\\Big| \\{c_1, c_2, \\ldots, c_K\\} \\cap \\{d_1, d_2, \\ldots, d_K\\} \\Big| \\geq L,\n$$\n\nsuch that the following sum is maximized:\n\n$$\n\\sum_{i=1}^K a_{c_i} + \\sum_{i=1}^K b_{d_i}.\n$$\n\n### Input Format\n\nRead the input from a file named `sequence.in`.\n\n**The input file contains multiple test cases.**\n\n- The first line contains a positive integer $T$, the number of test cases.\n- For each test case, three lines are provided:\n 1. The first line contains three integers $n$, $K$, and $L$, which are described in the problem statement.\n 2. The second line contains $n$ integers, specifying the sequence $\\{a_i\\}$.\n 3. The third line contains $n$ integers, specifying the sequence $\\{b_i\\}$.\n\n### Output Format\n\nWrite the output to a file named `sequence.out`.\n\nFor each test case, output a single line containing an integer: the maximum possible total sum.\n\n### Example\n\n**Input:**\n\n```\n2\n5 2 1\n1 2 3 4 5\n5 4 3 2 1\n6 3 2\n10 20 30 40 50 60\n60 50 40 30 20 10\n```\n\n**Output:**\n\n```\n16\n210\n```\n\n### Explanation of Example\n\n- For the first test case, choose $\\{c_i\\} = \\{4, 5\\}$ from $\\{a_i\\}$ and $\\{d_i\\} = \\{3, 4\\}$ from $\\{b_i\\}$, ensuring at least one overlapping index (in this case, index $4$). The total sum is $4 + 5 + 3 + 4 = 16$.\n- For the second test case, choose $\\{c_i\\} = \\{4, 5, 6\\}$ from $\\{a_i\\}$ and $\\{d_i\\} = \\{1, 2, 3\\}$ from $\\{b_i\\}$, ensuring at least two overlapping indices. The total sum is $40 + 50 + 60 + 60 + 50 + 40 = 210$.\n\n### Constraints and Hints\n\nFor all test points:\n\n- $T \\leq 10$,\n- $1 \\leq \\sum n \\leq 10^6$,\n- $1 \\leq L \\leq K \\leq n \\leq 2 \\times 10^5$,\n- $1 \\leq a_i, b_i \\leq 10^9$.\n\nSpecific constraints for individual test points:\n\n| Test Point ID | $n \\leq$ | $\\sum n \\leq$ |\n|---------------|----------------|-------------------|\n| $1 \\sim 3$ | $10$ | $3 \\times 10^5$ |\n| $4, 5$ | $18$ | $3 \\times 10^5$ |\n| $6, 7$ | $30$ | $3 \\times 10^5$ |\n| $8 \\sim 10$ | $150$ | $3 \\times 10^5$ |\n| $11 \\sim 16$ | $2 \\times 10^3$| $3 \\times 10^5$ |\n| $17 \\sim 21$ | $2 \\times 10^5$| $3 \\times 10^5$ |\n| $22 \\sim 25$ | $2 \\times 10^5$| $10^6$ |\n\nExample input and output files can be found in the contestant's directory at `sequence/sequence2.in`, `sequence/sequence2.ans`, `sequence/sequence3.in`, and `sequence/sequence3.ans`.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2721, "prompt": "### Problem Description\n\nD recently discovered an online mini-game. The rules are as follows:\n\n- The objective of the game is to defeat $n$ dragons in sequential order numbered $1 \\rightarrow n$. Each dragon has an initial health value $a_i$. Additionally, each dragon has a regeneration ability: when activated, the dragon\u2019s health increases by $p_i$ each time, continuing until its health is non-negative. A dragon only dies if its \"final\" health value is **exactly zero** after attacks and regeneration.\n- At the start of the game, the player has $m$ swords with known attack values. When facing a dragon, the player can choose only one sword to use. Once the dragon is slain, the sword used is lost; however, the player is awarded a new sword as a reward.\n\nThough D quickly became bored of this game, she learned that the fastest clearing player could qualify to compete in ION2018. As a result, D wants to develop a simple robot to clear the game. The robot operates using the following methodology:\n\n- When facing a dragon, the robot chooses the sword with the **highest attack power** among those with attack power less than or equal to the dragon's initial health. If no such sword exists, the robot chooses the **lowest attack power** sword.\n- Against each dragon, the robot will attack it exactly $x$ times using the selected sword, reducing the dragon's health by $x \\times ATK$, where $ATK$ is the attack power of the sword.\n- Subsequently, the dragon starts regenerating health using its regeneration ability, increasing its health by $p_i$ after each regeneration. If the dragon\u2019s health becomes zero either before the first regeneration step or after some subsequent regeneration step, the dragon is defeated, and the player advances to the next level.\n\nClearly, the number of attacks performed by the robot is the crucial factor in determining how quickly the game is cleared. D now has detailed information about the properties of all dragons. She wants to test your intuition: can you determine the minimum number of attacks $x$ required by the robot to clear the game? \n\nIf clearing the game is impossible regardless of the setting for $x$, output $-1$.\n\n---\n\n### Input Format\n\nThe first line contains an integer $T$, representing the number of test cases.\n\nFollowing are $T$ test cases, each consisting of five lines:\n\n- The first line of each test case contains two integers, $n$ and $m$, representing the number of dragons and the initial number of swords.\n- The second line contains $n$ positive integers, where the $i$-th number $a_i$ represents the initial health of the $i$-th dragon.\n- The third line contains $n$ positive integers, where the $i$-th number $p_i$ represents the regeneration ability of the $i$-th dragon.\n- The fourth line contains $n$ positive integers, where the $i$-th number denotes the attack power of the sword rewarded for defeating the $i$-th dragon.\n- The fifth line contains $m$ positive integers, representing the attack power of the initial $m$ swords.\n\n---\n\n### Output Format\n\nOutput consists of $T$ lines.\n\nThe $i$-th line contains a single integer, representing the minimum number of attacks $x$ required for the robot to clear the game for the $i$-th test case. If clearing the game is impossible, output $-1$.\n\n---\n\n### Additional Examples\n\nDownload additional examples from the provided files.\n\n---\n\n### Example 2\n\nRefer to the files `dragon2.in` and `dragon2.ans`.\n\n---\n\n### Explanation of Example 1\n\nFor the first test case:\n\n- The robot starts with swords of attack power $\\{1,9,10\\}$. For the first dragon with health $3$, the robot chooses the sword with attack power $1$, and attacks $59$ times, dealing $59$ damage. The dragon\u2019s health becomes $-56$. It regenerates $14$ times until its health is precisely $0$, then dies.\n \n- The sword with attack power $1$ is lost. The robot receives a sword with attack power $7$. The current swords have attack power $\\{7,9,10\\}$. For the second dragon with health $5$, the robot chooses the sword with attack power $7$, and attacks $59$ times, dealing $413$ damage. The dragon\u2019s health becomes $-408$. It regenerates $68$ times until its health is precisely $0$, then dies.\n\n- Now the robot's swords have attack power $\\{3,9,10\\}$. For the third dragon with health $7$, the robot chooses the sword with attack power $3$, and attacks $59$ times, dealing $177$ damage. The dragon\u2019s health becomes $-170$. It regenerates $17$ times until its health is precisely $0$, then dies.\n\n- There is no faster way to clear the level with fewer than $59$ attacks per dragon. Thus, the answer is $59$.\n\nFor the second test case:\n\nIt is impossible to kill the first dragon and the second dragon simultaneously. Thus, the output is $-1$.\n\n---\n\n### Subtasks\n\n| Test Case ID | $n$ | $m$ | $p_i$ | $a_i$ | Attack Power | Other Constraints |\n|-|-|-|-|-|-|-|\n| 1 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $=1$ | None |\n| 2 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $=1$ | None |\n| 3 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $\\leq 10^5$ | None |\n| 4 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $\\leq 10^5$ | None |\n| 5 | $\\leq 10^3$ | $\\leq 10^3$ | $\\leq 10^5$ | $\\leq 10^5$ | $\\leq 10^5$ | Property 1, Property 2 |\n| 6 | $\\leq 10^3$ | $\\leq 10^3$ | $\\leq 10^5$ | $\\leq 10^5$ | $\\leq 10^5$ | Property 1, Property 2 |\n| 7 | $\\leq 10^3$ | $\\leq 10^3$ | $\\leq 10^5$ | $\\leq 10^5$ | $\\leq 10^5$ | Property 1, Property 2 |\n| 8 | $=1$ | $=1$ | $\\leq 10^8$ | $\\leq 10^8$ | $\\leq 10^6$ | Property 1 |\n| ... | ... | ... | ... | ... | ... | ... |\n\n**Property 1**: For any $i$, $a_i \\leq p_i$. \n**Property 2**: $\\operatorname{lcm}(p_i) \\leq 10^6$, i.e., the **least common multiple** of all $p_i$ is no greater than $10^6$.\n\nFor all test cases, $T \\leq 5$, all sword attack powers $\\leq 10^6$, and the least common multiple of all $p_i \\leq 10^{12}$. \n\nIt is guaranteed that $T$, $n$, and $m$ are positive integers.\n\n---\n\n### Notes\n\nIntermediate results may become very large. Ensure that your variable types can adequately store intermediate values.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2306, "prompt": "### Problem Description\n\nLittle N is the manager of a vegetable warehouse and is responsible for designing vegetable sales plans. \nIn the vegetable warehouse, there are a total of $n$ types of vegetables. Little N needs to consider various factors based on the characteristics of each vegetable to design an optimal sales plan to maximize revenue. \n\nWhen calculating the revenue from selling vegetables, selling one unit of the $i$-th type of vegetable will bring in a revenue of $a_i$. \nParticularly, since policies encourage diversified sales, the first unit of the $i$-th type of vegetable sold will also yield an additional revenue of $s_i$. \n\nAt the beginning of the operation, the initial inventory of the $i$-th type of vegetable is $c_i$ units. \nHowever, vegetables have a very limited freshness period. Once spoiled, they can no longer be sold. Fortunately, Little N has already calculated the spoilage time for every unit of vegetable: for the $i$-th type of vegetable, there is a freshness value $x_i$, meaning $x_i$ units of the vegetable will spoil at the end of every day until all units are spoiled. (Note: The spoilage time for each unit of vegetable is fixed and does not change with sales.) \n\nFormally: for all positive integers $d$ satisfying $d \\times x_i \\leq c_i$, $x_i$ units of the $i$-th type of vegetable will spoil at the end of the $d$-th day. \nParticularly, if $(d-1) \\times x_i \\leq c_i < d \\times x_i$, then $c_i - (d-1) \\times x_i$ units of the vegetable will spoil at the end of the $d$-th day. \nNote that if $x_i = 0$, it means this type of vegetable will not spoil. \n\nIn addition, the total quantity of vegetables sold each day is also limited and cannot exceed $m$ units. \n\nNow, Little N has $k$ queries and wants your help to calculate the results. Each query is in the form of a given $p_j$, asking: if the sales last for $p_j$ days, what is the maximum revenue that can be obtained?\n\n---\n\n### Input Format\n\nThe first line contains three positive integers $n, m, k$, representing the number of vegetable types, the daily maximum sales limit, and the number of queries, respectively. \nThe next $n$ lines each contain four non-negative integers describing the characteristics of one type of vegetable: $a_i, s_i, c_i, x_i$, as described above. \nThe next $k$ lines each contain a non-negative integer $p_j$, as described above.\n\n---\n\n### Output Format\n\nOutput $k$ lines, each containing a single integer. The $i$-th line represents the answer to the $i$-th query.\n\n---\n\n### Sample\n\n```\nInput\n2 10 1\n5 10 100 5\n4 0 50 0\n1\n\nOutput\n65\n```\n\n---\n\n### Data Range and Constraints\n\n| Test Case ID | $n$ | $m$ | $p_j$ | Characteristic $1$ | Characteristic $2$ |\n| :----------: | :--------: | :------: | :--------: | :-----------------: | :----------------------: |\n| $1$ | $\\leq 2$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $2$ | $\\leq 3$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $3$ | $\\leq 4$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $4$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 2$ | None | None |\n| $5$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 3$ | None | None |\n| $6$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 4$ | None | None |\n| $7$ | $\\leq 4$ | $\\leq 1$ | $\\leq 4$ | None | None |\n| $8$ | $\\leq 6$ | $\\leq 2$ | $\\leq 6$ | None | None |\n| $9$ | $\\leq 8$ | $\\leq 1$ | $\\leq 8$ | None | None |\n| $10$ | $\\leq 10$ | $\\leq 2$ | $\\leq 10$ | None | None |\n| $11$ | $\\leq 20$ | $\\leq 3$ | $\\leq 20$ | None | None |\n| $12$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | Present | None |\n| $13$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | None | Present |\n| $14$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | None | None |\n| $15$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | None | None |\n| $16$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | Present | Present |\n| $17$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | Present | None |\n| $18$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | None | Present |\n| $19$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $20$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $21$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | Present | Present |\n| $22$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | Present | None |\n| $23$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | None | Present |\n| $24$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | None | None |\n| $25$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | None | None |\n\n- Characteristic $1$: All $s_i$ are $0$. \n- Characteristic $2$: All $x_i$ are $0$. \n\nFor all test cases, it is guaranteed that the $k$ queries $p_j$ are distinct, and $0 < a_i, c_i \\leq 10^9$, $0 \\leq s_i, x_i \\leq 10^9$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3982, "prompt": "### Problem Description\n\nIn recent years, Country A has experienced rapid commercial development. However, its road infrastructure has not kept pace, significantly constraining trade and travel. The government has been working tirelessly to address this issue.\n\nSpecifically, Country A consists of $2^n - 1$ cities, where City $1$ is the capital. For every non-capital city $i$, there is a **one-way** road from City $i$ to City $\\lfloor \\frac{i}{2} \\rfloor$. For convenience, these roads are referred to as \"Type-1 Roads,\" and City $\\lfloor \\frac{i}{2} \\rfloor$ is called the \"superior city\" of City $i$.\n\nIn addition, there are $m$ other **one-way** roads. The $i$-th of these roads connects City $u_i$ to City $v_i$ and possesses a unique property: starting from City $v_i$ and continuously following Type-1 Roads toward superior cities will eventually lead to City $u_i$. Such roads are referred to as \"Type-2 Roads.\"\n\nEach road has an associated length. Consequently, for any two cities $x$ and $y$ in Country A, we can compute the minimum total length of roads required to travel from City $x$ to City $y$, denoted as $dist(x, y)$. However, due to the poor state of road infrastructure, it may not be possible to travel from City $x$ to City $y$ at all. In such cases, $dist(x, y)$ is defined to be $0$. Additionally, the distance from a city to itself is $0$, i.e., $dist(x, x) = 0$.\n\nThe government wishes to calculate the sum of all $dist(x,y)$ values to better evaluate the convenience of trade and travel. However, since there are too many cities, listing all such values is infeasible. Instead, they want to compute the sum $\\sum_{x=1}^{2^n-1}\\sum_{y=1}^{2^n-1} dist(x, y)$ and have asked for your help in solving this task.\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $m$.\n\nThe second line of input contains $2^n - 2$ positive integers. The $i$-th integer $a_i$ represents the length of the \"Type-1 Road\" from City $i+1$ to City $\\lfloor \\frac{i+1}{2} \\rfloor$.\n\nThe next $m$ lines each contain three positive integers $u, v, w$, describing a \"Type-2 Road\" from City $u$ to City $v$ with a length of $w$.\n\n### Output Format\n\nOutput one line containing a single positive integer, representing the answer. Since the result may be very large, output the result modulo $998244353$.\n\n**\u3010Constraints\u3011**\n\nAll test data satisfy the following constraints: \n$2 \\leq n \\leq 18$, $1 \\leq m \\leq 2^n$, $1 \\leq u, v \\leq 2^n - 1$, $1 \\leq a_i, w \\leq 10^9$.\n\n| Test Case ID | $n$ | $m$ | Special Property? |\n| :---: | :---: | :---: | :---: |\n| $1\\sim 2$ | $=8$ | $\\leq 256$ | No |\n| $3\\sim 4$ | $=9$ | $\\leq 512$ | No |\n| $5\\sim 8$ | $=12$ | $\\leq 4,096$ | No |\n| $9$ | $=16$ | $\\leq 10$ | No |\n| $10$ | $=16$ | $\\leq 50$ | No |\n| $11$ | $=16$ | $\\leq 100$ | No |\n| $12$ | $=16$ | $\\leq 65,536$ | Yes |\n| $13\\sim 15$ | $=16$ | $\\leq 65,536$ | No |\n| $16\\sim 17$ | $=18$ | $\\leq 262,144$ | Yes |\n| $18\\sim 20$ | $=18$ | $\\leq 262,144$ | No |\n\nSpecial Property: If present, all \u201cType-2 Roads\u201d start from the capital (City $1$). \n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 2315, "prompt": "### Problem Description\n\nXiao Ming is learning a new programming language called A++. Having just mastered loop statements, he excitedly wrote many programs and calculated their time complexities himself. However, his programming teacher is unwilling to check each of Xiao Ming\u2019s programs one by one. This is where you step in! Please write a program to determine whether the time complexity given by Xiao Ming for each of his programs is correct.\n\nIn the A++ language, the loop structure is as follows:\n\n```plain\nF i x y\n Loop Body\nE\n```\n\nHere, `F i x y` represents the creation of a new variable $i$ (note that variable $i$ cannot have the same name as any currently existing variable that has not been destroyed) initialized to $x$. Then, it compares $i$ with $y$. If $i$ is less than or equal to $y$, the loop starts; otherwise, it does not. After the end of each loop iteration, $i$ will increment by 1. The loop terminates when $i$ exceeds $y$.\n\n$x$ and $y$ can be either positive integers ($x$ and $y$ have no predetermined size relationship) or the variable $n$. The variable $n$ represents the data size and must be retained in complexity calculations without being treated as a constant. This variable is significantly larger than $100$.\n\n`E` marks the end of the loop body. When the loop body ends, the variables created by this loop are destroyed.\n\n**Note**: To simplify notation in the problem, we use capital letter $O$ to represent the commonly understood concept of $\\Theta$ in time complexity.\n\n---\n\n### Input Format\n\nThe first line of the input file contains a positive integer $t$, representing the number of programs to analyze $(t \\leq 10)$. For each program, we only extract the `F i x y` and `E` statements to calculate the time complexity. Note that the loop structures may have nested loops.\n\nThe first line of each program contains a positive integer $L$ and a string denoting the program\u2019s time complexity. Complexity is described as `O(1)` for constant complexity, or `O(n^w)` for complexity proportional to $n^w$, where $w$ is a positive integer less than $100$. The input guarantees that only these two forms of complexity (`O(1)` and `O(n^w)`) are present (without quotation marks).\n\nThe next $L$ lines represent the loop structure of the program: either `F i x y` or `E`.\n\n- Lines starting with `F` denote the beginning of a loop, followed by three space-separated tokens `i x y`. Here, $i$ is a lowercase English letter (guaranteed not to be `n`), indicating the newly declared variable name. $x$ and $y$ can be either positive integers (known to be less than $100$) or `n`. \n- **Important Note**: In the 10th test case, there may be instances of variable names being `n`, which contradicts the earlier description.\n- Lines starting with `E` mark the end of the loop body.\n\n---\n\n### Output Format\n\nThe output contains $t$ lines, corresponding to the $t$ programs provided in the input. Each line should output `Yes`, `No`, or `ERR`:\n- If the program\u2019s actual complexity matches the provided complexity, output `Yes`.\n- If the complexity does not match, output `No`.\n- If the program contains a syntax error, output `ERR`. Syntax errors are of two types:\n 1. Mismatched `F` and `E` statements.\n 2. A variable being redefined within a loop while it is already defined but has not yet been destroyed.\n\n**Note**: Even if a syntax error appears inside a loop body that will not execute at runtime, the program is considered to have a compile-time error and should output `ERR`.\n\n---\n\n### Examples\n\n1. The first program has $i$ loop from $1$ to $1$, resulting in constant complexity (`O(1)`).\n2. The second program has $x$ loop from $1$ to $n$, resulting in a complexity of $n$ ($O(n^1)$).\n3. The third program contains an unmatched `F` statement without a corresponding `E`, causing a syntax error.\n4. The fourth program contains a nested loop structure, resulting in $n^2$ complexity (`O(n^2)`).\n5. The fifth program consists of two independent loops, each with complexity $n$. The overall complexity is $n$ ($O(n^1)`).\n6. The sixth program has a first loop that executes normally, but the second loop terminates immediately (as $n$ is significantly larger than $100$, and $100 > 4`).\n7. The seventh program\u2019s first loop does not execute at all, resulting in constant complexity (`O(1)`).\n8. The eighth program contains a variable `x` in the second loop that redefines a variable already defined in the first loop, resulting in a syntax error (`ERR`).\n\n---\n\n### Constraints and Notes\n\n**Constraints**:\n- For $30\\%$ of the test cases:\n - No syntax errors exist.\n - The first $L/2$ lines of each program will always start with `F`, while the last $L/2$ lines will start with `E`.\n - $L \\leq 10$.\n - If both $x$ and $y$ are integers, it is guaranteed that $x < y$, and only $y$ may be equal to `n`.\n\n- For $50\\%$ of the test cases:\n - No syntax errors exist.\n - $L \\leq 100$.\n - If both $x$ and $y$ are integers, it is guaranteed that $x < y$, and only $y$ may be equal to `n`.\n\n- For $70\\%$ of the test cases:\n - No syntax errors exist.\n - $L \\leq 100$.\n\n- For $100\\%$ of the test cases:\n - $t \\leq 10$, $L \\leq 100`.\n\n---\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2722, "prompt": "### Problem Description\n\nIn recent years, Country C and Country D have been caught in the chaos of war.\n\nRecently, Country C successfully infiltrated a city in Country D. This city can be abstracted as an undirected graph with $n$ nodes and $n-1$ bidirectional edges connecting the nodes, ensuring that any two nodes can reach each other. In other words, this undirected graph is actually a tree.\n\nThrough reconnaissance, the intelligence minister of Country C, GGB, was surprised to find that this seemingly inconspicuous city is the military hub of Country D. Therefore, GGB decided to establish intelligence agencies within the city. After investigation, intelligence expert TAC organized $m$ options to set up these agencies. According to option $i$, intelligence officers would be stationed along all the edges on the shortest path between node $x_i$ and node $y_i$, incurring a cost of $v_i$.\n\nHowever, due to manpower constraints, GGB can implement only two of the $m$ options. Furthermore, TAC pointed out that for better cooperation between these two intelligence agencies, their surveillance areas must **share at least one edge**. To evaluate the performance of an option, GGB and TAC surveyed all the edges and assigned each edge an intelligence value $c_i$, which represents the monetary benefit ($c_i$) derived from gathering intelligence on this edge. Note that intelligence is unique, so an edge being monitored by two agencies will still yield only $c_i$ monetary benefit.\n\nNow, your task is to help GGB select two legal options to implement such that the surveillance areas of the two options share at least one edge, and the **difference between the total benefit and the total cost** is maximized.\n\nNote: This value may be negative, but it is still considered valid. If no such pair of options can be found, output `F`.\n\n---\n\n### Input Format\n\nInput is read from the file `center.in`.\n\nThis problem consists of multiple test cases.\n\nThe first line of the input file contains an integer $T$, representing the number of test cases.\n\nEach test case contains $(n + m + 1)$ lines:\n\n1. The first line contains an integer $n$, representing the number of nodes in the city.\n2. The next $n-1$ lines contain three integers $a_i$, $b_i$, and $c_i$, representing a bidirectional edge connecting node $a_i$ to node $b_i$ with an intelligence value of $c_i$. It is guaranteed that $a_i < b_i$, and $b_i$ values are distinct.\n3. The $(n+1)$-th line contains an integer $m$, representing the number of options provided by TAC for establishing intelligence agencies.\n4. The following $m$ lines contain three integers $x_i$, $y_i$, and $v_i$, representing the $i$-th option for establishing an intelligence agency. According to this option, intelligence officers are stationed on all the edges along the shortest path between nodes $x_i$ and $y_i$, incurring a cost of $v_i$.\n\n---\n\n### Output Format\n\nOutput to the file `center.out`.\n\nThe output file contains $T$ lines.\n\nFor each test case, output a single line: If a legal pair of options exists, output the maximum difference between the total benefit and the total cost. Otherwise, output `F`.\n\n---\n\n### Example\n\nThis example contains two test cases. In both cases, the city structure remains the same, but the intelligence values and agency options differ. The city's graph is as follows:\n\n![](https://i.loli.net/2018/07/20/5b519ef60c198.png)\n\n#### Test Case 1\n\n- In Option 1, the shortest path from node $1$ to node $4$ is $1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4$. \n- In Option 2, the shortest path from node $3$ to node $5$ is $3 \\rightarrow 2 \\rightarrow 1 \\rightarrow 5$. \n\nChoosing these two options incurs a cost of $5 + 8 = 13$. All edges are monitored, yielding a total benefit of $1 + 3 + 2 + 8 = 14$. Thus, the difference between total benefit and total cost is $14 \u2212 13 = 1$.\n\n#### Test Case 2\n\n- In Option 1, the shortest path from node $1$ to node $5$ is $1 \\rightarrow 5$. \n- In Option 2, the shortest path from node $2$ to node $3$ is $2 \\rightarrow 3$. \n\nThere is no shared edge between these two options. Thus, this test case has no legal solution, and the output is `F`.\n\n---\n\nSee the attached files `center2.in` and `center2.ans`. \n\nThis example includes only one test case. For this test case, the optimal solution is to choose Option 2 and Option 3.\n\nThe city's graph is as follows. **Bold** edges represent those being monitored. Red edges are monitored only by Option 2, blue edges are monitored only by Option 3, and purple edges are monitored by both options.\n\n![](https://i.loli.net/2018/07/20/5b51a17325aed.png)\n\n---\n\nSee the attached files `center3.in` and `center3.ans`.\n\nThis example shares the same structure as the fourth test case described below. You can utilize this test case for robust debugging and testing.\n\n---\n\n### Data Ranges and Hints\n\nThe scale and properties of each test case are indicated in the table below:\n\n| Test Point | $n \\le$ | $m \\le$ | $T \\le 50$ | Special Properties |\n| :-: | :-: | :-: | :-: | :-: |\n| 1 | $2$ | $3$ | Guaranteed | None |\n| 2 | $10$ | $30$ | Guaranteed | None |\n| 3 | $200$ | $300$ | Guaranteed | None |\n| 4 | $10^3$ | $2,000$ | Guaranteed | $a_i = b_i - 1$ |\n| 5 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $a_i = b_i - 1$ |\n| 6 | $5 \\times 10^4$ | $3 \\times 10^4$ | Guaranteed | $a_i = b_i - 1$ |\n| 7 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $c_i = 0$ |\n| 8 | $5 \\times 10^4$ | $10^5$ | Guaranteed | $c_i = 0$ |\n| 9 | $5 \\times 10^4$ | $10^5$ | Guaranteed | $c_i = 0$ |\n| 10 | $10^4$ | $n$ | Guaranteed | $S_1$ |\n| 11 | $5 \\times 10^4$ | $n$ | Not Guaranteed | $S_1$ |\n| 12 | $5 \\times 10^4$ | $n$ | Not Guaranteed | $S_1$ |\n| 13 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $S_2$ |\n| 14 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $S_2$ |\n| 15 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | $S_2$ |\n| 16 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | $S_2$ |\n| 17 | $10^4$ | $3 \\times 10^4$ | Guaranteed | None |\n| 18 | $5 \\times 10^4$ | $10^5$ | Guaranteed | None |\n| 19 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | None |\n| 20 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | None |\n\n#### Special Properties:\n1. Property $S_1$: For any $i$ and $j$, it is guaranteed that the smallest indexed node on the shortest path between $x_i$ and $y_i$ differs from the smallest indexed node on the shortest path between $x_j$ and $y_j$.\n2. Property $S_2$: For any $i$, the smallest indexed node on the shortest path between $x_i$ and $y_i$ is guaranteed to be node $1$.\n\n#### Constraints:\nFor all test cases:\n- $1 \\le n \\le 5 \\times 10^4$\n- $0 \\le m \\le 10^5$\n- $0 \\le c_i \\le 10^9$\n- $0 \\le v_i \\le 10^{10} \\times n$\n\nThe sum of all $n$ across all test cases does not exceed $1,000,233$, and the sum of all $m$ does not exceed $2,000,233$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3567, "prompt": "### Problem Description\n\nThe game is played on a rectangular grid-based chessboard of dimensions $n$ rows by $m$ columns. The chess pieces are placed at the grid's intersections. Let the top-left intersection be represented as $(1,1)$ and the bottom-right intersection as $(n,m)$.\n\nThe chess pieces are divided into two colors: black and white. Each player controls one color.\n\nIn addition to color, each chess piece has a level, denoted as $\\mathit{col}_i$ for the color of piece $i$ and $\\mathit{lv}_i$ for its level. Furthermore, the grid lines of the chessboard have $4$ possible states, where the state of the $i$-th grid line is denoted as $\\mathit{opt}_i$.\n\nWhen it is a player's turn, they can select one of their own chess pieces and move it along the grid lines to another intersection, referred to as a \"move\". The formal definition of making a \"move\" involves selecting a sequence of coordinates $(x_0,y_0),(x_1,y_1),\\ldots,(x_k,y_k)$. Here, $k$ is any chosen positive integer, $(x_0,y_0)$ is the initial position of the piece, and $(x_k,y_k)$ is the final destination. The following conditions must be satisfied:\n\n- For all $i = 0,1,\\ldots,k-1$, the coordinates $(x_i,y_i)$ and $(x_{i+1},y_{i+1})$ must be directly connected by a grid line. This means **all moves must follow grid lines**.\n- For all $i \\neq j$, $(x_i,y_i) \\neq (x_j,y_j)$. In other words, the piece cannot pass through the same position more than once, and specifically, $(x_0,y_0) \\neq (x_k,y_k)$. That is, **the piece cannot remain stationary or return to its original position**.\n- For all $i = 1,\\ldots,k-1$, the position $(x_i,y_i)$ must not contain any chess piece. This means **the move cannot skip over any existing chess pieces**.\n- If there is no chess piece at $(x_k,y_k)$, the move is called a normal move. If there is a piece at $(x_k,y_k)$, the move is called a capture. In a capture move, if the moving piece has color $\\mathit{col}_1$ and level $\\mathit{lv}_1$, and the captured piece has color $\\mathit{col}_2$ and level $\\mathit{lv}_2$, the following conditions must hold: $\\mathit{col}_1 \\neq \\mathit{col}_2$ and $\\mathit{lv}_1 \\geq \\mathit{lv}_2$. In other words, **a piece can only capture an opponent's piece, and its level must be greater than or equal to the opponent's level**.\n\nAdditionally, note that a piece cannot continue moving after performing a capture.\n\nThe meanings of the grid line states are as follows:\n\n- If $\\mathit{opt}_i=0$, it means the path is blocked, and the piece cannot move through this grid line.\n- If $\\mathit{opt}_i=1$, it means the grid line is a \"normal road\", and the piece can pass through at most one normal road during a move.\n- If $\\mathit{opt}_i=2$, it means the grid line is a \"straight road\", and the piece can pass through any number of straight roads during a single move. However, the piece must move **strictly either horizontally or vertically without turning**. For example, moving from $(1,1)$ to $(1,2)$ and then to $(1,3)$ along straight roads is allowed, but moving from $(1,1)$ to $(1,2)$ and then to $(2,2)$ is not allowed.\n- If $\\mathit{opt}_i=3$, it means the grid line is an \"open road\", and the piece can pass through any number of open roads during a single move, with turns allowed.\n\nAdditionally, during a single move, **all grid lines along the path must be of the same state**. For instance, moving from $(1,1)$ to $(1,2)$ via a straight road and then to $(1,3)$ via an open road is not allowed.\n\nDetails such as how to determine the winner are not relevant to this problem and are thus omitted.\n\nAfter developing this board game, Little Z and Little C decided to improve their skills through a training strategy. Initially, the board is empty. Little C places a chess piece onto an empty intersection on the board at each step. Little Z needs to quickly calculate how many positions on the board can be reached if the newly placed chess piece is selected to make a move. Note: This is a mental training activity, and they do not actually move the pieces.\n\nHowever, Little Z found this calculation too difficult to perform, so he came to you for help.\n\n### Input Format\n\nEach test point consists of multiple data sets.\n\nThe first line contains a positive integer $T$, representing the number of data sets.\n\nFor each data set:\n\n- The first line contains three positive integers $n, m, q$, the number of rows, columns, and game rounds, respectively.\n- The next $n$ lines each contain a string of length $m - 1$, where each character is one of $\\texttt{0}$, $\\texttt{1}$, $\\texttt{2}$, or $\\texttt{3}$. The $j$-th character in the $i$-th line represents the state of the grid line connecting intersection $(i, j)$ to $(i, j+1)$. \n- The next $n - 1$ lines each contain a string of length $m$, where each character is one of $\\texttt{0}$, $\\texttt{1}$, $\\texttt{2}$, or $\\texttt{3}$. The $j$-th character in the $i$-th line represents the state of the grid line connecting intersection $(i, j)$ to $(i+1, j)$.\n- The next $q$ lines each contain $4$ non-negative integers $\\mathit{col}_i, \\mathit{lv}_i, x_i, y_i$, indicating that in the $i$-th round, a chess piece with color $\\mathit{col}_i$ and level $\\mathit{lv}_i$ is placed at the intersection $(x_i, y_i)$. Here, $\\mathit{col}_i = 0$ represents a black piece and $\\mathit{col}_i = 1$ represents a white piece. It is guaranteed that there was no chess piece at $(x_i, y_i)$ beforehand.\n\n### Output Format\n\nFor each data set, output $q$ lines. Each line contains a non-negative integer, representing the number of intersections that the $i$-th chess piece can reach after being placed.\n\n**Sample Explanation #1**\n\nAfter placing piece $1$, it can move to positions $(2, 1),(2, 2),(3, 2),(3, 3)$.\n\nAfter placing piece $2$, it can move to positions $(2, 2),(2, 3),(3, 1)$.\n\nAfter placing piece $3$, it can move to positions $(1, 1),(1, 3),(2, 2)$.\n\nAfter placing piece $4$, it can move to positions $(2, 2),(3, 1),(3, 3)$.\n\nAfter placing piece $5$, it can move to positions $(2, 3),(3, 2)$.\n\n### Constraints\n\n| Test Case | $n \\times m \\le$ | $q \\le$ | Special Notes |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 2$ | $100$ | $50$ | None |\n| $3 \\sim 6$ | $5000$ | $2000$ | None |\n| $7 \\sim 8$ | $2 \\times {10}^5$ | ${10}^5$ | No \"straight roads\" or \"open roads\" |\n| $9 \\sim 11$ | $2 \\times {10}^5$ | ${10}^5$ | No \"open roads\" |\n| $12 \\sim 14$ | $2 \\times {10}^5$ | ${10}^5$ | No \"straight roads\" |\n| $15 \\sim 16$ | $2 \\times {10}^5$ | ${10}^5$ | $\\mathit{lv}_i = i$ |\n| $17 \\sim 18$ | $2 \\times {10}^5$ | ${10}^5$ | $\\mathit{lv}_i = q - i + 1$ |\n| $19 \\sim 21$ | $2 \\times {10}^5$ | $2000$ | $n, m \\le 1000$ |\n| $22 \\sim 25$ | $2 \\times {10}^5$ | ${10}^5$ | None |\n\nFor $100\\%$ of the data, $1 \\le T \\le 5$, $2 \\le n, m \\le {10}^5$, $4 \\le n \\times m \\le 2 \\times {10}^5$, $1 \\le q \\le \\min \\{ {10}^5, n \\times m \\}$, $1 \\le \\mathit{lv}_i \\le q$, $1 \\le x_i \\le n$, $1 \\le y_i \\le m$, and $\\mathit{col}_i \\in \\{ 0, 1 \\}$.\n\nNote: Due to the large input and output size of this problem, it is recommended to use fast input and output methods.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3535, "prompt": "### Problem Description\nXiao Z is self-learning knowledge about quantum computers and has recently been studying the quantum communication chapter. During this study, he encountered an interesting problem. In this problem, Alice and Bob are performing quantum communication, and their communication language is a dictionary $S$ of size $n$. Each word $s_i$ ($1 \\leq i \\leq n$) in the dictionary can be represented as a $\\boldsymbol{256}$-bit binary string composed of $\\boldsymbol{0}$ and $\\boldsymbol{1}$. In this problem, $s_i$ can be generated by calling the function `gen`, which is implemented in `gen.cpp` that you can access in the problem's directory. The function takes parameters `n`, `a1`, and `a2`, which will be provided in the input data.\n\nAlice and Bob will conduct $m$ rounds of communication, and in each communication, Alice transmits **exactly one** word from the dictionary to Bob. However, the communication channel they use is not reliable due to noise interference. Specifically, in the $i$-th transmission, let's denote the original word that Alice transmits as $x_i$. This $256$-bit binary string may be affected by noise and could have at **most** $\\boldsymbol{k_i}$ bit flips. In other terms, let $y_i$ represent the $256$-bit binary string received by Bob after transmission. Compared to $x_i$, $y_i$ may differ by at most $k_i$ bits, and $y_i$ may not necessarily belong to the dictionary $S$.\n\nAt the same time, Bob learns that an adversary, Eve, has also infiltrated the communication channel and is attempting to disrupt their transmission. Eve's interference strategy involves altering the $256$-bit binary string received by Bob into **any arbitrary** $256$-bit binary string, which may not necessarily belong to dictionary $S$. Eve is cunning and **does not necessarily** interfere with every communication.\n\nNow, Bob seeks your help. For every communication round, based on the $256$-bit binary string Bob ultimately receives and the noise tolerance threshold $k_i$ ($0 \\leq k_i \\leq 15$), you need to determine whether it is **possible** that this communication was not interfered with by Eve. In other words, you need to check if it is possible that the received $256$-bit string can be transformed into a dictionary word with at most $k_i$ bit flips. If it is possible that Eve did not interfere, output $1$; otherwise, output $0$. Bob has full trust in your ability, so you need to provide answers **online** as described in the input format.\n\nTo reduce input processing time, the binary string received by Bob will be given as a $\\boldsymbol{64}$-character hexadecimal string ($16$-base string). The hexadecimal string consists of digits $\\texttt{0} \\sim \\texttt{9}$ and uppercase letters $\\texttt{A} \\sim \\texttt{F}$, where characters $\\texttt{A} \\sim \\texttt{F}$ correspond to values $10 \\sim 15$, respectively.\n\nA hexadecimal string can be converted character by character into a binary string. For example, `5` corresponds to `0101`, `A` corresponds to `1010`, and `C` corresponds to `1100`.\n\n### Input Format\nThe first line of input contains four non-negative integers: $n$, $m$, $a_1$, and $a_2$, which represent the size of the dictionary, the number of communication rounds, and the initial values of the parameters `a1` and `a2` used in the `gen` function.\n\nParticipants need to call the `gen` function mentioned in the problem description to generate the dictionary. The function implementation can be copied and used directly from the `gen.cpp` file. In the program, the boolean array `s[N+1][256]` will store all the dictionary words.\n\nThe next $m$ lines each contain a hexadecimal string of length $64$ and a non-negative integer $k_i$, representing the $256$-bit binary string Bob finally received in the $i$-th communication and the noise tolerance threshold.\n\nTo ensure **online querying**, participants must first convert the $64$-character hexadecimal string to a $256$-bit binary string, and then XOR ($\\texttt{exclusive-or}$) each bit with ${\\mathit{lastans}}$. Here, ${\\mathit{lastans}} \\in \\{0, 1\\}$ is the answer to the previous query, with an initial value of ${\\mathit{lastans}} = 0$ before the first query.\n\n**Note:** When using `scanf` or `printf` to handle `unsigned long long` types in C/C++, the format specifier is `llu`.\n\n### Output Format\nThe output should contain $m$ lines, where each line is an integer $0$ or $1$ representing the answer to the current query.\n\n**Example for Queries**\n\nTo better illustrate the problem, consider a simplified example using direct dictionary words, shorter word lengths of $4$, and allowing offline answers for clarity.\n\nConsider a dictionary size $n = 2$ with words `1010` and `0111`.\n\n- For the query `B = 1011` and $k_1 = 1$, the answer should be $1$, as flipping the $4$th bit of `1010` will result in `1011`.\n- For the query `1 = 0001` and $k_2 = 2$, the answer should be $1$, as flipping the $2$nd and $3$rd bits of `0111` will result in `0001`.\n- For the query `1 = 0001` and $k_3 = 1$, the answer should be $0`.\n\nExplanation for $k_3 = 1$: \n- Flipping at most $1$ bit of `1010` results in: `1010`, `0010`, `1110`, `1000`, `1011`. \n- Flipping at most $1$ bit of `0111` results in: `0111`, `1111`, `0011`, `0101`, `0110`. \n- However, `0001` cannot be generated, and it must have been caused by Eve's interference.\n\n### Constraints\nFor all test cases: \n$1 \\leq n \\leq 4 \\times 10^5$, $1 \\leq m \\leq 1.2 \\times 10^5$, $0 \\leq k_i \\leq 15$, and $a_1, a_2$ are chosen uniformly at random within the range $[0, 2^{64} - 1]$.\n\n| Case ID | $n =$ | $m =$ | Max $k_i$ | Special Property |\n|:-:|:-:|:-:|:-:|:-:|\n| 1 | $10$ | $10$ | $2$ | None |\n| 2 | $500$ | $500$ | $15$ | None |\n| 3 | $1000$ | $1000$ | $0$ | None |\n| 4 | $2000$ | $2000$ | $2$ | None |\n| 5 | $5000$ | $5000$ | $15$ | None |\n| 6 | $10^4$ | $10^4$ | $15$ | None |\n| 7 | $2 \\times 10^4$ | $2 \\times 10^4$ | $15$ | None |\n| 8 | $10^5$ | $10^5$ | $1$ | None |\n| 9 | $4 \\times 10^5$ | $1.2 \\times 10^5$ | $1$ | None |\n| 10 | $5 \\times 10^4$ | $5 \\times 10^4$ | $2$ | None |\n| 11 | $7 \\times 10^4$ | $7 \\times 10^4$ | $3$ | None |\n| 12 | $10^5$ | $10^5$ | $2$ | None |\n| 13 | $3 \\times 10^4$ | $3 \\times 10^4$ | $5$ | None |\n| 14 | $6 \\times 10^4$ | $6 \\times 10^4$ | $4$ | None |\n| 15 | $1.2 \\times 10^5$ | $1.2 \\times 10^5$ | $5$ | None |\n| 16 | $6 \\times 10^4$ | $6 \\times 10^4$ | $8$ | All queries randomly generated |\n| 17 | $1.2 \\times 10^5$ | $1.2 \\times 10^5$ | $12$ | All queries randomly generated |\n| 18 | $4 \\times 10^5$ | $10^5$ | $15$ | All queries randomly generated |\n| 19 | $3 \\times 10^4$ | $3 \\times 10^4$ | $7$ | None |\n| 20 | $6 \\times 10^4$ | $6 \\times 10^4$ | $9$ | None |\n| 21 | $9 \\times 10^4$ | $9 \\times 10^4$ | $11$ | None |\n| 22 | $2 \\times 10^5$ | $1.2 \\times 10^5$ | $12$ | None |\n| 23 | $4 \\times 10^5$ | $8 \\times 10^4$ | $15$ | None |\n| 24 | $4 \\times 10^5$ | $10^5$ | $15$ | None |\n| 25 | $4 \\times 10^5$ | $1.2 \\times 10^5$ | $15$ | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3896, "prompt": "### Problem Description\n\nLittle C has decided to plant flowers in his garden to form a pattern that spells \"CCF\". He wants to know how many ways he can plant flowers to form the letter `C` and the letter `F` respectively. Unfortunately, some spots in the garden have pits and cannot be used for planting. He hopes you can help him solve this problem.\n\nThe garden can be viewed as a grid with $n \\times m$ positions, numbered from top to bottom as rows $1$ to $n$, and from left to right as columns $1$ to $m$. Each position may either be a pit or not, denoted by $a_{i, j}$. If $a_{i, j} = 1$, it means the position at row $i$ and column $j$ is a pit and cannot be used for planting; otherwise, if $a_{i, j} = 0$, the position is not a pit and can be planted.\n\nA planting configuration is called a $\\texttt{C-}$**shaped** configuration if there exist $x_1, x_2 \\in [1, n]$ and $y_0, y_1, y_2 \\in [1, m]$ such that:\n\n- $x_1 + 1 < x_2$ \n- $y_0 < y_1, y_2 \\leq m$\n\nand the positions:\n\n1. From column $y_0$ to $y_1$ in row $x_1$,\n2. From column $y_0$ to $y_2$ in row $x_2$, and\n3. From row $x_1$ to $x_2$ in column $y_0$,\n\nare **all free of pits**, and flowers are planted only in these positions.\n\nA planting configuration is called an $\\texttt{F-}$**shaped** configuration if there exist $x_1, x_2, x_3 \\in [1, n]$ and $y_0, y_1, y_2 \\in [1, m]$ such that:\n\n- $x_1 + 1 < x_2 < x_3$ \n- $y_0 < y_1, y_2 \\leq m$\n\nand the positions:\n\n1. From column $y_0$ to $y_1$ in row $x_1$,\n2. From column $y_0$ to $y_2$ in row $x_2$, and\n3. From row $x_1$ to $x_3$ in column $y_0$,\n\nare **all free of pits**, and flowers are planted only in these positions.\n\nThe examples provided explain the patterns formed by $\\texttt{C-}$shaped and $\\texttt{F-}$shaped planting configurations.\n\nGiven $n, m$, and the values of $a_{i, j}$ that indicate which positions are pits, Little C wants to know how many possible configurations of $\\texttt{C-}$shaped and $\\texttt{F-}$shaped plantings exist. Since the results could be very large, you only need to output the results modulo $998244353$ as specified in the output format section.\n\n### Input Format\n\nThe first line contains two integers $T$ and $id$, representing the number of test cases and the test point number respectively. If the input is an example case, $id = 0$.\n\nFor each of the $T$ test cases:\n\n- The first line contains four integers $n, m, c, f$, where $n$ and $m$ represent the number of rows and columns of the garden. The meanings of $c$ and $f$ are explained in the output format section.\n- The next $n$ lines each contain a string of length $m$ consisting of only `0` and `1`. The $j$-th character in the $i$-th string denotes $a_{i, j}$, indicating whether row $i$ and column $j$ is a pit or not (`1` for a pit, `0` otherwise).\n\n### Output Format\n\nLet $V_C$ and $V_F$ be the number of $\\texttt{C-}$shaped and $\\texttt{F-}$shaped planting configurations in the garden respectively. For each test case, output one line with two non-negative integers separated by a space:\n\n- $(c \\times V_C) \\bmod 998244353$, $(f \\times V_F) \\bmod 998244353$,\n\nwhere $a \\bmod P$ represents the result of $a$ modulo $P$.\n\n### **Example Explanation**\n\nFor the first example, there are four $\\texttt{C-}$shaped planting configurations:\n\n```plain\n**1 **1 **1 **1\n*10 *10 *10 *10\n**0 *** *00 *00\n000 000 **0 ***\n```\n\nIn the visualizations, `*` marks the positions where flowers are planted. Note that the two horizontal lines of the letter `C` can have different lengths.\n\nSimilarly, there are two $\\texttt{F-}$shaped planting configurations:\n\n```plain\n**1 **1\n*10 *10\n**0 ***\n*00 *00\n```\n\n### **Example 2**\n\nSee the files `plant/plant2.in` and `plant/plant2.ans`.\n\n### **Example 3**\n\nSee the files `plant/plant3.in` and `plant/plant3.ans`.\n\n### **Constraints**\n\nFor all the test cases, the following conditions are guaranteed:\n\n- $1 \\leq T \\leq 5$\n- $1 \\leq n, m \\leq 10^3$\n- $0 \\leq c, f \\leq 1$\n- $a_{i, j} \\in \\{0, 1\\}$\n\n| Test Point ID | $n$ | $m$ | $c$ | $f$ | Special Properties | Test Point Value |\n| :----------: | :----------: | :----------: | :----------: | :----------: | :----------: | :----------: |\n| $1$ | $\\leq 1000$ | $\\leq 1000$ | $0$ | $0$ | None | $1$ |\n| $2$ | $=3$ | $=2$ | $1$ | $1$ | None | $2$ |\n| $3$ | $=4$ | $=2$ | $1$ | $1$ | None | $3$ |\n| $4$ | $\\leq 1000$ | $=2$ | $1$ | $1$ | None | $4$ |\n| $5$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $1$ | A | $4$ |\n| $6$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $1$ | B | $6$ |\n| $7$ | $\\leq 10$ | $\\leq 10$ | $1$ | $1$ | None | $10$ |\n| $8$ | $\\leq 20$ | $\\leq 20$ | $1$ | $1$ | None | $6$ |\n| $9$ | $\\leq 30$ | $\\leq 30$ | $1$ | $1$ | None | $6$ |\n| $10$ | $\\leq 50$ | $\\leq 50$ | $1$ | $1$ | None | $8$ |\n| $11$ | $\\leq 100$ | $\\leq 100$ | $1$ | $1$ | None | $10$ |\n| $12$ | $\\leq 200$ | $\\leq 200$ | $1$ | $1$ | None | $6$ |\n| $13$ | $\\leq 300$ | $\\leq 300$ | $1$ | $1$ | None | $6$ |\n| $14$ | $\\leq 500$ | $\\leq 500$ | $1$ | $1$ | None | $8$ |\n| $15$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $0$ | None | $6$ |\n| $16$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $1$ | None | $14$ |\n\nSpecial Property A: $\\forall 1 \\leq i \\leq n, 1 \\leq j \\leq \\left\\lfloor \\frac{m}{3} \\right\\rfloor$, $a_{i, 3j} = 1$.\n\nSpecial Property B: $\\forall 1 \\leq i \\leq \\left\\lfloor \\frac{n}{4} \\right\\rfloor, 1 \\leq j \\leq m$, $a_{4i, j} = 1$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "medium"} +{"id": 2718, "prompt": "### Problem Description\n\n> This story takes place in the City of Magic, where we will introduce some necessary settings.\n>\n> The City of Magic can be abstracted as an **undirected connected graph** with $n$ nodes and $m$ edges (nodes are numbered from $1$ to $n$). Each edge is described by its **length** $l$ and **altitude** $a$.\n>\n> As a representative city of monsoon climates, the City of Magic is often accompanied by rain, which makes water accumulation on roads inevitable. Due to the interconnected nature of the city\u2019s drainage system, **edges with water accumulation are always those with the lowest altitudes.**\n>\n> We use a **waterline** to describe the degree of rain. Its meaning is: all edges with altitude **not exceeding** the waterline are considered to have **water accumulation.**\n\nYazid is an OIer from the City of Magic. After participating in ION2018, he is on his way home to return to his cozy residence.\n\nYazid's home happens to be located at node $1$ in the City of Magic. For the next $Q$ days, Yazid will provide his **starting point** $v$ and the **waterline** $p$ for each day.\n\nEach day, Yazid has a **car** at his starting point. Due to a malfunction, the car cannot traverse edges with water accumulation.\n\nYazid can get off the car at any node, after which he can walk through edges with water accumulation. However, the car will remain parked at the node where it was left and will no longer be used.\n\n+ Special notes about the car reset for subsequent days:\n + A new car will be prepared for Yazid at the next starting point.\n + Yazid cannot use cars left at other locations from previous days.\n\nYazid dislikes walking in the rain, so he wants to minimize the **total length of edges walked** while still achieving the goal of getting home. Please help Yazid calculate this.\n\n**Some test cases for this problem will be forced to run in an online manner. Please refer to the \"Input Format\" and \"Subtasks\" sections for specific details.**\n\n---\n\n### Input Format\n\nThe input is read from the file `return.in`.\n\nEach test case contains multiple datasets. The first line is a non-negative integer $T$, indicating the number of datasets.\n\nThe description of each dataset is as follows:\n\n+ The first line contains two non-negative integers $n$ and $m$, representing the number of nodes and the number of edges.\n+ The following $m$ lines describe the edges. Each line contains four positive integers $u, v, l, a$, representing an edge connecting node $u$ and node $v$ with a **length** of $l$ and an **altitude** of $a$.\n + It is guaranteed that $1 \\leq u, v \\leq n$.\n+ The next line contains three non-negative integers $Q, K, S$, where:\n + $Q$ represents the number of days,\n + $K \\in \\{0, 1\\}$ is a coefficient used in defining daily parameters,\n + $S$ is the maximum possible value of the waterline.\n+ The next $Q$ lines describe the conditions for each day. Each line contains two integers, $v_0$ and $p_0$, which define the day's parameters:\n + The starting point for the day is calculated as $v = (v_0 + K \\times \\text{lastans} - 1) \\bmod n + 1$.\n + The waterline for the day is calculated as $p = (p_0 + K \\times \\text{lastans}) \\bmod (S + 1)$.\n + Here, $\\text{lastans}$ represents the answer (minimum total walking distance) for the previous day. For the first day, it is predefined as $\\text{lastans} = 0$.\n + It is guaranteed that $1 \\leq v_0 \\leq n$ and $0 \\leq p_0 \\leq S$.\n\nIn input lines with multiple numbers, the numbers are separated by single spaces.\n\n---\n\n### Output Format\n\nThe output is written to the file `return.out`.\n\nOutput the result for each dataset sequentially. For each dataset:\n\n+ Print $Q$ lines, with each line containing one integer representing the minimum total walking distance for the corresponding day.\n\n---\n\n### Example Input and Output\n\n#### Example 1\n\n**Input:**\n\n```plaintext\n1\n4 4\n1 2 1 1\n2 3 1 2\n1 3 3 4\n3 4 2 2\n5 0 3\n2 0\n4 2\n4 2\n4 3\n4 3\n```\n\n**Output:**\n\n```plaintext\n0\n3\n4\n1\n6\n```\n\n**Explanation:**\n\n- On Day 1, there is no rain, and Yazid can drive directly home.\n- On Days 2, 3, and 4, the same edges accumulate water: the edge connecting nodes $1$ and $2$, and the edge connecting nodes $3$ and $4$.\n * On Day 2, starting at node $2$, Yazid can only drive to node $3$, which is unhelpful. He must walk back home entirely.\n * On Day 3, starting at node $4$, all edges connected to it are submerged, so the car is useless. He must walk home entirely.\n * On Day 4, Yazid can drive to node $2$ first and then walk home.\n- On Day 5, all edges are submerged, forcing Yazid to walk the entire way home.\n\n#### Example 2\n\n**Input:**\n\n```plaintext\n1\n5 6\n1 2 1 1\n1 3 2 0\n2 4 2 2\n3 4 3 0\n3 5 4 1\n4 5 5 3\n4 1 3\n5 2\n2 0\n0 0\n3 0\n```\n\n**Output:**\n\n```plaintext\n0\n2\n3\n5\n```\n\n---\n\n### Constraints and Notes\n\n**All test cases guarantee $T \\leq 3$. Input data across all test cases satisfy the following constraints:**\n\n+ $n \\leq 2 \\times 10^5$, $m \\leq 4 \\times 10^5$, $Q \\leq 4 \\times 10^5$, $K \\in \\{0, 1\\}$, and $1 \\leq S \\leq 10^9$.\n+ For all edges: $l \\leq 10^4$, $a \\leq 10^9$.\n+ Any two nodes are directly or indirectly connected via edges.\n\n---\n\n### Additional Details\n\nFor easier understanding, we use some simplified explanations in tables. These are formalized as follows:\n\n+ Shape of the graph:\n * When labeled as \u201ca tree\u201d or \u201ca chain,\u201d it means $m = n - 1$. Additionally:\n - \u201cTree\u201d: The graph structure contains no cycles.\n - \u201cChain\u201d: Requires all edges to satisfy $u + 1 = v$.\n+ Altitude:\n * If labeled as \u201cuniform,\u201d all edges satisfy $a = 1$.\n+ Forcing online:\n * When labeled as \u201cyes,\u201d $K = 1$; otherwise, $K = 0$.\n+ If labeled as \u201cnot guaranteed,\u201d no assumptions are made.\n\n| $n$ | $m$ | $Q =$ | Test Case | Graph Type | Altitude | Force Online |\n|-------|-----------------|----------|-----------|------------|------------|--------------|\n| $\\leq 1$ | $\\leq 0$ | $0$ | 1 | Not guaranteed | Uniform | No |\n| $\\leq 6$ | $\\leq 10$ | $10$ | 2 | Not guaranteed | Uniform | No |\n| $\\leq 50$ | $\\leq 150$ | $100$ | 3 | Not guaranteed | Uniform | No |\n| $\\leq 100$ | $\\leq 300$ | $200$ | 4 | Not guaranteed | Uniform | No |\n| $\\leq 1500$| $\\leq 4000$ | $2000$ | 5 | Not guaranteed | Uniform | No |\n| $\\leq 200000$ | $\\leq 400000$ | $100000$ | 6 | Not guaranteed | Uniform | No |\n| $\\leq 1500$| $= n - 1$ | $2000$ | 7 | Chain | Not guaranteed | No |\n| $\\leq 1500$| $= n - 1$ | $2000$ | 8 | Chain | Not guaranteed | No |\n| $\\leq 1500$| $= n - 1$ | $2000$ | 9 | Chain | Not guaranteed | No |\n| $\\leq 200000$| $= n - 1$ | $100000$ | 10 | Tree | Not guaranteed | No |\n| $\\leq 200000$| $= n - 1$ | $100000$ | 11 | Tree | Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 12 | Not guaranteed| Not guaranteed | No |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 13 | Not guaranteed| Not guaranteed | No |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 14 | Not guaranteed| Not guaranteed | No |\n| $\\leq 1500$| $\\leq 4000$ | $2000$ | 15 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 1500$| $\\leq 4000$ | $2000$ | 16 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 17 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 18 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $400000$ | 19 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $400000$ | 20 | Not guaranteed| Not guaranteed | Yes |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3852, "prompt": "### Problem Description\n\nIn this problem, you need to solve a well-known NP problem \u2014 the Quadratic Integer Programming Problem.\n\nThe Quadratic Integer Programming Problem has variables: You are required to produce an **integer** sequence of length $n$, denoted as $(x_1, x_2, \\ldots, x_n)$, that satisfies all of the following conditions.\n\nThe Quadratic Integer Programming Problem has constraints: The integer sequence you provide must satisfy the following two types of constraints:\n\n1. **Constraints on individual variables:** Given a positive integer $k$ ($3 \\leq k \\leq 5$) and $n$ intervals $[l_i, r_i]$ ($1 \\leq i \\leq n$), where $1 \\leq l_i \\leq r_i \\leq k$, the sequence must satisfy $\\forall 1 \\leq i \\leq n$, $l_i \\leq x_i \\leq r_i$.\n2. **Constraints between variables:** Given $m$ triplets $(p_j, q_j, b_j)$, the sequence must satisfy $\\forall 1 \\leq j \\leq m$, $\\lvert x_{p_j} - x_{q_j} \\rvert \\leq b_j$.\n\nThe Quadratic Integer Programming Problem has an objective function: Given $k-2$ objective parameters $v_2,v_3,\\dots,v_{k-1}$ (**note that the subscript range is $\\boldsymbol{2}$ to $\\boldsymbol{k-1}$**), for an integer sequence $\\{p_1,p_2,\\ldots,p_n\\}$ with values in the domain $[1, k]$, let $c_i$ denote the number of elements in this sequence that are equal to $i$, and let $G$ denote the number of integer pairs $(i, j)$ that satisfy $1 \\leq i, j \\leq n$ and $\\lvert p_i - p_j \\rvert \\leq 1$. **Note that when $\\boldsymbol{i \\neq j}$, $\\boldsymbol{(i, j)}$ and $\\boldsymbol{(j, i)}$ are different pairs.** The **weight** of this sequence is defined as:\n\n$$\nW(p_1, p_2, \\ldots, p_n) = 10^6 G + \\sum_{i=2}^{k-1} c_i v_i \\text{.}\n$$\n\nYour sequence needs to maximize its weight while satisfying the two types of constraints. Under the given constraints, it is guaranteed that there exists at least one sequence that satisfies the constraints.\n\nThe Quadratic Integer Programming Problem may involve multiple queries. For each query, you will be provided with different objective parameters $v_2, v_3, \\ldots, v_{k-1}$. For each query, you need to find a sequence that maximizes its weight under the given constraints. To reduce output size, you only need to output the weight of the sequence.\n\n### Input Format\n**This problem contains multiple test cases.** The first line contains a non-negative integer and a positive integer $C, T$, representing the test case ID and the number of test cases. $C = 0$ indicates that this group of data is a sample.\n\nFor each test case, the first line contains four integers $k, n, m, q$, specifying the domain of the sequence values, the length of the sequence, the number of constraints between variables, and the number of queries.\n\nThe next $n$ lines each contain two integers $l_i, r_i$, describing the value range of each element in the sequence.\n\nThe next $m$ lines each contain three integers $p_j, q_j, b_j$, describing one constraint between variables.\n\nThe next $q$ lines each contain $k - 2$ non-negative integers $v_2, v_3, \\ldots, v_{k - 1}$, describing the weight parameters for a query.\n\n### Output Format\nFor each query of each test case, output a single integer in a line, representing the maximum weight of the sequence.\n\n---\n\n### **Sample \\#1**\n\nSee the files `qip/qip1.in` and `qip/qip1.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $1$ in the data range.\n\n---\n\n**Sample Explanation \\#1**\n\nIn the first test case, the optimal sequence for both queries is $(1, 2, 2, 1, 3)$, where $c_2 = 2$ and $G = 21$.\n\n---\n\n### **Sample \\#2**\n\nSee the files `qip/qip2.in` and `qip/qip2.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $3$ in the data range.\n\n---\n\n**Sample Explanation \\#2**\n\nIn the first test case, the optimal sequences for the two queries are $(4, 4, 3, 3)$ and $(4, 3, 2, 2)$, respectively.\n\n---\n\n### **Sample \\#3**\n\nSee the files `qip/qip3.in` and `qip/qip3.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $5$ in the data range.\n\n---\n\n**Sample Explanation \\#3**\n\nIn the first test case, the optimal sequences for the three queries are $(3, 3, 3, 3, 3)$, $(2, 2, 3, 3, 2)$, and $(3, 2, 4, 4, 2)$, respectively.\n\n---\n\n### **Sample \\#4**\n\nSee the files `qip/qip4.in` and `qip/qip4.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $2$ in the data range.\n\n---\n\n### **Sample \\#5**\n\nSee the files `qip/qip5.in` and `qip/qip5.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $4$ in the data range.\n\n---\n\n### **Sample \\#6**\n\nSee the files `qip/qip6.in` and `qip/qip6.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $8$ in the data range.\n\n---\n\n### **Sample \\#7**\n\nSee the files `qip/qip7.in` and `qip/qip7.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $14$ in the data range.\n\n---\n\n### **Sample \\#8**\n\nSee the files `qip/qip8.in` and `qip/qip8.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $17$ in the data range.\n\n---\n\n### **Data Constraints**\n\nLet $\\sum q$ denote the total number of queries for all test cases in a single test point. For all test points:\n\n- $1 \\leq T \\leq 600$,\n- For the $i$-th ($1 \\leq i \\leq T$) test case, $1 \\leq n \\leq \\max(\\frac{T}{i}, 2 \\log_2 T)$,\n- $3 \\leq k \\leq 5$, $0 \\leq m \\leq 3n$, $1 \\leq q, \\sum q \\leq 3 \\times 10^5$,\n- $1 \\leq l_i \\leq r_i \\leq k$,\n- $1 \\leq p_j, q_j \\leq n$, $0 \\leq b_j < k$,\n- $0 \\leq v_2, \\dots, v_{k-1} \\leq 10^{12}$.\n\n| Test Point ID | $T \\leq$ | $k=$ | $\\sum q \\leq$ | Special Properties | Points |\n|:-------------:|:--------:|:----:|:-------------------:|:------------------:|:------:|\n| $1$ | $10$ | $3$ | $200$ | None | $4$ |\n| $2$ | $600$ | $3$ | $3 \\times 10^5$ | None | $6$ |\n| $3$ | $10$ | $4$ | $200$ | None | $4$ |\n| $4$ | $600$ | $4$ | $3 \\times 10^5$ | None | $6$ |\n| $5$ | $10$ | $5$ | $300$ | None | $5$ |\n| $6$ | $15$ | $5$ | $500$ | None | $4$ |\n| $7$ | $25$ | $5$ | $750$ | None | $4$ |\n| $8$ | $50$ | $5$ | $1000$ | None | $6$ |\n| $9$ | $80$ | $5$ | $1500$ | None | $6$ |\n| $10$ | $120$ | $5$ | $2000$ | None | $5$ |\n| $11$ | $200$ | $5$ | $8000$ | A | $3$ |\n| $12$ | $400$ | $5$ | $3 \\times 10^4$ | A | $4$ |\n| $13$ | $600$ | $5$ | $2 \\times 10^5$ | A | $5$ |\n| $14$ | $200$ | $5$ | $8000$ | B | $3$ |\n| $15$ | $400$ | $5$ | $3 \\times 10^4$ | B | $4$ |\n| $16$ | $600$ | $5$ | $2 \\times 10^5$ | B | $4$ |\n| $17$ | $120$ | $5$ | $10^5$ | C | $4$ |\n| $18$ | $150$ | $5$ | $2 \\times 10^5$ | C | $5$ |\n| $19$ | $180$ | $5$ | $3 \\times 10^5$ | C | $5$ |\n| $20$ | $300$ | $5$ | $5 \\times 10^4$ | None | $5$ |\n| $21$ | $450$ | $5$ | $10^5$ | None | $4$ |\n| $22$ | $600$ | $5$ | $3 \\times 10^5$ | None | $4$ |\n\n### Special Properties\n\n- **Property A**: $m = 0$.\n- **Property B**: $m \\leq 10$, and the total of $m$ across all test cases in a single test point does not exceed $200$.\n- **Property C**: Data generated randomly as follows:\n - During dataset generation, given parameters $k, n, m, q$ and $k$ non-negative constants $p_0, p_1, p_2, \\dots, p_{k-1}$, where $p_{k-1} \\neq 0$:\n - For $1 \\leq i \\leq n$, independently generate $x, y \\in [1, k]$ uniformly at random. Then $l_i = \\min(x, y)$, and $r_i = \\max(x, y)$.\n - Continue generating triplets as follows until $m$ triplets are produced:\n 1. Randomly generate $u, v \\in [1, n]$ uniformly.\n 2. Randomly generate $w$ with the probabilities defined over $p$ (for $0 \\leq i \\leq k-1$, $w = i$ with probability $\\frac{p_i}{p_0 + p_1 + \\dots + p_{k-1}}$).\n 3. If adding $(u, v, w)$ to the existing set of triplets causes no sequence $(x_1, x_2, \\dots, x_n)$ to satisfy all constraints, discard this triplet; otherwise, include it.\n - Each query\u2019s $v_2, \\ldots, v_{k-1}$ is independently generated uniformly at random in the range $[0, 10^{12}]$.\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": 3343, "prompt": "### Problem Description\n$\\mathbf{X1}$: Let me translate the message content.\n\n> Definition: Trees described in this context are inductively defined: a single node constitutes a tree; a tree with another tree as its left (or right) child constitutes a tree; a tree with two trees as its left and right children also constitutes a tree. Any structure generated using these rules in a finite number of steps is called a tree.\n\n$\\mathbf{X2}$: In other words, the trees discussed here refer to **non-empty, rooted, binary trees with distinct left and right children**.\n\n$\\mathbf{X1}$: Exactly. Next, the book defines isomorphism between two trees.\n\n> Definition: Two trees $T$, $T^{\\prime}$ are said to be isomorphic, denoted as $T \\equiv T^{\\prime}$, which is defined by the following four rules:\n> 1. Trees consisting of a single node are mutually isomorphic;\n> 2. If the roots of two trees both have only left subtrees, and their left subtrees are isomorphic, then the two trees are isomorphic;\n> 3. If the roots of two trees both have only right subtrees, and their right subtrees are isomorphic, then the two trees are isomorphic;\n> 4. If the roots of two trees have both left and right subtrees, and their left and right subtrees correspondingly are isomorphic, then the two trees are isomorphic.\n>\n> Obviously, the isomorphic relation forms an equivalence relation among all trees. For convenience, we treat isomorphic trees as identical.\n\n$\\mathbf{X2}$: Treating isomorphic trees as identical means the nodes of such trees are equivalent. Simply put, two trees are isomorphic if and only if **they are identical in terms of node arrangement without labels, while distinguishing left and right children**; we say two trees are different if and only if they are not isomorphic.\n\n$\\mathbf{X1}$: The book also defines **leaves**: as in the usual definition, leaves refer to **nodes that have no children**.\n\n$\\mathbf{X2}$: This is completely consistent with the definition we are familiar with. Mathematicians really are a bit verbose... I bet only $\\mathbf{X3}$ would like this kind of approach.\n\n$\\mathbf{X1}$: I don\u2019t really mind this \u2014 compared to an intuition based on experience, precise definitions and rigorous proofs are much more reassuring. Look, the next definition is not as intuitive.\n\n> Definition: A tree $T$ is said to be **replaced in one step** by another tree $T^{\\prime}$ if replacing one **leaf node** of $T$ with another tree $T^{\\prime \\prime}$ results in a tree isomorphic to $T^{\\prime}$, denoted as $T \\rightarrow T^{\\prime}$; a tree $T$ is said to be **replaced** by $T^{\\prime}$, denoted as $T \\rightarrow^{\\star} T^{\\prime}$, if there exists a natural number $n \\geq 1$ and trees $T_{1}, T_{2}, \\ldots, T_{n}$ such that $T \\equiv T_{1} \\rightarrow T_{2} \\rightarrow \\cdots \\rightarrow T_{n} \\equiv T^{\\prime}$.\n\n$\\mathbf{X2}$: Let me think... Replacement means deleting a leaf node and placing another tree in its position, as if the leaf node \"grows\" into a larger subtree. To say one tree replaces another means it can be obtained through **zero, one, or multiple single-step replacements**. Oh... I get it now! For example, any tree can be replaced with itself, meaning for a tree $T$, $T \\rightarrow^{\\star} T^{\\prime}$ always holds. The following image helps to understand the concepts of single-step replacement and replacement.\n\n![img](https://cdn.luogu.com.cn/upload/image_hosting/0o4pfqui.png)\n\n$\\mathbf{X1}$: You are correct. Specifically, any tree can replace itself with infinitely many distinct trees, and a tree consisting only of a single node can replace itself with any other tree. This is also defined in the book.\n\n> Definition: For a tree $T$, define $\\operatorname{grow}(T)$ as the set of all trees that $T$ can replace itself to form, i.e., $\\operatorname{grow}(T)=\\left\\{T^{\\prime} \\mid T \\rightarrow^{\\star} T^{\\prime}\\right\\}$. Moreover, if $\\mathscr{T}=\\left\\{T_{1}, T_{2}, \\ldots, T_{n}\\right\\}$ is a finite set of trees, $\\operatorname{grow}(\\mathscr{T})$ is defined as the union of all $\\operatorname{grow}\\left(T_{i}\\right)$, where $i=1,2, \\ldots, n$. That is,\n> $$\\operatorname{grow}(\\mathscr{T})=\\bigcup_{T_{i} \\in \\mathscr{T}} \\operatorname{grow}\\left(T_{i}\\right)$$\n\n$\\mathbf{X2}$: Let\u2019s call $\\operatorname{grow}(\\mathscr{T})$ the **growth set of tree set $\\mathscr{T}$** \u2014 in other words, the growth set $\\operatorname{grow}(\\mathscr{T})$ contains all the trees that can be obtained by replacing any tree $T \\in \\mathscr{T}$. Let\u2019s refer to a set of trees as a **forest**. Informally, a new forest formed by the growth of an existing forest includes all trees obtained by every tree in the original forest growing in all possible ways. Clearly, the new forests grown from a non-empty forest are always infinite. However, this infinite forest, namely $\\operatorname{grow}(\\mathscr{T})$, does not necessarily include all trees \u2014 furthermore, it may not even include \"almost all\" trees.\n\n$\\mathbf{X1}$: Let me supplement: A forest is considered **almost complete** (or **almost includes all trees**) if only finitely many trees are excluded from it. For a finite forest $\\mathscr{T}$, $\\operatorname{grow}(\\mathscr{T})$ either includes all trees, includes almost all trees, or excludes infinitely many trees. If this were an OI problem, the problem setter would likely **provide examples of all three cases in the test cases**. The key theorem in the book uses the same definitions.\n\n> **Theorem** (**Decidability of Almost Completeness**): A set of trees is **almost complete** if it excludes only finitely many trees. For a given finite set of trees $\\mathscr{T}$, there exists an efficient algorithm to determine whether $\\operatorname{grow}(\\mathscr{T})$ is almost complete.\n\n$\\mathbf{X2}$: This problem has become a pure OI problem! Let me restate the problem: **Given a finite forest $\\mathscr{T}$, determine whether $\\operatorname{grow}(\\mathscr{T})$ is almost complete, i.e., whether only finitely many trees cannot be grown from the trees in the forest**.\n\n$\\mathbf{X1}$: In other words, given a finite set of trees $\\mathscr{T}$, determine whether only finitely many trees $T$ satisfy $T \\notin \\operatorname{grow}(\\mathscr{T})$. The condition $T \\notin \\operatorname{grow}(\\mathscr{T})$ means there does not exist $T^{\\prime} \\in \\mathscr{T}$ such that $T^{\\prime} \\rightarrow^{\\star} T$. This problem is indeed very different from typical OI problems: I cannot even think of an algorithm for this problem.\n\n$\\mathbf{X2}$: Same here, but this gives me a thrilling urge to solve an unknown problem.\n\n---\n\n### Input Format\nThis problem has multiple test cases. The first line of the input contains a positive integer $N$, indicating the number of test cases. The following are exactly the $N$ test cases, each with the following format:\n\nThe first line contains a positive integer $m$, denoting the number of trees in the set. Then, $m$ trees are described in the following format:\n- First, a positive integer $n$, indicating the number of nodes in the tree. Nodes are numbered $1, 2, \\ldots, n$;\n- Following this are $n$ lines, each containing two non-negative integers. The $i$-th line contains $l_i$ and $r_i$, respectively representing the node numbers of the left and right children of node $i$. If a left (or right) child does not exist, then $l_i$ (or $r_i$) is $0$. A leaf node satisfies $l_i = r_i = 0$.\n- The input is guaranteed to form a tree with node $1$ as the root. **Note**: Node numbers are for input convenience; any isomorphic trees are considered identical.\n\nAmong the $m$ input trees, there may be pairs of isomorphic trees; after removing duplicates (i.e., keeping only one of each isomorphic tree), they form a tree set $\\mathscr{T}$. You are required to determine whether the growth set $\\operatorname{grow}(\\mathscr{T})$ is almost complete.\n\n---\n\n### Output Format\nThe output contains $N$ lines corresponding to the answers for the $N$ test cases. For the $i$-th test case, output a string: if the growth set of the forest from the $i$-th test case is almost complete (i.e., only finitely many trees cannot be grown from the forest), output `Almost Complete`; otherwise, output `No`. **Pay attention to the spelling and case of the output strings**.\n\n#### Sample Case 2 Explanation\nThis example contains only one test case, in which the forest $\\mathscr{T}$ includes three trees, as shown below. It is easy to find that only a single-node tree is not included in $\\operatorname{grow}(\\mathscr{T})$, and $\\operatorname{grow}(\\mathscr{T})$ almost contains all trees, making it almost complete.\n\n![img2](https://cdn.luogu.com.cn/upload/image_hosting/394s081s.png)\n\n#### Sample Case 3 Explanation\nThis example contains only one test case, in which the forest $\\mathscr{T}$ includes two trees. It is easy to find that for any $n \\geq 2$, chain-like trees containing $n$ nodes where each non-leaf node has only a right child are excluded from $\\operatorname{grow}(\\mathscr{T})$. Hence, infinitely many trees are excluded from $\\operatorname{grow}(\\mathscr{T})$, and $\\mathscr{T}$ is not almost complete.\n\n#### Sample Case 4\nRefer to the player directory under surreal/surreal4.in and surreal/surreal4.ans.\n\n---\n\n### Constraints on Test Cases\n\n**All test cases satisfy**: $\\sum n \\leq 2 \\times 10^{6}$, $\\sum m \\leq 2 \\times 10^{6}$, $\\max h \\leq 2 \\times 10^{6}$, $N \\leq 10^{2}$. Here, $\\sum n$, $\\sum m$, and $\\max h$ have the following meanings:\n- $\\sum n$: The total number of nodes across all trees in all test cases.\n- $\\sum m$: The total number of trees across all test cases.\n- $\\max h$: The maximum height among all trees in the test cases (a single-node tree has a height of $1$).\n\nBelow is a summary of the constraints for each test case group:\n\n| Case Set | $N$ | $\\sum n$ | $\\sum m$ | $\\max h$ | Special Constraints |\n| :-: | :-: | :-: | :-: | :-: |:-: |\n| $1$ | $100$ | $\\le 10^3$ | $\\le 10^3$ | $\\leq 1$ | None |\n| $2 \\sim 3$ | $100$ | $\\le 10^3$ | $\\le 10^3$ | $\\leq 2$ | Property $1$ |\n| $4$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 4$ | None | \n| $5$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 5$ | Property $2$ | \n| $6$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 8$ | None | \n| $7$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 9$ | Property $2$ | \n| $8$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 10$ | None | \n| $9$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 10^6$ | Property $3$ | \n| $10$ | $20$ | $\\le 10^3$ | $\\le 100$ | $\\leq 10^3$ | Property $4$ | \n| $11$ | $20$ | $\\le 2\\times 10^3$ | $\\le 2\\times 10^3$ | $\\leq 2\\times 10^3$ | Property $4$ | \n| $12$ | $20$ | $\\le 10^5$ | $\\le 10^5$ | $\\leq 10^5$ | Property $4$ | \n| $13$ | $20$ | $\\le 2\\times 10^5$ | $\\le 2\\times 10^5$ | $\\leq 2\\times 10^5$ | Property $4$ | \n| $14$ | $20$ | $\\le 800$ | $\\le 200$ | $\\leq 800$ | None |\n| $15$ | $20$ | $\\le 10^3$ | $\\le 100$ | $\\leq 10^3$ | None |\n| $16$ | $20$ | $\\le 2\\times 10^3$ | $\\le 2\\times 10^3$ | $\\leq 2\\times 10^3$ | None |\n| $17$ | $40$ | $\\le 3\\times 10^5$ | $\\le 3\\times 10^5$ | $\\leq 3\\times 10^5$ | None |\n| $18$ | $40$ | $\\le 6\\times 10^5$ | $\\le 6\\times 10^5$ | $\\leq 6\\times 10^5$ | None |\n| $19$ | $40$ | $\\le 9\\times 10^5$ | $\\le 9\\times 10^5$ | $\\leq 9\\times 10^5$ | None |\n| $20$ | $40$ | $\\le 1.2\\times 10^6$ | $\\le 1.2\\times 10^6$ | $\\leq 1.2\\times 10^6$ | None |\n| $21$ | $40$ | $\\le 1.5\\times 10^6$ | $\\le 1.5\\times 10^6$ | $\\leq 1.5\\times 10^6$ | None |\n| $22 \\sim 25$ | $40$ | $\\leq 2\\times 10^6$ | $\\leq 2\\times 10^6$ | $\\leq 2\\times 10^6$ | None |\n\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "python", "difficulty": "hard"} +{"id": "swerc2022_E", "prompt": "# Problem E: Spinach Pizza\n## SWERC 2022-2023\n\n## Problem Statement\n\nThe two siblings, Alberto and Beatrice, have to eat a spinach pizza together. However, neither of them likes spinach, so they both want to eat as little as possible.\n\nThe pizza has the shape of a strictly convex polygon with $n$ vertices located at integer coordinates $(a_1, y_1), (a_2, y_2), \\ldots, (a_n, y_n)$ of the plane.\n\nThe siblings have decided to eat the pizza in the following way: taking turns, starting with Alberto, each sibling chooses a vertex of the remaining part of the pizza and eats out the triangle determined by its two neighboring edges. In this way, after each of the first $n - 3$ turns, the pizza will have one less vertex. The game ends after the $(n - 2)$-th turn, when all the pizza has been eaten.\n\nAssuming that Alberto and Beatrice choose the slices to eat optimally, which of the siblings manages to eat at most half of the pizza? You should identify a sibling that has a strategy to do so and help them choose the slices appropriately. Note that it is possible that both Alberto and Beatrice end up eating exactly half of the area if they choose their slices optimally.\n\n## Input\n\nThe first line contains a single integer $n$ ($4 \\leq n \\leq 100$) \u2014 the number of vertices.\n\nThe next $n$ lines contain two integers $a_i$ and $y_i$ each ($-10^6 \\leq a_i, y_i \\leq 10^6$) \u2014 the coordinates of the $i$-th vertex of the polygon representing the initial shape of the pizza.\n\nIt is guaranteed that the polygon is strictly convex and that its vertices are given in counterclockwise order.\n\n## Interaction\n\nFirst, you should print a line containing either the string `Alberto` or the string `Beatrice` \u2014 the sibling that you will help to win.\n\nThen, for the next $n - 2$ turns, you will alternate with the judge in choosing a slice of the pizza and removing it, starting with you if you chose to help Alberto, or starting with the judge if you chose to help Beatrice.\n\n- When it is your turn, print a single line containing an integer $p$ ($1 \\leq p \\leq n$) that has not been chosen before, indicating that you want to eat the slice determined by the vertex located at $(a_p, y_p)$.\n- When it is the judge's turn, read an integer $q$ ($1 \\leq q \\leq n$), indicating that the other player eats the slice determined by the vertex located at $(a_q, y_q)$. It is guaranteed that $q$ has not been chosen before.\n\nIf one of your interactions is malformed, the interactor terminates immediately and your program receives the verdict `WRONG-ANSWER`. Otherwise, you will receive `CORRECT` if at the end your player has eaten at most half of the pizza, and `WRONG-ANSWER` otherwise.\n\n## Notes\n\nAfter printing a line, do not forget to end the line and flush the output. Otherwise, you will get the verdict `TIMELIMIT`. To flush the output, use:\n- `fflush(stdout)` in C\n- `fflush(stdout)`, `cout << flush` or `cout.flush()` in C++\n- `System.out.flush()` in Java and Kotlin\n- `sys.stdout.flush()` in Python\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n4\n0 0\n6 1\n5 3\n1 4\n```\n\n### Sample Output 1\n```\nAlberto\n2\n```\n\n### Explanation of Sample 1\nThe pizza has an area of 15. Alberto can eat less than half of the pizza by eating the slice around vertex 2 (which has an area of 6.5) or around vertex 3 (which has an area of 3.5).\n\n### Sample Input 2\n```\n6\n0 0\n2 0\n3 2\n2 4\n0 4\n-1 2\n```\n\n### Sample Output 2\n```\nAlberto\n2\n```\n\n### Explanation of Sample 2\nIt can be proved that both players will eat exactly half of the pizza if they eat optimally. Therefore, it is possible to choose to help either Alberto or Beatrice.\n\n### Sample Input 3\n```\n7\n0 0\n2 0\n5 2\n4 5\n1 5\n-1 4\n-1 2\n```\n\n### Sample Output 3\n```\nBeatrice\n7\n2\n5\n4\n6\n```\n\n### Explanation of Sample 3\nIt is possible to show that only Beatrice has a strategy to eat at most half of the pizza. The following is an example of a valid interaction (after reading the input):\n\n| Contestant | Judge | Explanation |\n|------------|-------|------------|\n| Beatrice | | The contestant will help Beatrice |\n| 7 | | Alberto eats the triangle with vertices 6, 7, 1 and area 1 |\n| | 2 | Beatrice eats the triangle with vertices 1, 2, 3 and area 2 |\n| 5 | | Alberto eats the triangle with vertices 4, 5, 6 and area 1.5 |\n| | 4 | Beatrice eats the triangle with vertices 3, 4, 6 and area 8 |\n| 6 | | Alberto eats the triangle with vertices 3, 6, 1 and area 11 |\n| | | The total area eaten by Alberto is 13.5 and the total area eaten by Beatrice is 10, which is less than half the area of the whole pizza. The actions performed by the contestant and the judge in this example of interaction may be non-optimal. |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2023_A", "prompt": "### Problem Statement\n\n**Card Game**\n\n**Time Limit:** 1 second\n\nThe Olympic Games in Paris are almost here, and you are thrilled! You and four of your friends managed to get five of the rare tickets for sports climbing, even though all tickets were sold out in less than two hours. While waiting for the games to start, you decide to do something fun to keep your mind off the wait: play your favourite card game.\n\nThe card deck contains four standard suits of different colours: silver (S), white (W), emerald (E), and red (R), as well as one trump suit coloured cyan (C). That is, the cyan cards outrank all other cards. There are $N$ cards of each suit, numbered from 1 to $N$. This means that, in total, the deck comprises $5N$ cards. At the beginning of the game, the deck is randomly distributed between the five players, such that each player gets $N$ cards.\n\nBefore you start playing, you want to organise your cards such that all cards of the same suit are next to each other in increasing order, and the trump cards appear at the end (also in increasing order). When you receive your cards, they appear in your hand as a sequence. To organise them, you perform a sequence of actions, where in each action you take one card out of your hand and put it back in your hand at another position (between two cards, before the first card, or after the last card).\n\nYou cannot help but wonder: what is the minimum number of actions you need to take in order to organise your hand?\n\n**Input:**\nThe input consists of two lines. The first line contains the number $N$. The second line contains $N$ space-separated values describing the sequence of cards in your hand. Each value is composed of one letter of the set [S, W, E, R, C] (describing the card suit), followed by an integer $V$ such that $1 \\leq V \\leq N$ (describing the card number).\n\n**Output:**\nThe output should contain a single line, consisting of a single number: the minimum number of actions required to organise your hand.\n\n**Limits:**\n- $1 \\leq N \\leq 100000$\n\n### Sample Inputs and Outputs\n\n**Sample Input 1**\n```\n4\nC1 R2 E4 R1\n```\n\n**Sample Output 1**\n```\n2\n```\n\n**Sample Input 2**\n```\n5\nS2 W4 E1 R5 C1\n```\n\n**Sample Output 2**\n```\n10\n```\n\n### Explanation\n\nIn the first sample input, the sequence of cards is \"C1 R2 E4 R1\". To organise the cards, you can perform the following actions:\n1. Move \"R1\" to the position before \"R2\" to get \"C1 R1 R2 E4\".\n2. Move \"E4\" to the end to get \"C1 R1 R2 E4\".\n\nThus, the minimum number of actions required is 2.\n\nIn the second sample input, the sequence of cards is \"S2 W4 E1 R5 C1\". The sequence needs to be organised as \"S1 S2 W1 W2 W3 W4 E1 E2 E3 E4 R1 R2 R3 R4 R5 C1\". The minimum number of actions required to achieve this is 10.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2022_B", "prompt": "# Problem B: Uniform Chemistry\n**SWERC 2022-2023**\n\n## Problem Statement\n\nIn a parallel universe, there are $n$ chemical elements, numbered from 1 to $n$. The element number $n$ has not been discovered so far, and its discovery would be a pinnacle of research and would bring the person who does it eternal fame and the so-called SWERC prize.\n\nThere are $m$ independent researchers, numbered from 1 to $m$, that are trying to discover it. Currently, the $i$-th researcher has a sample of the element $s_i$. Every year, each researcher independently does one fusion experiment. In a fusion experiment, if the researcher currently has a sample of element $a$, they produce a sample of an element $b$ that is chosen uniformly at random between $a + 1$ and $n$, and they lose the sample of element $a$. The elements discovered by different researchers or in different years are completely independent.\n\nThe first researcher to discover element $n$ will get the SWERC prize. If several researchers discover the element in the same year, they all get the prize. For each $i = 1, 2, ..., m$, you need to compute the probability that the $i$-th researcher wins the SWERC prize.\n\n## Input\n\nThe first line contains two integers $n$ and $m$ ($2 \\leq n \\leq 100$, $1 \\leq m \\leq 10$) \u2014 the number of elements and the number of researchers.\nThe second line contains $m$ integers $s_1, s_2, \\ldots, s_m$ ($1 \\leq s_i < n$) \u2014 the elements that the researchers currently have.\n\n## Output\n\nPrint $m$ floating-point numbers. The $i$-th number should be the probability that the $i$-th researcher wins the SWERC prize. Your answer is accepted if each number differs from the correct number by at most $10^{-8}$.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n2 3\n1 1 1\n```\n\n### Sample Output 1\n```\n1.0 1.0 1.0\n```\n\n**Explanation of Sample 1:**\nAll researchers will discover element 2 in the first year and win the SWERC prize.\n\n### Sample Input 2\n```\n3 3\n1 1 2\n```\n\n### Sample Output 2\n```\n0.5 0.5 1.0\n```\n\n**Explanation of Sample 2:**\nThe last researcher will definitely discover element 3 in the first year and win the SWERC prize. The first two researchers have a 50% chance of discovering element 2 and a 50% chance of discovering element 3, and only element 3 will bring them the prize.\n\n### Sample Input 3\n```\n3 3\n1 1 1\n```\n\n### Sample Output 3\n```\n0.625 0.625 0.625\n```\n\n**Explanation of Sample 3:**\nEach researcher has an independent 50% chance of discovering element 3 in the first year, in which case they definitely win the SWERC prize. Additionally, if they all discover element 2 in the first year, which is a 12.5% chance, then they will all discover element 3 in the second year and all win the prize.\n\n### Sample Input 4\n```\n100 7\n1 2 4 8 16 32 64\n```\n\n### Sample Output 4\n```\n0.178593469 0.179810455 0.182306771\n0.187565366 0.199300430 0.229356322\n0.348722518\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2022_K", "prompt": "### Problem K: Train Splitting\n\n**SWERC 2022-2023**\n\n#### Train Splitting\n\n**Time Limit:** 2.0s \n**Memory Limit:** 2048MB\n\nThere are $n$ big cities in Italy, and there are $m$ train routes between pairs of cities. Each route connects two different cities bidirectionally. Moreover, using the trains, one can reach every city starting from any other city.\n\nRight now, all the routes are operated by the government-owned Italian Carriage Passenger Company, but the government wants to privatize the routes. The government does not want to give too much power to a single company, but it also does not want to make people buy a lot of different subscriptions. Additionally, it would like to give a fair chance to all companies. In order to formalize all these wishes, the following model was proposed:\n\n- There will be $k \\geq 2$ private companies indexed by 1, 2, ..., $k$. Each train route will be operated by exactly one of the $k$ companies.\n- For any company, there should exist two cities such that it is impossible to reach one from the other using only routes operated by that company.\n- On the other hand, for any two companies, it should be possible to reach every city from any other city using only routes operated by these two companies.\n\nFind a plan satisfying all these criteria. It can be shown that a viable plan always exists. Please note that you can choose the number $k$ and you do not have to minimize or maximize it.\n\n#### Input\n\nEach test contains multiple test cases. The first line contains an integer $t$ ($1 \\leq t \\leq 1000$) \u2014 the number of test cases. The descriptions of the $t$ test cases follow.\n\nThe first line of each test case contains two integers $n$ and $m$ ($3 \\leq n \\leq 50$, $n - 1 \\leq m \\leq \\frac{n(n - 1)}{2}$) \u2014 the number of cities and the number of train routes.\n\nThe next $m$ lines contain two integers $u_i$ and $v_i$ each ($1 \\leq u_i, v_i \\leq n$, $u_i \\neq v_i$) \u2014 the $i$-th train route connects cities $u_i$ and $v_i$.\n\nIt is guaranteed that the routes connect $m$ distinct pairs of cities. It is guaranteed that using the trains, one can reach every city starting from any other city.\n\nThe sum of the values of $n$ over all test cases does not exceed 5000.\n\n#### Output\n\nFor each test case, on the first line print an integer $k$ ($2 \\leq k \\leq m$) \u2014 the number of companies in your plan; on the second line print $m$ integers $c_1, c_2, \\ldots, c_m$ ($1 \\leq c_i \\leq k$) \u2014 in your plan, company $c_i$ operates the $i$-th route.\n\nIf there are multiple valid plans, you may print any of them.\n\n#### Sample Input 1\n```\n2\n5 9\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n3 3\n1 2\n3 1\n2 3\n```\n\n#### Sample Output 1\n```\n4\n1 2 3 1 4 2 2 4 3\n3\n2 3 1\n```\n\n#### Explanation of Sample 1\n\nIn the first test case, the output is illustrated in the following picture, where different colors correspond to different companies (blue for 1, red for 2, green for 3, and yellow for 4):\n\n- If we consider, for example, only companies 2 and 3, we can see that from any city it is possible to reach every other city (picture on the left below).\n- However, if we restrict to company 2 alone, it becomes impossible to reach city 5 from city 1 (picture on the right).\n\nIn the second test case, the output is illustrated in the following picture:\n\n- The plan ensures that no single company can connect all cities, but any two companies together can.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2024_K", "prompt": "# Problem: Disk Covering\n\nOn a vast, flat green meadow, there are several golden disks in the shape of perfect circles from ancient times. According to legend, if one chants a spell, the area covered by the disks will turn into flames, fending off enemy attacks. When the enemy comes, you can hide in a place completely surrounded by disks, yet not on the disks, thus isolated from the outside world by the flames.\n\nGiven the positions and sizes of the disks, determine whether such a hiding place exists.\n\n## Input\n\nThe first line contains an integer $N$, representing the number of disks.\nIn the following $N$ lines, the $i$th line contains three integers that describe disk $i$: the x-coordinate $x_i$, the y-coordinate $y_i$ of its center, and its radius $r_i$.\n\n## Output\n\nA single integer, $1$ if such a place exists, or $0$ otherwise.\n\n## Limits\n\n- $1 \\leqslant N \\leqslant 250$\n- $-10^9 \\leqslant x_i, y_i \\leqslant 10^9$ for all $i \\leqslant N$\n- $1 \\leqslant r_i \\leqslant 10^9$ for all $i \\leqslant N$\n- There are no three disks whose circular outlines intersect at a common point\n- Among all intersection points of the circular outlines of any two disks, the distance between any two intersection points is greater than or equal to 1\n- There are no two disks whose circular outlines are tangent to each other (i.e., have exactly one intersection point)\n- For two disks whose circular outlines do not intersect, the distance between any point on the circular outline of one disk and any point on the circular outline of the other disk is always greater than or equal to 1\n\n## Sample Inputs and Outputs\n\n### Sample 1\n\n#### Input\n```\n4\n-6 0 8\n-4 10 7\n4 4 6\n8 14 2\n```\n\n#### Output\n```\n0\n```\n\n#### Explanation\nIn this sample, there isn't any place that is completely surrounded by disks, yet not on the disks.\n\n### Sample 2\n\n#### Input\n```\n5\n4 -2 5\n-4 -2 5\n-8 8 8\n4 6 5\n-6 4 2\n```\n\n#### Output\n```\n1\n```\n\n#### Explanation\nIn this sample, $(-0.5, 3)$ is one of the places we can hide. It is surrounded by disks, yet not on the disks. Note that although all the inputs are integers, the hiding place does not necessarily have to be an integer point.\n\n### Sample 3\n\n#### Input\n```\n3\n420 580 230\n200 200 200\n600 200 210\n```\n\n#### Output\n```\n0\n```\n\n#### Explanation\nIn this sample, there isn't any place that is completely surrounded by disks, yet not on the disks.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2024_B", "prompt": "# Problem: Divine Gifting\n\nA celestial scroll, detailing Zeus's latest whim unfurls before Hermes: the next few millenia will be a period of divine gifting for mortals. Hermes, the messenger god, is tasked with delivering these gifts. Not just any gifts, mind you, but exquisitely crafted items from the Olympian workshops: a lyre that plays melodies of pure joy, a quill that writes words of profound wisdom, and so on. Each of the $N$ gifts is unique, and, to complicate matters, each has an optimal delivery date, a day when its magic would be most potent. But a divine law forbids delivering gifts before their optimal delivery day, lest mortals become complacent and entitled. Of course, all gifts must be delivered.\n\nAdding to the challenge, Hermes, despite being the fastest god on Olympus, is always extremely busy. Between managing the celestial postal service and refereeing chariot races, he knows that he can only dedicate at most $K$ days for the deliveries (each of those days, Hermes can deliver any number of gifts). Furthermore, late deliveries incur penalties: for each gift, the penalty is the square of the difference between its actual delivery day and its optimal delivery day. If a lyre is delivered a day or two late, a village might experience a few hours of slightly off-key music. A minor inconvenience, to be sure. However, if the lyre is delivered a month or a year late, the consequences are far more dire: a full year of discordant melodies, enough to drive even the most stoic musician to madness. The potential for chaos is immense.\n\nAnd this is where you come in, mortal friend. Hermes, with his myriad responsibilities, could use a helping hand. Can you help him plan his divine calendar by determining the best days for delivering the gifts, so as to minimize the sum of late delivery penalties?\n\n## Input\n\nOn the first line of the input, two space-separated integers:\n\n- $N$, the number of gifts;\n- $K$, the maximum number of days Hermes dedicates to gifting.\n\nOn the second line, $N$ space-separated integers $d_{i}$, representing the optimal delivery date of each gift.\n\n## Output\n\nA single line of space-separated integers, where the $i$-th element is the day when Hermes should deliver the $i$-th gift. If there are multiple optimal solutions, they will all be accepted.\n\n## Limits\n\n- $1 \\leq N \\leq 5,000$\n- $1 \\leq K \\leq 20$\n- $0 \\leq d_i \\leq 1,000,000$ for all $i \\leq N$\n\n## Sample Input\n\n```\n5 2\n50 0 51 10 50\n```\n\n## Sample Output\n\n```\n51 10 51 10 51\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2024_L", "prompt": "# Problem Statement\n\n## Problem Name\n\nDuring the summer break, fewer students are dwelling on campus, so this is the perfect time to add new books to the TU Delft library. These new books all have the same width, but they have varying heights. Because all existing bookcases are already full, the management board of the library has decided that they will add a new bookcase to display these new books.\n\nThe new bookcase has a number of shelves with varying heights. Each shelf in the bookcase can fit $x$ books. Since there may be some leftover space, the management board would also like to display some art pieces in this bookcase, at most one per shelf. An art piece will only fit on a shelf if there are at most $y$ books next to it, because the art pieces take up the same amount of space as $x-y$ books. As an example, Figure 1 shows a bookcase where three of the shelves have enough space for an art piece.\n\n![Illustration of Sample Input 1. Three shelves can have art pieces in the hatched areas, while still fitting all new books.](sample.pdf)\n\nThe management board wants you to find the largest number of shelves on which you can place an art piece, whilst also being able to fit all the new books on the shelves.\n\n## Input\n\nThe input consists of:\n- One line with four integers $n$, $m$, $x$, and $y$ ($1 \\leq n, m \\leq 10^5$, $1 \\leq y < x \\leq 1000$), the number of shelves, the number of books, the number of books that fit on a full shelf, and the number of books that fit on a shelf next to an art piece.\n- One line with $n$ integers $a$ ($1 \\leq a \\leq 10^9$), the heights of the shelves.\n- One line with $m$ integers $b$ ($1 \\leq b \\leq 10^9$), the heights of the books.\n\n## Output\n\nIf it is possible to fit all the $m$ books into the $n$ shelves, output the largest number of art pieces you can place. Otherwise, output \"impossible\".\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n4 8 4 2\n4 8 6 2\n1 2 3 5 7 7 8 8\n```\n\n### Sample Output 1\n```\n3\n```\n\n### Sample Input 2\n```\n4 11 3 2\n2 2 2 2\n1 1 1 1 1 1 1 1 1 1 1\n```\n\n### Sample Output 2\n```\n1\n```\n\n### Sample Input 3\n```\n2 10 3 2\n8 6\n4 2 1 3 6 2 1 3 4 5\n```\n\n### Sample Output 3\n```\nimpossible\n```\n\n### Sample Input 4\n```\n3 8 8 3\n7 9 4\n2 3 4 5 6 7 8 9\n```\n\n### Sample Output 4\n```\n3\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2023_J", "prompt": "### Problem: Olympic Goodies\n\n**Time limit:** 0.25 second\n\nFreshly arrived on the market, retailer YAOGS (Yet Another Olympic Goodies Seller) sells very expensive Olympics-themed items. To make themselves better known to the public, they half-heartedly decide to give away some of these items via a contest: the first person to answer correctly the question \"How many circles are there in the Olympic Games logo?\" can thus gain up to $P$ very expensive but equally valued items.\n\nTo spice things up (and spend less), YAOGS however opts for an additional challenge, as follows. The $P$ available items are positioned along some, but possibly not all of the alleys of YAOGS's headquarters; each alley can thus contain 0, 1, or more items. For reasons unknown, these alleys form a connected, undirected, acyclic graph (i.e., a tree) with $N$ nodes, numbered from 0 to $N - 1$.\n\nThe winner knows $N$ but has no idea about either the tree structure or the items' placement. Once goodies are placed, her task is to choose a start node $m$ and an end node $n$. She can then collect all the items on the (unique) path from $m$ to $n$ in the tree.\n\nYAOGS decides to cleverly place the goodies so that they minimize the maximum number of items that can possibly be collected. Assuming they properly carry out this task, what is the maximum number of items the winner can collect?\n\n**Input:**\nEach line contains two space-separated integers. The first line contains the numbers $N$ and $P$. Then follow $N - 1$ lines; the $k$-th such line contains two integers $a_k$ and $b_k$, meaning that there is an edge between the nodes $a_k$ and $b_k$ of the tree.\n\n**Output:**\nThe output should contain a single line, consisting of a single integer: the maximum number of items that can be collected by the winner.\n\n**Limits:**\n- $1 \\leq N \\leq 100000$\n- $1 \\leq P \\leq 100000$\n- $0 \\leq a_k \\leq N - 1$ and $0 \\leq b_k \\leq N - 1$ for all $k \\leq N - 1$\n- The set of edges in the input file describes a valid tree structure.\n\n**Sample Input:**\n```\n5 5\n0 1\n0 2\n2 3\n2 4\n```\n\n**Sample Output:**\n```\n4\n```\n\n**Sample Explanation:**\nFor the tree in the sample input, an optimal item placement by YAOGS guarantees that the winner cannot collect more than four items. The figures below show two possible item placements to achieve this optimality. In the first one, the four items may be collected by choosing, for instance, nodes 1 and 3. In the second one, the four items may be collected by choosing, for instance, nodes 0 and 4.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2024_H", "prompt": "# Problem: H: The King of SWERC\n\nThat's it! After years of research, you finally managed to find who was the king of the infamous South Western Egyptian River City (SWERC)!\n\nWell, not exactly. You have found the actual votes. But considering that the person who got the most votes got elected, and considering that there wasn't a tie for first place, can your code deduce who was the actual king of SWERC?\n\n## Input\n\nThe first line of the input is an integer, $N$, the number of votes. The next $N$ lines describe the votes, and each contains a name $V_i$ in capital English letters, without spaces.\n\nIt is guaranteed one name appears strictly more than the others.\n\n## Output\n\nThe output should contain a single string, the name of the king of SWERC.\n\n## Limits\n\n- $1 \\leqslant N \\leqslant 500$.\n- $1 \\leqslant |V_i| \\leqslant 20$, for $i = 1, \\ldots, N$.\n\n## Sample Input 1\n\n```\n1\nRAMSES\n```\n\n## Sample Output 1\n\n```\nRAMSES\n```\n\n## Sample Input 2\n\n```\n4\nJON\nJOFFREY\nTYWIN\nJON\n```\n\n## Sample Output 2\n\n```\nJON\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2023_D", "prompt": "### Problem Statement\n\n**Problem:** Flag Performance\n\n**Time Limit:** 2 seconds\n\nYou are in charge of a team of sorted gymnastics. This new discipline involves teams of $N$ members. Each team member dresses with a different colour (a number from 1 to $N$) and holds a coloured flag. Flags have unique colours, also numbered from 1 to $N$. A performance consists of exactly $K$ steps. At each step, two members exchange their flags. You are free to choose the initial configuration of the flags. The only constraint is that, at the end of the performance, each participant must hold the flag corresponding to the colour of his outfit.\n\nBeing the team captain, you would like the performance to be as unpredictable as possible. You consider $T$ possible initial configurations of flags among the team members, and wonder: in how many ways can the team perform the task for each of these initial configurations?\n\nFor each of the given $T$ initial configurations, compute the number of possible ways to do the performance. As the answers may be very large, return them modulo the prime number $1{,}000{,}000{,}007$.\n\n### Input\n\nEach line consists of space-separated integers. The first input line contains the numbers $N$, $K$, and $T$. Then follow $T$ lines. The $k$-th such line consists of $N$ distinct space-separated integers $C_{k,1}, C_{k,2}, \\ldots, C_{k,N}$, representing the $k$-th initial configuration of flags among team members. Here, $C_{k,j}$ is the colour number of the flag initially in the hands of the team member whose outfit colour is $j$.\n\n### Output\n\nThe output should contain $T$ lines. The $k$-th such line should consist of a single number: the number of possible sequences of exchanges that start from the $k$-th configuration and satisfy the constraints listed above, modulo $1{,}000{,}000{,}007$.\n\n### Limits\n\n- $2 \\leq N \\leq 30$\n- $1 \\leq K \\leq 50$\n- $1 \\leq T \\leq 10{,}000$\n\n### Sample Input 1\n\n```\n4 2 1\n4 1 2 3\n```\n\n### Sample Output 1\n\n```\n0\n```\n\n### Sample Explanation 1\n\nIt is impossible to sort the flags with two exchanges.\n\n### Sample Input 2\n\n```\n4 3 1\n4 1 2 3\n```\n\n### Sample Output 2\n\n```\n16\n```\n\n### Sample Input 3\n\n```\n6 15 10\n5 6 1 2 4 3\n2 4 1 6 5 3\n4 1 3 6 5 2\n1 3 2 4 5 6\n4 5 6 1 2 3\n1 2 5 3 6 4\n6 4 2 3 1 5\n3 6 4 1 2 5\n4 5 1 2 6 3\n6 1 4 3 2 5\n```\n\n### Sample Output 3\n\n```\n310571736\n0\n745108126\n996135367\n597596468\n745108126\n0\n0\n310571736\n0\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2023_D", "prompt": "# Problem: Date Picker\n\nThe NWERC is coming up and your agenda is filling up with meetings. One of your teammates wants to plan a meeting, and asks for your input. However, instead of asking you for your exact agenda, you have to fill out two separate polls: one for indicating which days you are available, and one for the hours!\n\nAs a computer scientist, you plan your meetings only on whole hours and each meeting takes an integer number of hours. Therefore, your agenda can be modelled as a matrix of $\\days$ rows (days), and $\\hours$ columns (hours). Each cell in this matrix is either `\\texttt{.}' or `\\texttt{x}', meaning that hour of that day you are either free or have a meeting, respectively.\n\nYou have to pick at least $d$ days in the first poll and $h$ hours in the second poll, and we assume the meeting will take place on any of your picked hour/day combinations with equal probability. What is the probability that you can attend the meeting if you fill in the polls optimally?\n\n## Input\nThe input consists of:\n- $\\days$ lines with $\\hours$ characters, each character being either `\\texttt{.}' or `\\texttt{x}', with `\\texttt{.}' indicating the time slots you are available.\n- One line with two integers $d$ and $h$ ($1 \\leq d \\leq \\days$, $1 \\leq h \\leq \\hours$), the minimum number of days and hours you have to fill in.\n\n## Output\nOutput the probability that you are available at the chosen meeting time.\n\nYour answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\nxxxxxx..xx..xxxxxxxxxxxx\nxxxxxxxxxxxxx....xxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxx..xx..xxxxxxxxxxxx\nxxxxxxxxxxxxx...x..xxxxx\nxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxx\n2 5\n```\n\n## Sample Output 1\n```\n0.8\n```\n\n## Sample Input 2\n```\nxxxxxxxxx.....x...xxxxxx\nxxxxxxxx..x...x...xxxxxx\nxxxxxxxx......x...x.xxxx\nxxxxxxxx...xxxxxxxxxxxxx\nxxxxxxxx...xxxxxxxxxxxxx\nxxxxxxxx...xxxxxxxx.xxxx\n......xxxxxxxxxxxxxxxxxx\n3 8\n```\n\n## Sample Output 2\n```\n0.958333333333333\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2023_C", "prompt": "### Metro Quiz\n\n**Time Limit:** 5 seconds\n\nTwo Olympics spectators are waiting in a queue. Each holds a copy of the metro map of Paris, and they devise a little game to kill time. First, player A thinks of a metro line (chosen uniformly at random among all metro lines) that player B needs to guess. To guess, player B repeatedly asks whether the line stops at a metro station of her choice, and player A answers truthfully. After enough questions, player B will typically know with certainty which metro line player A had in mind. Of course, player B wants to minimize the number of questions she needs to ask.\n\nYou are given the map of the $M$ metro lines (numbered from 1 to $M$), featuring a total of $N$ metro stations (numbered from 0 to $N - 1$) and indicating, for each line, those stations at which the line stops. Please compute the expected number of questions that player B needs to ask to find the answer, using the optimal strategy.\n\nIn other words, given a strategy $S$, let $Q_{s,j}$ be the number of questions asked by the strategy if the metro line in the solution is line $j$. Then, let\n$$ E_s = E[Q_s] = \\frac{1}{M} \\sum_{j=1}^{M} Q_{s,j} $$\nbe the expected value of $Q_{s,j}$ assuming that $j$ is uniformly chosen from the set of all metro lines. Your task is to compute $\\min_s E_s$.\n\nIf it is not always possible for player B to know which line player A had in mind with certainty, output \"not possible\".\n\n### Input\nThe first line contains the number $N$. The second line contains the number $M$. Then follow $M$ lines:\n- The $k$-th such line contains first a positive integer $n \\leq N$, then a space, and then $n$ space-separated integers $s_1, s_2, \\ldots, s_n$; these are the metro stations at which line $k$ stops. A line stops at a given station at most once.\n\n### Output\nThe output should contain a single line, consisting of a single number: the minimum expected number of questions that player B must ask in order to find the correct metro line, or \"not possible\" (in lowercase characters). Answers within $10^{-4}$ of the correct answer will be accepted.\n\n### Limits\n- $1 \\leq N \\leq 18$\n- $1 \\leq M \\leq 50$\n\n### Sample Input 1\n```\n5\n4\n3 0 3 4\n3 0 2 3\n3 2 3 4\n2 1 2\n```\n\n### Sample Output 1\n```\n2\n```\n\n### Sample Input 2\n```\n3\n3\n1 0\n1 1\n1 2\n```\n\n### Sample Output 2\n```\n1.66666666666667\n```\n\n### Sample Explanation 2\nAsk the first question about station 0: this is optimal by symmetry of the problem. This lets us distinguish between line 1, which stops at station 0, and lines 2 and 3, which do not. If needed, ask a second question to distinguish between lines 2 and 3.\n\nPlayer B asks one question if the answer is line 1, and two questions otherwise. Thus, the expected number of questions she will ask is $\\frac{1 + 2 \\times 2}{3}$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2023_L", "prompt": "# Problem Statement\n\n## Lateral Damage\n\nYou are playing *Battleships* in a large ocean with large ships. More precisely, there is a large square grid of size at most $100 \\times 100$ and inside it are up to $10$ of the largest type of ship in Battleships -- the aircraft carrier -- which has a length of five tiles, placed either horizontally or vertically. The ships do not overlap, but they are allowed to be adjacent to each other. See Figure 1 for an example.\n\nUnfortunately, your opponent appears to bend the rules to their liking. It looks like they do not always determine the placement of their ships before you start shooting. You are not impressed by their attempt at cheating, and decide to try and win the game anyway.\n\nYour goal is to locate and sink all your opponent's aircraft carriers in at most $2500$ shots, that is, you must hit each of the five tiles of all their ships.\n\n![Illustration of Sample Interaction 1 after the first four shots were fired.](sample)\n\n## Interaction\n\nThis is an interactive problem. Your submission will be run against an *interactor*, which reads from the standard output of your submission and writes to the standard input of your submission. This interaction needs to follow a specific protocol:\n\n1. The interactor first sends one line with two integers $n$ and $k$ ($5 \\le n \\le 100$, $1 \\le k \\le 10$), the size of the grid and the number of ships. It is guaranteed that it is possible to place $k$ aircraft carriers in the grid without overlap.\n2. Then, your program needs to start firing shots. Each shot is fired by printing one line of the form `x y` ($1 \\le x, y \\le n$), indicating you shoot at position $(x, y)$.\n3. The interactor will respond with `hit` if the shot was a hit, `sunk` if the shot caused an aircraft carrier to sink, and `miss` otherwise. If you have shot the same location before, the response will be `miss`.\n4. Once you sink the last aircraft carrier, the interaction will stop and your program must exit.\n5. The interactor is adaptive: the positions of the ships may be determined during the interaction, and may depend on where you decide to shoot.\n6. Make sure you flush the buffer after each write.\n7. A testing tool is provided to help you develop your solution.\n8. Firing more than $2500$ shots will result in a wrong answer.\n\n## Sample Interaction\n\n### Input\n```\n7 2\n2 0 0\nh 1 3\nv 6 2\n```\n\n### Output\n```\n1 3\n6 2\n```\n\n### Explanation\n- The interactor sends the grid size $n = 7$ and the number of ships $k = 2$.\n- The first ship is placed horizontally at position $(1, 3)$.\n- The second ship is placed vertically at position $(6, 2)$.\n- Your program fires shots at positions $(1, 3)$ and $(6, 2)$, and the interactor responds accordingly.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2024_A", "prompt": "# Problem: Titanomachy\n\nIn ancient Greek mythology, it is believed that the Olympian gods acquired their power from a long-lasting war with the Titans.\n\nAfter some recent excavations, an archaeological team found manuscripts explaining how people thought this war happened.\n\nZeus, the leader of the Olympian gods, and Kronos, the leader of the Titans, each picked their best $N$ soldiers in order to fight.\n\nThen, the soldiers arranged themselves in two rows, one row containing only the Olympian gods, and the other containing the Titans, such that each soldier faced exactly one opponent.\n\nAt the beginning of the battle, each such pair $i$ ($1 \\leq i \\leq N$) of soldiers had a score, $A_i$, which is an integer representing which side of the war had the advantage. A positive number represented an advantage for Zeus and the Olympian gods, a negative number an advantage for the Titans.\n\nDuring the war, $Q$ events occurred. These events could be of two kinds: either the relative strength of all pairs of soldiers changed due to the actions of Zeus and Kronos (for example, breaking down mountains with lightning), or Zeus conducted a strategic assessment of his army's advantage.\n\nIn the first case, the same integer $X$ got added to every single $A_i$. If $X$ was greater than $0$, it meant that Zeus increased the strength of his army, while a negative value meant that the Titans increased their strength, and a value of $0$ meant that nothing changed.\n\nIn the second case, Zeus focused on an interval $[L,R]$ of soldiers ($1 \\leq L \\leq R \\leq N$): he considered every possible subinterval, that is, all $l, r$ such that $L \\leq l \\leq r \\leq R$, and computed the sum $A_l + A_{l+1} + \\cdots + A_r$ for each of them. He computed the maximum value $M$ of such sums over all possible subintervals, and declared that $V = \\max(M, 0)$ was the strategic assessment of his army's advantage.\n\nObviously, Zeus's wisdom allowed him to compute such values instantaneously, but unfortunately, he did not record them anywhere.\n\nYour task as a philologist is to provide the values of all the strategic assessments made by Zeus during the war.\n\n## Input\n\nThe first line of the input contains two space-separated integers $N$ and $Q$. The second line contains $N$ space-separated integers $A_i$, representing the state at the beginning of the war.\nThe following $Q$ lines describe the events of the war, in chronological order. Each of them is either:\n- The word `STRENGTH`, followed by a space and an integer $X$, meaning that the strength of an army changed.\n- The word `ASSESS` followed by space-separated integers $L$ and $R$, meaning that Zeus made a strategic assessment of his army's advantage by focusing on the interval $[L, R]$ ($1 \\leq L \\leq R \\leq N$).\n\n## Output\n\nFor every time Zeus made a strategic assessment of his army's advantage, and in the order they appear in the input, you must output one line with the value $V$ of each assessment.\n\n## Limits\n\n- $1 \\leq N \\leq 3 \\times 10^5$\n- $1 \\leq Q \\leq 3 \\times 10^5$\n- $-10^9 \\leq A_i \\leq 10^9$ for $i=1,\\dots,N$.\n- All $X$ integers are between $-10^9$ and $10^9$, inclusive.\n- At all times during the war, $-2 \\times 10^9 \\leq A_i \\leq 2 \\times 10^9$ for all $i=1,\\dots,N$ holds true.\n\n## Sample Input\n\n```\n4 6\n1 -2 3 4\nASSESS 1 4\nASSESS 1 2\nASSESS 2 2\nSTRENGTH 2\nASSESS 1 4\nASSESS 1 2\n```\n\n## Sample Output\n\n```\n7\n1\n0\n14\n3\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2022_J", "prompt": "# Problem J: Italian Data Centers\n## SWERC 2022-2023\n\n## Problem Statement\n\nAn Italian data center consists of a set of servers, each colored green, white, or red, and a set of wires connecting them. Each wire connects two distinct servers, and two servers are connected by at most one wire. Additionally, the data center is connected, meaning there is a way to transmit information between any two servers through a sequence of wires.\n\nTo judge all of the contestant submissions, SWERC has an Italian data center. Since the number of contestants doubles every year, the data center needs to grow to adapt to the extra load. To address this, SWERC builds a new data center based on the previous year's one by following these steps:\n\n- For each server $s$ in the old data center, the new data center contains two servers $s1$ and $s2$ of the same color as $s$. A wire is placed connecting the two servers $s1$ and $s2$.\n- For each wire connecting servers $s$ and $t$ in the old data center: if $s$ and $t$ have the same color, then a wire is placed in the new data center connecting $s1$ and $t1$ and another wire connecting $s2$ and $t2$; otherwise, a wire is placed in the new data center connecting $s1$ and $t2$ and another one connecting $s2$ and $t1$.\n\nOne can show that if the old data center is connected, then the new data center is also connected.\n\nYou are given the Italian data center that SWERC currently has, which contains $n$ servers (indexed by 1, 2, ..., $n$) and $m$ wires connecting them. The organization wants to know how good their data center will be after $k$ years, so you should determine the diameter of the data center SWERC will have in $k$ years. The diameter of the data center is the largest distance between any two servers, i.e., the shortest number of wires that have to be used to transmit something between the two servers.\n\n## Input\nThe first line contains three integers $n$, $m$, and $k$ ($2 \\leq n \\leq 100$, $n-1 \\leq m \\leq n(n-1)/2$, $0 \\leq k \\leq 100$) \u2014 the number of servers, the number of wires, and the number of years to consider.\nThe second line contains $n$ integers $c1, c2, \\ldots, cn$ ($1 \\leq ci \\leq 3$) \u2014 $ci$ is the color of server $i$ (where 1 stands for green, 2 for white, and 3 for red).\nEach of the next $m$ lines contains two integers $s_i$ and $t_i$ ($1 \\leq s_i, t_i \\leq n$) \u2014 the two servers the $i$-th wire connects.\n\nIt is guaranteed that the data center is connected, the endpoints of each wire are distinct, and that there are no repeated wires.\n\n## Output\nPrint the diameter of SWERC's data center after $k$ years.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n3 3 0\n1 2 3\n1 2\n2 3\n3 1\n```\n\n### Sample Output 1\n```\n1\n```\n\n### Explanation of Sample 1\nThe Italian data center is the following:\n- The distance between any pair of servers is 1, so the diameter is 1.\n\n### Sample Input 2\n```\n3 3 1\n1 2 3\n1 2\n2 3\n3 1\n```\n\n### Sample Output 2\n```\n2\n```\n\n### Explanation of Sample 2\nThe initial Italian data center is the one from the first sample.\nAfter one year, we obtain the following (where the numbers indicate which copy the server refers to):\n- Consider the highlighted servers. The distance between them is 2 and there is no pair of servers with a greater distance, so the diameter is 2.\n\n### Sample Input 3\n```\n3 3 2\n1 2 1\n1 2\n2 3\n3 1\n```\n\n### Sample Output 3\n```\n3\n```\n\n### Explanation of Sample 3\nThe data center after one year is the following:\n- After one more year:\n- Consider the highlighted servers. The distance between them is 3 and there is no pair of servers with a greater distance, so the diameter is 3.\n\n### Sample Input 4\n```\n8 14 100\n3 3 2 2 1 2 2 1\n2 7\n1 5\n7 8\n4 6\n2 8\n1 8\n2 6\n6 7\n1 6\n1 4\n3 5\n1 3\n4 5\n5 7\n```\n\n### Sample Output 4\n```\n53\n```\n\n### Explanation of Sample 4\nThe data center after 100 years has a diameter of 53.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2023_I", "prompt": "# Throwing Dice\n\n**Time Limit:** 1 second\n\nAlice and Bob are discussing penalty shoot-outs and their randomness: \"We might as well be throwing dice to determine the winner!\", Alice said. And so they started simulating penalty shoot-outs by each throwing dice, summing the points indicated on their dice, and comparing these sums. The player with the largest sum wins; in case both sums are equal, there is a tie.\n\nBut even in such situations, some player might have an edge over their opponent, depending on which dice they throw. Thus, just by looking at the dice they are about to throw, Alice and Bob want to determine who has the better edge.\n\nAlice has $M$ fair dice, with $A_1, A_2, \\ldots, A_M$ sides. For all integers $k$ and $l$ such that $1 \\leq k \\leq M$ and $1 \\leq l \\leq A_k$, the $k$-th die of Alice has a probability $1 / A_k$ of showing its face numbered $l$. Then, Alice's score is the sum of the numbers displayed by her $M$ dice. Similarly, Bob has $N$ fair dice, with $B_1, B_2, \\ldots, B_N$ sides.\n\nGiven these dice, Alice has a probability $P_A$ of having a strictly larger score than Bob, and Bob has a probability $P_B$ of having a strictly larger score than Alice. Which probability is the largest one?\n\n## Input\nThe input consists of three lines, each one containing space-separated integers:\n- The first line contains the numbers $M$ and $N$.\n- The second line contains the numbers $A_1, A_2, \\ldots, A_M$.\n- The third line contains the numbers $B_1, B_2, \\ldots, B_N$.\n\n## Output\nThe output should contain a single line, consisting of a single uppercase word:\n- `ALICE` if $P_A > P_B$,\n- `TIED` if $P_A = P_B$,\n- `BOB` if $P_A < P_B$.\n\n## Limits\n- $1 \\leq M \\leq 100000$\n- $1 \\leq N \\leq 100000$\n- $4 \\leq A_k \\leq 1000000000$ for all $k \\leq M$\n- $4 \\leq B_k \\leq 1000000000$ for all $k \\leq N$\n\n## Sample Input 1\n```\n8 1\n4 4 4 4 4 4 4 4\n6\n```\n\n## Sample Output 1\n```\nALICE\n```\n\n## Sample Explanation 1\nSince Alice has 8 dice, her score is always 8 or more; Bob's score is always 6 or less. Hence, Alice has a probability $P_A = 100\\%$ of beating Bob, and he has a probability $P_B = 0\\%$ of beating her. Consequently, $P_A > P_B$.\n\n## Sample Input 2\n```\n2 2\n6 4\n4 6\n```\n\n## Sample Output 2\n```\nTIED\n```\n\n## Sample Explanation 2\nAlice has a probability $P_A = 125/288$ of beating Bob; he also has a probability $P_B = 125/288$ of beating her.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "nwerc2022_E", "prompt": "# ETA\n\nYou want to design a level for a computer game. The level can be described as a connected undirected graph with vertices numbered from $1$ to $n$. In the game, the player's character is dropped at one of the $n$ vertices uniformly at random and their goal is to reach the exit located at vertex $1$ as quickly as possible. Traversing an edge takes exactly $1$ second.\n\nThe difficulty of the level is determined by the average optimal time to reach the exit. Given a target value for this average optimal time, construct a level so that this target value is reached. See the example below for an illustration.\n\n## Input\n\nThe input consists of:\n- One line with two coprime integers $a$ and $b$ ($1 \\le a, b \\le 1000$) separated by a `\\texttt{/}', giving the desired average optimal time to reach the exit as the fraction $\\frac{a}{b}$.\n\n## Output\n\nIf no connected graph with the average optimal time $\\frac{a}{b}$ to reach vertex $1$ exists, output `impossible`.\nOtherwise, output one such graph in the following format:\n- Two integers $n$ and $m$ ($1 \\le n, m \\le 10^6$), the number of vertices and the number of edges.\n- $m$ pairs of integers $u$ and $v$ ($1 \\le u, v \\le n$), indicating an edge between vertices $u$ and $v$.\n\nThe graph may include self loops and parallel edges. You are given that if there exists a valid graph, then there also exists one with $1 \\le n, m \\le 10^6$.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n1/2\n```\n\n### Sample Output 1\n```\n2 1\n1 2\n```\n\n### Sample Input 2\n```\n1/3\n```\n\n### Sample Output 2\n```\nimpossible\n```\n\n### Sample Input 3\n```\n7/4\n```\n\n### Sample Output 3\n```\n8 12\n1 2\n1 3\n2 3\n2 4\n3 5\n3 6\n4 5\n5 6\n4 7\n5 7\n4 8\n6 8\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2024_J", "prompt": "# Problem Statement\n\n## Given Problem\n\nBob was hired for a new job after last year's success of building an infinite wall. His first task is to set up multiple cranes on a new construction site. Each crane consists of a central tower with a horizontal beam (the *jib*) attached to the top that can freely rotate around the central tower. The towers have already been set up for Bob, at some fixed coordinates and with some fixed height. Only the jibs still need to be placed. However, Bob has to be careful with this:\n\n- The length of a jib may not exceed the height of its tower, as else the crane would simply topple over.\n- The length of a jib must be a positive integer number of metres.\n- No two cranes should be able to collide. Luckily, all the towers are of different height. Therefore, the only way two cranes could collide is if the jib of one tower crashed into the tower of another crane. Note that a jib touching the tower of another crane does not result in a crash.\n\nWith this in mind, Bob wants to maximize the area that can be reached with at least one of the cranes, that is, the area of points on the ground such that at least one of the jibs can be positioned above them through rotations. Which length should each of the jibs have so that Bob can maximize the covered area?\n\n## Input\n\nThe input consists of:\n- One line with one integer $n$ $(1 \\leq n \\leq 500)$, the number of cranes.\n- $n$ lines, each with three integers $x$, $y$, and $h$ $(0 \\leq x, y \\leq 10\\,000, 1 \\leq h \\leq 10\\,000)$, describing the position of the crane and its height in metres.\n\nIt is guaranteed that no two cranes are at the same position and that all heights are distinct.\n\n## Output\n\nFor each crane, output the positive integer length of its jib in metres, such that the covered area is maximized.\n\nIf there are multiple optimal solutions, you may output any one of them.\n\n## Sample Input and Output\n\n### Sample Input 1\n```\n3\n1 1 4\n4 1 5\n7 4 3\n```\n\n### Sample Output 1\n```\n5\n3\n```\n\n### Sample Input 2\n```\n3\n0 0 10\n4 6 8\n6 6 6\n```\n\n### Sample Output 2\n```\n10\n7\n1\n```\n\n### Sample Input 3\n```\n5\n2 6 2\n4 10 4\n5 6 6\n8 8 7\n10 2 8\n```\n\n### Sample Output 3\n```\n2\n4\n2\n6\n8\n```\n\n## Illustration of Sample Input 3\nThe number at the centre of each circle indicates the height of the crane at that position. The number at each arrow indicates the length of the jib for that crane.\n\n\\[\n\\begin{tikzpicture}[x=0.5cm,y=0.5cm]\n \\newcommand{\\addCircle}[5][]{\n \\begin{pgfonlayer}{background}\n \\fill[black,#1] (#2) circle (#4*0.5cm+0.2pt);\n \\end{pgfonlayer}\n \\fill[red!10,#1] (#2) circle (#4*0.5cm-0.2pt);\n \\begin{pgfonlayer}{foreground}\n \\draw[dashed,#1] (#2) circle (#4);\n \\fill[black] (#2) circle (2pt);\n \\node[anchor=north] at (#2) {#3};\n \\draw[line width=1.5pt,-stealth] (#2) -- ($(#2)+(#5:#4)$) node [midway, above, sloped] {#4};\n \\end{pgfonlayer}\n \\stepcounter{nextCircle}\n }\n \n \\addCircle{2,6}{2}{2}{200}\n \\addCircle{4,10}{4}{4}{160}\n \\addCircle{5,6}{6}{2}{330}\n \\addCircle{8,8}{7}{6}{-20}\n \\addCircle{10,2}{8}{8}{-20}\n\\end{tikzpicture}\n\\]\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2024_G", "prompt": "# Problem: G: Guess How the Ballet Will End\n\nIn ancient Greek theater, the chorus would often dance. The dances were a pleasure to watch; all the dancers on stage executed the same movements at the same time, going across the theater, left to right or right to left. Of course, no dancer could ever go past the borders of the scene. So if the instructions would have made them fall off the scene, they would simply have carried out the move until they reached the border and then stayed there until the next move. For instance, if the move said 5 steps to the right but the dancer only had space for two steps, he/she would have taken those two steps and would then have waited on the border for the next move.\n\nYou are excavating a theater and have found extraordinarily well-preserved papyri detailing the sequence of moves the dancers would make during many theater plays, a real treasure trove. The initial positions of the dancers are not known to you, since you have only found the papyri with the moves, and the rest of the instructions and the rest of the plays have been lost.\n\nThe instructions are a sequence of numbers, telling all the dancers to dance 3 steps to the left, 5 steps to the right, etc., all carrying out the same move at the same time. Adding a coordinate system to the scene, each dancer $i$ starts at the position $(X_i, i)$ and a move only impacts their $X$ coordinate (each dancer dances on his/her own line), so they cannot bump into each other. They also all move at the same speed; moving by $n$ steps means the same change of $X$ coordinate for all dancers, unless they hit the borders as explained above.\n\nYou have figured out that in some cases, because some dancers may need to cut some movements short due to the borders, it may happen that they will all end up in a perfect line (all at the same $X$ position) at the end of the dance. There are so many papyri that you have decided to write a program to find out if this is the case. Maybe you will learn interesting things about Greek dancing, depending on the number of plays where all the dancers end up all aligned.\n\n## Input\n\nOn the first two lines of the input:\n\n- $R$, an integer, the length of the scene. The valid $X$ positions of the dancers range from 0 (left of the scene) to $R$ (right of the scene). Going beyond that would make the dancers fall off the scene.\n- $N$, the number of movements the dancers shall carry out.\n\nOn the third line, $N$ integers $d_i$, separated by spaces, the signed lengths of the moves the dancers shall carry out (a positive number means the dancer is moving to the right, a negative number that he/she is moving to the left).\n\n## Output\n\nIf you can be sure that all the dancers will end up being aligned at the same $X$ position, a single integer, corresponding to the position (distance from the left of the scene) where all the dancers will end up at the end of the moves.\n\nOtherwise, output the string `uncertain`.\n\n## Limits\n\n- $1 \\leq R \\leq 10,000,000,000$\n- $1 \\leq N \\leq 1000$\n- $-10,000,000,000 \\leq d_i \\leq 10,000,000,000$\n\n## Sample Input/Output\n\n### Sample Input 1\n```\n100\n2\n110 -20\n```\n\n### Sample Output 1\n```\n80\n```\n\n### Sample Input 2\n```\n100\n1\n50\n```\n\n### Sample Output 2\n```\nuncertain\n```\n\n### Sample Input 3\n```\n100\n8\n50 30 -40 10 -30 -50 30 -10\n```\n\n### Sample Output 3\n```\n20\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2022_C", "prompt": "# Problem C: Another Wine Tasting Event\n**SWERC 2022-2023**\n\n## Problem Statement\n\nAfter the first successful edition, Gabriella has been asked to organize a second wine tasting event. There will be $2n - 1$ bottles of wine arranged in a row, each of which is either red wine or white wine.\n\nThis time, Gabriella has already chosen the type and order of all the bottles. The types of the wines are represented by a string $s$ of length $2n - 1$. For each $1 \\leq i \\leq 2n - 1$, it holds that $s_i = R$ if the $i$-th bottle is red wine, and $s_i = W$ if the $i$-th bottle is white wine.\n\nExactly $n$ critics have been invited to attend. The critics are numbered from $1$ to $n$. Just like last year, each critic $j$ wants to taste an interval of wines, that is, the bottles at positions $a_j, a_j + 1, \\ldots, b_j$ for some $1 \\leq a_j \\leq b_j \\leq 2n - 1$. Moreover, they have the following additional requirements:\n- Each of them wants to taste at least $n$ wines, that is, it must hold that $b_j - a_j + 1 \\geq n$.\n- No two critics must taste exactly the same wines, that is, if $j \\neq k$ it must hold that $a_j \\neq a_k$ or $b_j \\neq b_k$.\n\nGabriella knows that, since the event is held in a coastal region of Italy, critics are especially interested in the white wines, and don't care much about the red ones. (Indeed, white wine is perfect to accompany seafood.) Thus, to ensure fairness, she would like all critics to taste the same number of white wines.\n\nHelp Gabriella find an integer $\\ell$ (with $0 \\leq \\ell \\leq 2n - 1$) such that there exists a valid assignment of intervals to critics where each critic tastes exactly $\\ell$ white wines. It can be proved that at least one such $\\ell$ always exists.\n\n## Input\nThe first line contains the integer $n$ ($1 \\leq n \\leq 10^6$) \u2014 where $2n - 1$ is the number of bottles, and $n$ is the number of critics.\nThe second line contains a string $s$ of length $2n - 1$ that represents the arrangement of the wines. The $i$-th character of $s$ ($1 \\leq i \\leq 2n - 1$) is $R$ for a red wine and $W$ for a white wine.\n\n## Output\nPrint an integer $\\ell$ \u2014 the number of white wines that each critic will taste.\nIt can be proved that at least one solution exists. If multiple solutions exist, any of them will be accepted.\n\n## Samples\n\n### Sample Input 1\n```\n5\nRWWRRRWWW\n```\n\n### Sample Output 1\n```\n2\n```\n\n### Explanation of Sample 1\nThere are 5 critics and $2 \\cdot 5 - 1 = 9$ bottles of wine. A possible set of intervals that makes each critic taste 2 white wines is the following: $[2, 6]$, $[1, 6]$, $[4, 8]$, $[1, 5]$, $[3, 7]$. Note that all intervals contain at least 5 bottles.\n\n### Sample Input 2\n```\n1\nR\n```\n\n### Sample Output 2\n```\n0\n```\n\n### Explanation of Sample 2\nThere is 1 critic and $2 \\cdot 1 - 1 = 1$ bottle of wine. The only possible interval is $[1, 1]$, which gives $\\ell = 0$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2022_I", "prompt": "# Problem I: Library Game\n## SWERC 2022-2023\n\n## Problem Statement\n\nAlessia and Bernardo are discovering the world of competitive programming through the books of their university library.\n\nThe library consists of $m$ sections numbered from 1 to $m$. Each section contains only books dedicated to a particular subject, and different sections correspond to different subjects. To prevent students from wandering in the library, the university has established a system of passes. Each pass has a length $y$ associated with it and allows access to an interval of $y$ consecutive sections in the library. During a visit, the student must choose exactly one book from one of these sections and leave the library. Each pass can be used only once.\n\nAt the moment, Alessia and Bernardo have $n$ passes of lengths $a_1, a_2, \\ldots, a_n$. They have different opinions on the best way to improve: Alessia thinks that it is important to study many different topics, while Bernardo believes that it is important to study deeply at least one topic. So, Alessia wants to use the $n$ passes to get $n$ books on distinct topics, while Bernardo would like to get at least two books on the same topic.\n\nThey have reached the following agreement: for each of the following $n$ days, Alessia will choose a pass of length $y$ among those which are still available and an interval of $y$ sections in the library, and Bernardo will go into the library and will take exactly one book from one of those sections.\n\nCan Bernardo manage to get at least two books on the same subject, or will Alessia be able to avoid it?\n\nYou should decide whether you want to be Alessia or Bernardo, and you have to fulfill the goal of your chosen character. The judge will impersonate the other character. Note that, even if at some moment Bernardo has already taken two books on the same subject, the interaction should go on until the end of the $n$ days.\n\n## Input\n\nThe first line contains two integers $n$ and $m$ ($1 \\leq n \\leq 100$, $n \\leq m \\leq 5000$) \u2014 the number of passes and the number of sections.\nThe second line contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq m$) \u2014 the lengths of the passes available.\n\n## Interaction\n\nFirst, you should print a line containing either the string `Alessia` or the string `Bernardo` \u2014 the character that you want to impersonate.\n\nThen, for each of the $n$ turns:\n- If you are taking the role of Alessia, print a single line consisting of two integers $y$ and $a$ ($1 \\leq a \\leq m - y + 1$) \u2014 you are choosing a pass of length $y$ and the interval of sections $[a, a + y - 1]$. Note that at least one pass of length $y$ must still be available. After this, read a single integer $b$ ($a \\leq b \\leq a + y - 1$) \u2014 the subject of the book selected by Bernardo.\n- If you are taking the role of Bernardo, read two integers $y$ and $a$ ($1 \\leq a \\leq m - y + 1$) \u2014 the length of the pass chosen by Alessia and the index of the first section of the interval. It is guaranteed that there is at least one pass of length $y$ available. Then, print a single integer $b$ ($a \\leq b \\leq a + y - 1$) \u2014 the subject from which you choose to take a book.\n\nIf one of your interactions is malformed, the interactor terminates immediately and your program receives the verdict `WRONG-ANSWER`. Otherwise, you will receive the verdict according to the game's criteria described above.\n\nAfter printing a line, do not forget to end the line and flush the output. Otherwise, you will get the verdict `TIME-LIMIT`. To flush the output, use:\n- `fflush(stdout)` in C\n- `fflush(stdout)`, `cout << flush` or `cout.flush()` in C++\n- `System.out.flush()` in Java and Kotlin\n- `sys.stdout.flush()` in Python\n\n## Samples\n\n### Sample Input 1\n```\n5 14\n3 7 2 3 10\n```\n\n### Sample Output 1\n```\nAlessia\n3 11\n13\n10 2\n9\n7 1\n4\n2 10\n10\n3 6\n7\n```\n\n### Explanation of Sample 1\nIt can be shown that Alessia can accomplish her goal. An example of interaction (after reading the input) follows:\n- Contestant (as Alessia) chooses $y = 3$ and $a = 11$.\n- Judge (as Bernardo) selects $b = 13$.\n- Contestant (as Alessia) chooses $y = 10$ and $a = 2$.\n- Judge (as Bernardo) selects $b = 9$.\n- Contestant (as Alessia) chooses $y = 7$ and $a = 1$.\n- Judge (as Bernardo) selects $b = 4$.\n- Contestant (as Alessia) chooses $y = 2$ and $a = 10$.\n- Judge (as Bernardo) selects $b = 10$.\n- Contestant (as Alessia) chooses $y = 3$ and $a = 6$.\n- Judge (as Bernardo) selects $b = 7$.\n\nThe program of the contestant wins because all the books chosen by Bernardo pertain to different topics. The actions performed by the contestant and the judge in this example of interaction may be non-optimal.\n\n### Sample Input 2\n```\n4 10\n4 1 6 4\n```\n\n### Sample Output 2\n```\nBernardo\n4 1\n4\n1 10\n10\n6 3\n4\n4 5\n8\n```\n\n### Explanation of Sample 2\nIt can be shown that Bernardo can manage to fulfill his goal. An example of interaction (after reading the input) follows:\n- Contestant (as Bernardo) selects $b = 4$.\n- Judge (as Alessia) chooses $y = 1$ and $a = 10$.\n- Contestant (as Bernardo) selects $b = 10$.\n- Judge (as Alessia) chooses $y = 6$ and $a = 3$.\n- Contestant (as Bernardo) selects $b = 4$.\n- Judge (as Alessia) chooses $y = 4$ and $a = 5$.\n- Contestant (as Bernardo) selects $b = 8$.\n\nThe program of the contestant wins because Bernardo has selected two books on topic number 4. The actions performed by the contestant and the judge in this example of interaction may be non-optimal.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2024_I", "prompt": "# Problem Statement\n\n## Counting Multiplicative Magic $3 \\times 3$ Squares\n\nEveryone knows that a $3 \\times 3$ magic square must meet two criteria:\n1. All nine numbers must be positive and distinct.\n2. The sums along all rows, columns, and diagonals are equal.\n\nEveryone, except maybe Matt Parker (Recreational mathematician, author, comedian, YouTube personality, and science communicator).\nHe wants to create a magic square of squares, that is, a magic square that also meets a third criterion:\n3. Each number is a square of a positive integer.\n\nHis \"result\" can be seen in the picture in the corner.\nAs you may notice, his square is not that magic...\nNot only do most of the values appear twice, it also has a diagonal with the wrong sum.\nTo be honest, apart from containing non-square values, there is not much that could make this square worse.\nWell, at least he tried!\n\nBut that is all in the past.\nAfter finding the *Parker Square*, he decided to completely ignore property 3 from now on and to instead give property 2 a new twist.\nHe now considers multiplicative magic squares, which are exactly like normal magic squares except that the *products* along all rows, columns, and diagonals have to be equal, instead of the sums.\nWho knows, Matt might even manage to find a proper multiplicative magic square in the future!\n\nWith this definition at hand, Matt wrote some terrible Python code -- his words, not ours -- to count the number of multiplicative magic $3 \\times 3$ squares where the product of the numbers in a single row, column, or diagonal is at most $n$.\nAs you may have guessed by now, his code is way too slow.\nTherefore, we task you to do the same, just more efficiently.\nGiven an integer $n$, count the number of multiplicative magic $3 \\times 3$ squares with product at most $n$.\n\n## Input\nThe input consists of:\n- One line with an integer $t$ ($1 \\leq t \\leq 10^5$), the number of test cases.\n- $t$ lines, each with an integer $n$ ($1 \\leq n \\leq 10^{18}$), the maximum product.\n\n## Output\nFor each test case, output the number of multiplicative magic squares with product at most $n$.\n\n## Sample Input\n```\n3\n500\n1000\n3000\n```\n\n## Sample Output\n```\n8\n16\n56\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2023_J", "prompt": "# Problem: Jogging Tour\n\nYou may know that in the 17th century, a group of Dutchmen founded a settlement called New Amsterdam on Manhattan Island that later went on to become New York City. Less well-known is the story of another group of Dutchmen that also moved over to America and founded a city called *New Delft*. Like its bigger counterpart, New Delft has been built on a grid made up of two sets of parallel streets that meet each other at a perpendicular angle.\n\nSome stroopwafel bakeries have already been built in New Delft, but none of the streets have been constructed. Your task is to lay out the grid of streets. For this, you need to decide on an orientation for the grid so that there are two orthogonal directions for the two types of streets. Once the orientation is fixed, you may build arbitrary streets, as long as each of them has one of the two given directions, as shown in the illustration. Each street can be traversed in either direction.\n\nThe street layout should be created in an optimal way for the annual *Stroopwafel Run*. This is an event in which a group of runners visits all the bakeries in some order of their choosing, and they may start and end their run at any point in the city. Your task is to come up with a grid layout that makes this shortest path as short as possible.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($2 \\le n \\le 12$), the number of stroopwafel bakeries in New Delft.\n- $n$ lines, each with two integers $x$ and $y$ ($0 \\le x, y \\le 10^6$), the coordinates of one of the bakeries.\n\nThe bakeries are at distinct coordinates, so for any $1 \\le i, j \\le n$ with $i \\neq j$, it holds that $(x_i, y_i) \\neq (x_j, y_j)$.\n\n## Output\n\nOutput the length of the shortest possible path that visits all bakeries in some order, assuming an optimal grid layout.\n\nYour answer should have an absolute or relative error of at most $10^{-6}$.\n\n### Sample Input 1\n\n```\n3\n0 1\n1 2\n3 0\n```\n\n### Sample Output 1\n\n```\n4.24264068712\n```\n\n### Sample Input 2\n\n```\n4\n1 4\n6 0\n5 3\n2 6\n```\n\n### Sample Output 2\n\n```\n11.1566387517\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2023_B", "prompt": "### Problem Statement: Supporting Everyone\n\n**Time Limit:** 0.25 second\n\nAlice is attending a sport event with many national teams and one thing is important to her: supporting every country. There are $N$ countries represented, and she has two ways to support a country: either have the flag drawn on her or have a pin with the name of the country. Alice has a list containing, for each country, the colours needed to make its flag. A total of $M$ colours may appear across all flags, and in Alice's list, each colour is conveniently represented as an integer between 1 and $M$.\n\nEach crayon and pin costs 1, but her budget is tight. Can you help her find the minimum she can spend to support everyone?\n\n### Input\nThe first line contains two space-separated numbers $N$ and $M$. Then follow $2N$ lines, grouped in pairs; the $(2i - 1)$th and $2i$th lines represent the $i$th country. More precisely, the $(2i-1)$th line contains a single integer $k_i$: the number of colours in the flag of the $i$th country. Then, the $2i$th line contains $k_i$ space-separated numbers $C_{i,1}, C_{i,2}, \\ldots, C_{i,k_i}$: these are the colours in the flag of the $i$th country.\n\n### Output\nThe output should contain a single line, consisting of a single number: the minimum amount Alice can spend on crayons and pins to represent every country.\n\n### Limits\n- $1 \\leq N \\leq 1000$\n- $1 \\leq M \\leq 100$\n- $1 \\leq k_i \\leq M$ for all $i \\leq N$\n- $1 \\leq C_{i,j} \\leq M$ for all $i \\leq N$ and $j \\leq k_i$\n- For all $i \\leq N$, the $M$ colour numbers $C_{i,j}$ are pairwise distinct.\n\n### Sample Input 1\n```\n7 6\n3\n1 4 5\n3\n1 4 5\n3\n1 4 5\n3\n3 4 5\n3\n3 4 5\n3\n3 4 5\n3\n2 5 6\n```\n\n### Sample Output 1\n```\n5\n```\n\n### Sample Explanation 1\nThe first three countries could be France, the Netherlands, and the Czech Republic, all represented by blue (1), white (4), and red (5). The next three countries could be Italy, Hungary, and Bulgaria, with green (3), white (4), and red (5). The last country could be Germany, with black (2), red (5), and yellow (6). The minimum cost is 5: we buy four crayons (for blue, green, white, and red) and one pin (for Germany).\n\n### Sample Input 2\n```\n8 12\n2\n7 9\n12\n1 2 3 4 5 6 7 8 9 10 11 12\n2\n7 9\n2\n7 9\n3\n3 4 11\n2\n7 9\n2\n7 9\n2\n7 9\n```\n\n### Sample Output 2\n```\n4\n```\n\n### Sample Explanation 2\nWe can buy two crayons for the colours 7 and 11 and buy two pins for a total cost of 4. All six countries with flag colours 7 (red) and 11 (white) could be Canada, Indonesia, Japan, Malta, Monaco, and Poland. The flag of Belize has 12 colours, including red and white, and the fifth country could be Botswana.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2022_D", "prompt": "# Problem: Delft Distance\n\nYou are currently in your hotel at the north-west corner of Delft, and want to go to the contest site at the university in the south-east corner of Delft. To get there, you have to go right through the historical centre of the city. Like Manhattan, the city consists of a grid of $h \\times w$ buildings. But unlike Manhattan, the city does not only contain square residential buildings but also some round medieval towers. All the square buildings are axis aligned with a side length of $10~\\text{m}$ and all round towers have a diameter of $10~\\text{m}$. There is just enough space for a small alley of negligible width between two neighbouring buildings.\n\nSince you are already late for the contest start, you need to find a shortest path from your hotel to the contest site. Fortunately, you have a map of the city. See the illustration below for an example.\n\n## Input\nThe input consists of:\n- One line with two integers $h$ and $w$ ($1 \\leq h, w \\leq 700$), the number of rows and the number of columns of buildings shown on the map of the city.\n- $h$ lines, each with $w$ characters which are either `O` (for round towers) or `X` (for square buildings) describing the shapes of the buildings.\n\nThe map is oriented with the north side up.\n\n## Output\nOutput the length of a shortest path from the north-west corner to the south-east corner of Delft in metres. Your answer may have a relative or absolute error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n3 5\nXOOXO\nOXOXO\nXXXXO\n```\n\n## Sample Output 1\n```\n71.4159265359\n```\n\n## Sample Input 2\n```\n1 4\nXOOX\n```\n\n## Sample Output 2\n```\n45.7079632679\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2023_G", "prompt": "# Galaxy Quest\n\nYou are travelling through the galaxy in your spaceship. There are $n$ planets in the galaxy, numbered from $1$ to $n$ and modelled as points in $3$-dimensional space.\n\nYou can travel between these planets along $m$ space highways, where each highway connects two planets along the straight line between them. Your engine can accelerate (or decelerate) at $1\\,\\text{m}/\\text{s}^2$, while using fuel at a rate of $1$ litre per second. There is no limit to how fast you can go, but you must always come to a complete standstill whenever you arrive at the planet at the end of a highway.\n\nIt is possible for a highway to pass through planets other than the ones it connects. However, as your spaceship is equipped with special hyperspace technology, it simply phases through these obstacles without any need of stopping. Another consequence of using this technology is that it is impossible to jump from one highway to another midway through: highways must always be travelled in full.\n\nYou need to fly several missions, in which you start at your home planet (with number $1$) and need to reach a given target planet within a given time limit. For each mission, determine whether it can be completed, and if so, find the least amount of fuel required to do so. As an example, the figure below shows the optimal route for the second mission of the first sample.\n\n![Illustration of Sample Input 1, showing highways in blue, and a route from planet $1$ to planet $3$. The green start of a highway indicates acceleration, and the red end indicates deceleration.](sample1.pdf)\n\n## Input\n\nThe input consists of:\n- One line with three integers $n$, $m$, and $q$ ($1 \\le n,m,q \\le 10^5$, $n \\ge 2$), where $n$ is the number of planets, $m$ is the number of space highways, and $q$ is the number of missions.\n- $n$ lines, each with three integers $x_i$, $y_i$, and $z_i$ ($\\left|x_i\\right|,\\left|y_i\\right|,\\left|z_i\\right| \\le 10^3$, $1 \\le i \\le n$), the coordinates of planet $i$.\n- $m$ lines, each with two integers $a$ and $b$ ($1 \\le a,b \\le n$, $a \\neq b$), describing a space highway that connects planets $a$ and $b$. It can be traversed in either direction.\n- $q$ lines, each with two integers $c$ and $t$ ($2 \\le c \\le n$, $1 \\le t \\le 10^3$), the target planet and time limit for each mission.\n\nThe $n$ planets are in distinct locations. Their coordinates are given in metres, and the time limits of the missions are given in seconds. No two highways connect the same pair of planets. For each mission, both the absolute and relative differences between the given time limit and the shortest possible completion time are at least $10^{-6}$.\n\n## Output\n\nFor each mission, output the least amount of fuel in litres required to reach the target location within the time limit. If the target location cannot be reached within the time limit, output `impossible`.\n\nYour answers should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n\n```\n4 4 3\n-30 0 0\n0 0 0\n50 0 0\n-30 10 0\n1 2\n2 3\n3 4\n4 1\n2 10\n3 25\n4 7\n```\n\n## Sample Output 1\n\n```\nimpossible\n19.0538441903\n4.0000000000\n```\n\n## Sample Input 2\n\n```\n4 2 5\n-3 0 2\n7 -9 -3\n4 4 -6\n8 -1 8\n1 2\n2 3\n2 1000\n2 100\n3 1000\n3 100\n4 1000\n```\n\n## Sample Output 2\n\n```\n0.0287058122\n0.2874671888\n0.1120998619\n1.1272896971\nimpossible\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2022_L", "prompt": "# Problem: Last Guess\n\nIf you spent any amount of time on social media at the end of last year, you are probably familiar with the word finding game *Wordle*, in which you need to find a five-letter English word using at most six guesses. After each guess, the letters in that guess are marked in either green, yellow, or black to provide information about the hidden word:\n\n- Green indicates that the letter is in the hidden word and appears in the same position.\n- Yellow indicates that the letter is in the hidden word, but in a different position.\n- Black indicates that the letter has no more occurrences in the hidden word.\n- If a letter appears more than once in the guessed word, first all the green markings for that letter are placed. Then, from left to right in the guessed word, yellow markings are placed for each remaining occurrence of the letter in the hidden word. Finally, black markings are placed for any surplus of the letter in the guessed word. See the example below for more clarity.\n\nIn this problem, we consider a variant of Wordle where you need to find a hidden word of length $\\ell$ in at most $g$ guesses. Additionally, there is *no* requirement that the hidden word or any of the guesses are words of any language; any string consisting of lowercase English letters is fine.\n\nIn your current play of this variant, you have already used all but one of your guesses, and now you need to find the hidden word using your final guess. Find any word that could be the hidden word based on the information you have.\n\n## Input\n\nThe input consists of:\n- One line with two integers $g$ and $\\ell$ ($2 \\leq g \\leq 500$, $1 \\leq \\ell \\leq 500$), the maximal number of guesses allowed in the game and the length of the word.\n- $g-1$ lines, each with two strings $s$ and $t$ of length $\\ell$, where $s$ is one of the guesses so far and $t$ gives the colours for that guess according to the rules above. The string $s$ consists of lowercase English letters (a-z) and the string $t$ consists of uppercase letters `G', `Y', and `B' indicating green, yellow, and black respectively.\n\nIt is guaranteed that the input describes a valid state of a Wordle game before the last guess and that a valid solution exists, in the form of a length $\\ell$ word consisting of lowercase English letters.\n\n## Output\n\nOutput a valid last guess that gives you a chance of winning.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Input 1\n\n```\n4 5\nreply YYGBB\nrefer BBBGG\npuppy YYGBB\n```\n\n## Sample Output 1\n\n```\nupper\n```\n\n## Sample Input 2\n\n```\n2 12\naabbccddeeff GGGYGBYYYBBB\n```\n\n## Sample Output 2\n\n```\naabdcbegdhij\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2023_H", "prompt": "### Problem Statement\n\n**Break a leg!**\n\nTime limit: 0.5 second\n\nFor the first time, breakdance will be featured in the Olympics. And you get to participate! Well, you get to participate in the jury... More precisely, you get to build the table in front of which the jury will be seated: still, that is an impressive feat, congratulations!\n\nActually, the top of the table is already built: it is plane, has constant width and constant density, and its shape consists of the interior of an $N$-sided non-crossing polygon $P_1 P_2 \\ldots P_N$ in which no three vertices are collinear (i.e., no line goes through three vertices or more). You have three table legs of the same length and negligible width. Your task is to place them at distinct corners of the table so that the table remains stable when standing on these legs. In other words, you must choose three vertices $P_i$, $P_j$, and $P_k$ of the polygon such that the center of gravity of the polygon lies in the interior of the triangle $P_i P_j P_k$ (and not on its boundary).\n\nIn how many different ways can you do this? If two ways of placing legs differ only by a permutation of the legs, they are not counted as different ways.\n\n### Input\n\nThe first line contains the number $N$. Then follow $N$ lines: the $i$-th of these lines contains two space-separated integers $x_i$ and $y_i$, which are the $x$-coordinate and the $y$-coordinate of the vertex $P_i$.\n\n### Output\n\nThe output should contain a single line, consisting of a single integer: the number of ways of placing legs such that the table remains stable.\n\n### Limits\n\n- $3 \\le N \\le 100000$\n- $-1000000 \\le x_i \\le 1000000$ and $-1000000 \\le y_i \\le 1000000$ for all $i \\le N$\n- Whenever $1 \\le i < j < k \\le N$, the vertices $P_i$, $P_j$, and $P_k$ are not collinear\n- The polygonal shape $P_1 P_2 \\ldots P_N$ is non-crossing\n\n### Sample Input/Output\n\n#### Sample Input 1\n```\n4\n0 0\n1 0\n1 1\n0 1\n```\n\n#### Sample Output 1\n```\n0\n```\n\n#### Sample Input 2\n```\n4\n0 0\n5 0\n6 6\n0 5\n```\n\n#### Sample Output 2\n```\n1\n```\n\n#### Sample Input 3\n```\n5\n0 0\n2 0\n2 20\n1 1\n0 20\n```\n\n#### Sample Output 3\n```\n5\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2024_I", "prompt": "# Problem: Divination\n\nIn Yinxu, the archaeological site of the late capital of the Shang Dynasty, there are $N$ divination papers written in oracle bone script, numbered $1, 2, ..., N$. Some papers may cite other papers, but no paper can cite itself. Additionally, there are no circular citations, meaning it's not possible to see the following situation: $A_1$ cites $A_2$, $A_2$ cites $A_3$, ..., $A_{K-1}$ cites $A_K$, $A_K$ cites $A_1$ (where $2 \\leqslant K \\leqslant N$).\n\nAs per myth, a complete set of divination papers can predict the wars and peace of the next century, and it should have a complete citation chain, i.e., $A_1$ cites $A_2$, $A_2$ cites $A_3$, ..., $A_{N-1}$ cites $A_N$, without any papers missing. Please determine whether these $N$ divination papers constitute a complete set.\n\n## Input\n\nThe first line contains an integer $N$, represents the number of papers.\nThen $N$ lines follow, the $i$th of them represents the citations of the $i$th paper: the first integer $c_i$ represents the number of its citations, followed by $c_i$ integers $p_{i,1}, p_{i,2}, ..., p_{i,{c_i}}$ that represent the papers that it cites.\n\n## Output\n\nA single integer, 1 if they constitute a complete set of divination papers, or 0 otherwise.\n\n## Limits\n\n- $2 \\leqslant N \\leqslant 100\\ 000$;\n- $0 \\leqslant c_i \\leqslant N-1$ for all $i \\leqslant N$;\n- $0 \\leqslant c_1 + c_2 + ... + c_N \\leqslant 500\\ 000$;\n- $1 \\leqslant p_{i,j} \\leqslant N$ for all $i \\leqslant N$ and $j \\leqslant {c_i}$.\n- $p_{i,j} \\neq i$ for all $i \\leqslant N$ and $j \\leqslant {c_i}$.\n\n## Sample Input 1\n\n```\n4\n0\n2 1 4\n2 2 4\n1 1\n```\n\n## Sample Output 1\n\n```\n1\n```\n\n## Sample Input 2\n\n```\n4\n0\n1 1\n2 2 4\n1 1\n```\n\n## Sample Output 2\n\n```\n0\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2022_C", "prompt": "# Problem: Circular Caramel Cookie\n\nStroopwafels -- two crispy round waffles with a grid-like pattern on top, separated by a thin layer of gooey and delicious caramel -- are simply the most amazing Dutch treat ever. Everybody loves them and your factory is known for making the best and the biggest stroopwafels in town... At least, until now.\n\nThis year, your archrival Rob had the audacity to open up another factory for stroopwafels and they have already announced that their stroopwafels will be even bigger than yours. Although the exact size of the new stroopwafels is a well-kept secret, your industrial spy managed to find out that the grid-like pattern of the stroopwafel consists of at most $s$ whole squares. You know for a fact that the area of each square is $1~\\text{cm}^2$ and that the centre point of the stroopwafel always contains the common corner of the four adjacent squares in the centre (i.e., the squares are aligned to a Cartesian grid), as shown in the figure below.\n\nNeedless to say, there is no way that you will let Rob outdo you and you plan on releasing a new edition of bigger stroopwafels. Since the production of bigger stroopwafels is more expensive, you naturally want to make them as small as possible. Thus, you are interested in the minimum radius of a stroopwafel with strictly more than $s$ squares.\n\n## Input\nThe input consists of:\n- One line with an integer $s$ ($1 \\leq s \\leq 10^9$), the number of whole squares Rob's stroopwafel has at most.\n\n## Output\nOutput the minimum radius in centimetres of a stroopwafel with strictly more than $s$ whole squares. Your answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n11\n```\n\n## Sample Output 1\n```\n2.2360679775\n```\n\n## Sample Input 2\n```\n59\n```\n\n## Sample Output 2\n```\n5.0000000000\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2023_E", "prompt": "# Exponentiation\n\nIn her spare time, Zoe develops an online calculator. Unfortunately, the calculator was targeted by a denial-of-service attack last week. The attacker created a lot of integer variables, exponentiated them with each other, and tried to do a bunch of comparisons. The huge integers were too much for the server to handle, so it crashed. Before Zoe fixes the issue, she decides to actually perform the calculations that the attacker requested.\n\nThere are $n$ integer variables $x_1, x_2, \\dots, x_n$. At the start, each variable is set to $2023$. You have to perform $m$ instructions of the following two types:\n- **Operations**, of the form `! $i$ $j$`, where $i \\neq j$. This means that $x_i$ gets set to $x_i^{x_j}$.\n- **Queries**, of the form `? $i$ $j$`, where $i \\neq j$. This means that you should print `>` if $x_i$ is greater than $x_j$, `=` if $x_i$ is equal to $x_j$, and `<` if $x_i$ is smaller than $x_j$.\n\nConsider the first sample. After the $5$ operations, the values of the variables are:\n\\begin{align*}\nx_1 &= \\left(2023^{2023}\\right)^{2023^{2023}}, \\\\\nx_2 &= \\left(2023^{2023^{2023}}\\right)^{2023}, \\\\\nx_3 &= 2023, \\\\\nx_4 &= 2023^{2023}.\n\\end{align*}\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $m$ ($2 \\leq n \\leq 1000$, $1 \\leq m \\leq 1000$), the number of variables and the number of instructions.\n- $m$ lines, each containing a character $c$ (either `!` or `?`) and two integers $i$ and $j$ ($1 \\leq i, j \\leq n$, $i \\neq j$), describing the instructions.\n\n### Sample Input 1\n```\n4 8\n! 1 4\n! 2 1\n! 4 3\n! 1 4\n! 2 3\n? 3 4\n? 2 4\n? 2 1\n```\n\n### Sample Output 1\n```\n<\n>\n=\n```\n\n### Sample Input 2\n```\n4 9\n! 2 4\n! 1 2\n? 3 1\n? 1 2\n! 2 3\n? 1 2\n! 1 3\n! 3 2\n? 1 3\n```\n\n### Sample Output 2\n```\n<\n>\n>\n<\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2022_K", "prompt": "# Problem: Kebab Pizza\n\nAlice loves pizza and plans to throw a pizza party for her birthday, where she will make one big, round pizza for all her guests. She knows that her friends are a bit special when it comes to pizza:\n- Julie does not want any vegetables but loves kebab meat on her pizza.\n- Katy would never eat pizza with cheese on top.\n- Alice herself is a huge fan of pineapple on pizza, while Mickey absolutely hates it.\n- Instead, he wants to put spaghetti on it, which everybody else finds weird.\nThe list goes on and on. Briefly put, it is absolutely impossible to accommodate everybody.\n\nAs a compromise, Alice decides to let each person choose two toppings for their pizza slice in advance. Each person will be happy if their slice has exactly their two chosen toppings and none of the others. Note that a person may choose the same topping twice, in which case they just get twice the amount of that topping.\n\nOn the day of her party, Alice discovers that the rolled out pizza dough takes up so much space on her kitchen counter that she can only prepare one kind of topping at a time. To optimise the workflow and to make sure that the pizza is ready in time for her party, she wants to take out each chosen kind of topping only once and then add it on a consecutive range of pizza slices. Note that the whole pizza forms a consecutive range of pizza slices in a circular fashion. Determine whether it is possible to prepare the pizza in this way while satisfying all the chosen topping combinations. See the illustration below for an example.\n\nIllustration of Sample Input 1, with two toppings numbered on every slice in one possible solution. Note that each topping only occurs on a single range of pizza slices.\n\n## Input\nThe input consists of:\n- One line with two integers $n$ and $k$ ($3 \\leq n, k \\leq 10^5$), the number of pizza slices and the number of possible toppings which are numbered from $1$ to $k$.\n- $n$ lines, each with two integers $a$ and $b$ ($1 \\leq a, b \\leq k$), describing the toppings chosen by the $i$th person.\n\n## Output\nOutput `possible` if it is possible for Alice to select a consecutive range of pizza slices for each chosen topping such that the resulting pizza can be split into $n$ suitable slices. Otherwise, output `impossible`.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n7 6\n2 2\n3 6\n1 1\n1 5\n4 5\n6 6\n6 5\n```\n\n### Sample Output 1\n```\npossible\n```\n\n### Sample Input 2\n```\n5 5\n1 3\n1 5\n2 3\n2 5\n3 4\n```\n\n### Sample Output 2\n```\npossible\n```\n\n### Sample Input 3\n```\n6 7\n1 2\n2 3\n3 4\n4 5\n3 6\n6 7\n```\n\n### Sample Output 3\n```\nimpossible\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2024_L", "prompt": "# Problem L: The Charioteer\n\nAs you are studying ancient Greek mythology, you stumble upon the legend of Phaethon, son of Helios. After being recognized by Helios as his son, he asks him to drive his chariot. Despite the warnings of Helios that only he can control the horses, Helios obliges, giving Phaethon the control of the chariot.\n\nTragically, Phaethon loses control of the chariot, which gets too close to the Earth and burns it.\n\nHowever, you wonder if maybe the story could have ended differently. If Phaethon reaches the temple of Helios, then the chariot can be stopped by Helios himself. For that, you create a model that fits the story.\n\nGreece can be represented as a 2D infinite grid, with Phaethon and his chariot starting at coordinate $(0,0)$, facing the Ox axis in the direction of increasing X. The temple of Helios is placed in an unknown position $(X,Y)$ on this 2D grid. Initially, the velocity $V$ of the chariot is 1.\n\nAt each timestep, the following happens in order:\n1. Phaethon does one of the following 3 actions: turn the chariot left 90 degrees, continue facing front, or turn the chariot right 90 degrees;\n2. The chariot moves $V$ units in the direction it is facing;\n3. $V$ is increased by 1;\n4. The Oracle tells Phaethon the Manhattan distance between his position and the position of the temple of Helios.\n\nThe Manhattan distance between $(X1,Y1)$ and $(X2,Y2)$ is $|X1-X2|+|Y1-Y2|$.\n\nIf the velocity ever reaches $2 \\times 10^4$, the chariot gets uncontrolled and too close to the earth. If at the end of a step, the chariot is in $(X, Y)$, the chariot is stopped.\n\n## Input and Output\n\nThis is an interactive problem. As such, no initial input is provided in this problem, and you get to ask a question first.\n\nAt each step, you must print a line to act on the direction of the chariot. This line must follow the description `? c` followed by a newline, where `c` is either `L` to rotate counterclockwise, `R` to rotate clockwise, or `F` to keep the direction unchanged. If it does not respect this format, you will receive a WRONG-ANSWER verdict.\n\nAfter sending a line, you must always flush the output. Otherwise, you will get the verdict TIMELIMIT.\n\nThe Oracle then prints a single integer, that you can read on the standard input, denoting the Manhattan distance between your new position (after moving $V$ units in the specified direction) and the temple. $V$ is increased after updating your position.\n\nIf this distance is $0$, it means you arrived at the temple of Helios and thus should stop interaction immediately (exiting your program), receiving an ACCEPTED verdict.\n\nNotice that you must be in the temple after your move, just flying above the temple with the chariot does not count.\n\nIf your velocity ever reaches $2 \\times 10^4$, you will receive the verdict WRONG-ANSWER.\n\n## Limits\n\n- $|X| \\leq 10^6$\n- $|Y| \\leq 10^6$\n- $|V| \\leq 2 \\times 10^4$\n\n## Sample Interaction\n\nIn this section, to clarify what the input and output should be, `>` is printed before what your program should output, and `<` is printed before what your program can read on standard input. Do not include these characters in your real input/output.\n\nIn this example, the temple of Helios (whose position you must guess) is located at $X=1$, $Y=5$.\nThe left column is the I/O. The right column is the state of the chariot after the requested move happened.\n\n```\n> ? F\n< 5\n> ? L\n< 3\n> ? F\n< 0\n```\n\n| Output | State of the Chariot |\n|--------|----------------------|\n| `> ? F` | Chariot moves to (1, 0), orientation = right, $V$ = 2 |\n| `< 5` | Distance from (1,0) to (1,5) is 5 |\n| `> ? L` | Chariot moves to (1, 2), orientation = up, $V$ = 3 |\n| `< 3` | Distance from (1,2) to (1,5) is 3 |\n| `> ? F` | Chariot moves to (1, 5), orientation = up, $V$ = 4 |\n| `< 0` | Success |\n\nAn interactive Python script where you can enter commands and see how the judge would respond is also available on the Web version of this problem.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2024_F", "prompt": "# Problem: Yaxchil\u00e1n Maze\n\n## Problem Statement\n\nYears spent deciphering Mayan glyphs had led Dr. Wood, a famous archeologist, to this very moment: inside a chamber of the Yaxchil\u00e1n maze, in the middle of the Lacandon Jungle, the last undiscovered Mayan codex appeared before her. It was beautiful, protected by jaguar pelt and adorned with jade. However, as soon as she touched it, all the corridors of the maze closed. She was now a prisoner of the maze. Worse, she was not alone, but had a full team of archeologists with her that were also held prisoner in different chambers of the maze.\n\nAs she examined the codex, a series of intricate diagrams caught her eye. They depicted the maze, its corridors morphing into different configurations, each aligned with a specific position of the sun. Another set of diagrams showed intricately carved holes in the walls together with a chilling depiction of a giant wasp. A realization dawned on her \u2013 the Maya had designed this maze to change with the sun's position, and some chambers were booby-trapped with a giant nest of deadly wasps.\n\nNamely, there are $N$ chambers in the maze numbered $0, \\ldots, N-1$. Dr. Wood and the members of her team start in chambers $0, 1, \\ldots, A - 1$ (one person per chamber). There are $E$ exits: chambers $N - E, \\ldots, N - 1$. Initially, the maze contains no open corridors. At each hour (00:00, 01:00, 02:00, and so on, represented by integers 0, 1, 2, and so on), a new corridor between two chambers opens. This corridor stays open for exactly $M$ hours minus one minute. Corridors are bi-directional.\n\nAmong the $N$ chambers, $B$ are booby-trapped. The trap of a chamber triggers as soon as it is connected to at least $K$ other chambers. When triggered, a gigantic swarm of deadly wasps appears in the chamber and immediately spreads to all chambers connected to the booby-trapped chamber. Furthermore, as time progresses, the wasps never disappear from a chamber, and worse, they continue to spread instantaneously from chambers that contain wasps to newly connected chambers. Two chambers are considered connected at a given time when there exists a path of one or multiple open corridors that allows going from one chamber to the other.\n\nThanks to the codex and to her knowledge of the maze (and smartphones!), Dr. Wood and each member of her team have full information on the maze at hour 0, including all future events: in particular, they each know where they are in the maze, where corridors lead to, the exact time, when corridors open and close and which chambers they connect, the location of the booby-traps, exits, $K$, and can deduce which chambers are or will be filled with deadly wasps. All the archeologists can move freely and independently from each other using the open corridors at all times. They run fast and can move to any reachable chamber in less than 59 minutes. If an archeologist ends up in a chamber filled with deadly wasps, he or she dies and cannot exit the maze.\n\nThe exit chambers behave as the other chambers: they can be filled with wasps and be booby-trapped. As soon as an archeologist reaches any exit chamber not filled with wasps, she or he exits the maze and its dangers. Can you tell the earliest time when each archeologist can exit the maze?\n\n## Input\n\n- The first line contains the integer $A$, the number of archeologists.\n- The second line contains the integer $N$.\n- The third line contains the integer $M$.\n- The fourth line contains the integer $E$.\n- The fifth line contains the integer $T$, the number of hours at which corridors open.\n- The sixth line contains $B$, followed by the list of the $B$ space-separated booby-trapped chambers $b_i$.\n- The seventh line contains $K$.\n- In the next $T$ lines, line $t$ contains two space-separated integers $u_t, v_t$ representing a corridor that opens at hour $t$ and connects chambers $u_t$ and $v_t$. $t$ goes from $0$ to $T - 1$ (inclusive). Multiple corridors can connect the same two chambers. A corridor can connect a chamber to itself.\n\n## Output\n\nThe output should contain $A$ lines. The $i$-th line represents the $i$-th archeologist. If the $i$-th archeologist can exit the maze, it should be the integer representing the earliest hour at which she or he can exit. Otherwise, it should be \"IMPOSSIBLE\" (without quotes).\n\n## Limits\n\n- $1 \\leqslant A \\leqslant 50$\n- $2 \\leqslant N \\leqslant 50\\,000$\n- $1 \\leqslant M \\leqslant 100\\,000$\n- $1 \\leqslant E \\leqslant 100$\n- $A + E \\leqslant N$ (no chamber is both a starting chamber and an exit chamber)\n- $1 \\leqslant T \\leqslant 500\\,000$\n- $0 \\leqslant B \\leqslant N$\n- $0 \\leqslant b_i < N$ for $i=0,\\dots, B-1$\n- The $b_i$'s are unique\n- $0 \\leqslant K < N$\n- $0 \\leqslant u_t < N$ for $t=0,\\dots, T-1$\n- $0 \\leqslant v_t < N$ for $t=0,\\dots, T-1$\n\n## Sample Input 1\n\n```plaintext\n1\n5\n1\n1\n5\n0\n0\n0 1\n0 2\n2 3\n2 4\n0 4\n```\n\n## Sample Output 1\n\n```plaintext\n3\n```\n\n## Sample Input 2\n\n```plaintext\n1\n4\n1\n1\n3\n0\n0\n0 1\n2 3\n1 2\n```\n\n## Sample Output 2\n\n```plaintext\nIMPOSSIBLE\n```\n\n## Sample Input 3\n\n```plaintext\n4\n10\n2\n2\n11\n2 3 7\n2\n0 1\n1 2\n2 3\n1 4\n4 9\n5 6\n0 6\n5 7\n1 6\n7 8\n6 8\n```\n\n## Sample Output 3\n\n```plaintext\n9\n9\n9\nIMPOSSIBLE\n```\n\n## Explanation\n\n### Sample 1\n\nThere are no booby-traps. Dr. Wood (the only archeologist) starts at $0$ and the exit is $4$. After the corridor `0 2` opens, she goes from chamber $0$ to chamber $2$. She stays there until the corridor `2 4` opens, which allows her to reach chamber $4$ and exit at hour $3$.\n\n### Sample 2\n\nThere are no booby-traps. Dr. Wood (the only archeologist) starts at $0$ and the exit is $3$. Unfortunately, Dr. Wood can only reach chamber $2$ after the corridor `2 3` leading to the exit closed. She cannot exit the maze.\n\n### Sample 3\n\nThe fastest path to an exit for the first archeologist starting at 0 is to go to chamber 5 at hour $6$ using corridors `0 6` and `5 6`, then to chamber 7 at hour $7$ using the corridor `5 7`, and finally reach chamber 8 (an exit) at hour 9 using the corridor `7 8`. Note that chamber 7 is booby-trapped, but the wasps only appear at hour 10, after the first archeologist exited the maze.\n\nThe second archeologist starting at 1 can move to chamber 0 at hour 0 and then follow the path of the first archeologist.\n\nThe third archeologist starting at 2 can move to chamber 0 at hour 1 and then follow the first two archeologists.\n\nThe last archeologist starting at 3 is killed by the wasps at hour 2.\n\nAt the end, chambers 1, 2, 3, 4, 6, 7, 8, 9 are filled with wasps.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2023_C", "prompt": "# Chair Dance\n\nIn a deterministic version of *Musical Chairs* (you do not need to know the original game, but you can try to play it after the contest is over), there are $n$ chairs placed in a circle. The chairs are numbered from $1$ to $n$ in clockwise order. Initially, the $i$th player sits on the $i$th chair. During the game, the game master gives commands to all players at once.\n\nThe first type of command tells each player to move $x$ chairs farther in clockwise order, so they must move from chair $i$ to chair $i + x$.\n\nThe second type of command tells each player to move from chair $i$ to chair $i \\cdot x$. Both these calculations are done modulo $n$, where a remainder of $0$ corresponds to chair $n$.\n\nIf two or more people want to move to the same chair, then the player needing to travel the least in clockwise direction to reach the chair gets to take the seat, and the other players trying to reach the same chair are out of the game. This is illustrated in Figure 1, where the larger circles represent the chairs and their numbers are written on their inside. The smaller circles represent the players. The next command (`* 10`) tells player $10$ (now on seat $11$) and player $4$ (now on seat $5$) to move to chair $2$. However, since player $10$ needs to travel less, this player gets to take the seat. Note that the other $10$ players will also move to some other chairs, but this is omitted from the figure for the sake of readability.\n\nThe jury wasted most of their free time designing this game and now need to go back to work. Fortunately, the game is deterministic, so you can play the game without the help of the jury.\n\n## Input\n\nThe input consists of:\n\n- One line with two integers $n$ and $q$ ($2 \\leq n, q \\leq 5 \\cdot 10^5$), the number of chairs and the number of commands.\n- $q$ lines, each containing one of three command types:\n - `+ $x$`: The player on chair $i$ moves to chair $i + x$.\n - `* $x$`: The player on chair $i$ moves to chair $i \\cdot x$.\n - `? $x$`: Tell us the number of the player on chair $x$.\n\nAll of the values $x$ will satisfy $1 \\leq x \\leq n$.\n\n## Output\n\nFor each command of type `?`, output the number of the player on the requested chair. If the chair is currently empty, output $-1$ instead.\n\n## Sample Input 1\n\n```plaintext\n12 10\n? 12\n+ 1\n? 12\n* 10\n? 2\n* 5\n? 2\n* 6\n? 1\n? 12\n```\n\n## Sample Output 1\n\n```plaintext\n12\n11\n10\n6\n-1\n11\n```\n\n## Sample Input 2\n\n```plaintext\n32 11\n* 6\n? 8\n* 6\n+ 31\n* 28\n? 4\n+ 1\n* 2\n+ 1\n* 3\n? 1\n```\n\n## Sample Output 2\n\n```plaintext\n28\n32\n32\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2023_G", "prompt": "### Problem Statement: Favourite Dish\n\n**Time Limit:** 4 seconds\n\nFrance is a country of gastronomy. For a dish, both the taste and plating are important. Nevertheless, when different people evaluate a dish, some focus more on taste and some focus more on plating. At the Olympic Village dining hall, there are $N$ dishes, numbered from 1 to $N$; each dish has a score on its taste and a score on its plating. There are also $M$ persons, numbered from 1 to $M$; each person has a weight on taste and a weight on plating. One person's final score of a dish is the weighted average of the dish's scores on taste and plating.\n\nThe chefs at the Olympics want to provide everyone with their favourite dish on the evening of the closing ceremony. Your task is to calculate everyone's favourite dish. If multiple dishes tie for the highest score as a person's favourite, choose the one with the smallest number.\n\n**Input:**\n- The first line contains two space-separated integers $N$ and $M$.\n- The next $N$ lines each contain two integers $t_k$ and $p_k$, which are the scores of the dish $k$ on taste and on plating.\n- The next $M$ lines each contain two integers $T_e$ and $P_e$, which are the weights of person $e$ on taste and on plating.\n\n**Output:**\n- The output should contain $M$ lines. The $a$-th such line should contain one number: the number of the favourite dish of person $a$.\n\n**Constraints:**\n- $1 \\leq N \\leq 500000$\n- $1 \\leq M \\leq 500000$\n- $0 \\leq t_k \\leq 1000000$, $0 \\leq p_k \\leq 1000000$, and $(t_k, p_k) \\neq (0, 0)$ for all $k \\leq N$\n- $0 \\leq T_e \\leq 1000000$, $0 \\leq P_e \\leq 1000000$, and $(T_e, P_e) \\neq (0, 0)$ for all $e \\leq M$\n- The $N$ pairs $(t_k, p_k)$ are pairwise distinct.\n- The $M$ pairs $(T_e, P_e)$ are pairwise distinct.\n\n**Sample Input 1:**\n```\n4 3\n2 5\n3 4\n4 2\n1 6\n6 4\n2 8\n5 5\n```\n\n**Sample Output 1:**\n```\n2\n4\n1\n```\n\n**Sample Explanation 1:**\nHere is the score table for each person on each dish. Each person's favourite dish is indicated with a *:\n- Person 1: \n - Dish 1: $2 \\times 6 + 5 \\times 4 = 32$\n - Dish 2: $3 \\times 6 + 4 \\times 4 = 38$\n - Dish 3: $4 \\times 6 + 2 \\times 4 = 32$\n - Dish 4: $1 \\times 6 + 6 \\times 4 = 30$\n - Favourite: Dish 2\n- Person 2: \n - Dish 1: $2 \\times 2 + 5 \\times 8 = 44$\n - Dish 2: $3 \\times 2 + 4 \\times 8 = 38$\n - Dish 3: $4 \\times 2 + 2 \\times 8 = 24$\n - Dish 4: $1 \\times 2 + 6 \\times 8 = 50$\n - Favourite: Dish 4\n- Person 3: \n - Dish 1: $2 \\times 5 + 5 \\times 5 = 35$\n - Dish 2: $3 \\times 5 + 4 \\times 5 = 35$\n - Dish 3: $4 \\times 5 + 2 \\times 5 = 30$\n - Dish 4: $1 \\times 5 + 6 \\times 5 = 35$\n - Favourite: Dish 1 (smallest number among the tied dishes)\n\n**Sample Input 2:**\n```\n3 4\n1 0\n0 2\n0 1\n1 1\n2 2\n2 1\n1 0\n```\n\n**Sample Output 2:**\n```\n2\n2\n1\n1\n```\n\n**Sample Explanation 2:**\nHere is the score table for each person on each dish. Each person's favourite dish is indicated with a *:\n- Person 1: \n - Dish 1: $1 \\times 1 + 0 \\times 1 = 1$\n - Dish 2: $0 \\times 1 + 2 \\times 1 = 2$\n - Dish 3: $0 \\times 1 + 1 \\times 1 = 1$\n - Favourite: Dish 2\n- Person 2: \n - Dish 1: $1 \\times 2 + 0 \\times 2 = 2$\n - Dish 2: $0 \\times 2 + 2 \\times 2 = 4$\n - Dish 3: $0 \\times 2 + 1 \\times 2 = 2$\n - Favourite: Dish 2\n- Person 3: \n - Dish 1: $1 \\times 2 + 0 \\times 1 = 2$\n - Dish 2: $0 \\times 2 + 2 \\times 1 = 2$\n - Dish 3: $0 \\times 2 + 1 \\times 1 = 1$\n - Favourite: Dish 1\n- Person 4: \n - Dish 1: $1 \\times 1 + 0 \\times 0 = 1$\n - Dish 2: $0 \\times 1 + 2 \\times 0 = 0$\n - Dish 3: $0 \\times 1 + 1 \\times 0 = 0$\n - Favourite: Dish 1\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2024_E", "prompt": "# Problem Statement\n\n## Problem Name\nE: Building the Fort\n\n## Problem Description\nYou are a Roman general setting up a defence fort against the Barbarians. \n\nYou only know how to build straight walls, so your fort is going to be polygon-shaped.\n\nDue to the shape of the land, which has multiple hills located at all the integer coordinates, you know that the enemy artillery can only be installed in very specific ways, and that higher positions inside your fort are more vulnerable, which means that:\n- All the vertices of the polygon must have integer coordinates between $1$ and $10^9$ (inclusive).\n- $N$ known points $(x_i, y_i), i=1,\\dots,N$, with integer coordinates between $1$ and $10^9$ (inclusive), initially given, must be among the vertices of the polygon.\n- No point with integer coordinates can be located strictly inside the polygon, as it would be vulnerable to the enemy artillery otherwise.\n- The polygon has to be simple (a simple polygon is a polygon formed by a single closed path that does not intersect itself or overlap itself).\n\nIn addition, due to the cost of building this fort and the limited materials, you can only afford to build a polygon with a number of vertices smaller than or equal to $3N$.\n\nIt can be shown that such a polygon always exists.\n\n## Input\nThe first line contains the integer $N$. The next $N$ lines contain two space-separated integers $x_i$, $y_i$, the points that must be among the vertices of the polygon.\n\n## Output\nThe first line should contain $K$, the number of vertices of the polygon.\n\nThe next $K$ lines should contain two space-separated integers $x'_i$, $y'_i$, the coordinates of the vertices of the polygon. They must be in an order that forms a closed and non-intersecting path that defines the outline of the polygon.\n\nIf there are multiple solutions, you can output any of them.\n\n## Limits\n- $3 \\leqslant N \\leqslant 1\\,000$\n- $1 \\leqslant x_i \\leqslant 10^9$ for $i=1,\\dots,N$\n- $1 \\leqslant y_i \\leqslant 10^9$ for $i=1,\\dots,N$\n- All $(x_i, y_i)$ are unique\n- $1 \\leqslant x'_i \\leqslant 10^9$ for $i=1,\\dots,K$\n- $1 \\leqslant y'_i \\leqslant 10^9$ for $i=1,\\dots,K$\n- All $(x'_i, y'_i)$ must be unique\n\n## Sample Input and Output\n\n### Sample Input\n```\n4\n1 1\n1 3\n3 1\n3 3\n```\n\n### Sample Output\n```\n5\n1 1\n3 1\n3 3\n2 2\n1 3\n```\n\n### Explanation\nOn the other hand, the following polygons are **not** valid solutions:\n\n- A square with vertices at $(1,1)$, $(1,3)$, $(3,3)$, $(3,1)$.\n- A square with vertices at $(1,1)$, $(3,3)$, $(3,1)$, $(1,3)$.\n- A polygon with vertices at $(1,1)$, $(1,3)$, $(3,3)$, $(2,3)$, $(2,2)$, $(2,3)$, $(3,1)$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2023_M", "prompt": "### Problem Statement\n\n#### In-order\n\n**Time limit:** 1 second\n\nThe opening ceremony for the Olympic Games will take place on the river with teams on boats. The layout of the athletes on top of the boat has been designed in a very specific way: for each team, the $N$ athletes (conveniently numbered from 1 to $N$) are arranged as a binary tree.\n\nThe organiser has also designed the pre-order traversal, post-order traversal, and a (possibly empty) consecutive part of the in-order traversal of the binary tree that each team must follow.\n\nNow, to make sure there are enough tree layouts so that each team can have a distinct one, you are asked to calculate the quantity of different possible in-order traversals, say $T$, modulo the prime number 999,999,937.\n\n#### Input\nThe input consists of four lines. The first line contains the number $N$. Each subsequent line contains a list of $N$ space-separated integers. The second line contains a list $A_1, A_2, \\ldots, A_N$, where $A_k$ is the number of the $k$-th athlete found in pre-order traversal. The third line contains a list $B_1, B_2, \\ldots, B_N$, where $B_k$ is the number of the $k$-th athlete found in post-order traversal. The fourth line contains a list $C_1, C_2, \\ldots, C_N$, where $C_k$ is either the number of the $k$-th athlete found in in-order traversal, or 0 if the organiser did not say who that $k$-th athlete should be.\n\n#### Output\nThe output should contain a single line, consisting of a single integer $S$: this is the only integer such that $0 \\leq S < 999,999,937$ and for which $T - S$ is divisible by 999,999,937.\n\n#### Limits\n- $1 \\leq N \\leq 500,000$\n- There exists at least one binary tree with such pre-order, post-order, and in-order traversals.\n- The integers $k$ for which $C_k \\geq 1$ form a (possibly empty) sub-interval of the set $\\{1, 2, \\ldots, N\\}$. In other words, whenever $k \\leq l$ and both $C_k$ and $C_l$ are positive, all the integers $C_k, C_{k+1}, \\ldots, C_l$ are positive.\n\n#### Sample Input 1\n```\n8\n1 2 3 5 6 4 7 8\n5 6 3 8 7 4 2 1\n0 0 6 2 4 0 0 0\n```\n\n#### Sample Output 1\n```\n2\n```\n\n#### Sample Explanation 1\nThe two possible binary trees have the following in-order traversals:\n- 5 3 6 2 4 8 7 1\n- 5 3 6 2 4 7 8 1\n\n#### Sample Input 2\n```\n3\n1 2 3\n3 2 1\n0 0 0\n```\n\n#### Sample Output 2\n```\n4\n```\n\n#### Sample Explanation 2\nThe four possible in-order traversals are:\n- 3 2 1\n- 2 3 1\n- 1 3 2\n- 1 2 3\n\n#### Sample Input 3\n```\n4\n1 2 3 4\n4 3 2 1\n0 4 0 0\n```\n\n#### Sample Output 3\n```\n3\n```\n\n#### Sample Explanation 3\nThe three possible in-order traversals are:\n- 2 4 3 1\n- 1 4 3 2\n- 3 4 2 1\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2024_A", "prompt": "# Problem Statement\n\n## Sort a List of Dutch Surnames\n\n- Sort a list of $n \\leq 1000$ Dutch surnames with lengths up to $50$ based on the Dutch rules, lexicographically, according to the values of the ASCII characters.\n- Consider only the part starting from the first capital letter.\n- The surnames consist of English letters, spaces, and apostrophes (`A-Z`, `a-z`, ` `, `'`).\n- It is guaranteed that the part starting with the first capital letter is unique.\n- Names have no leading, trailing, or consecutive spaces.\n- For example, the surname `van den Hecken the Younger` is sorted according to `Hecken the Younger`.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($1 \\leq n \\leq 1000$), the number of surnames.\n- $n$ lines, each with a string $s$ ($1 \\leq |s| \\leq 50$), one of the surnames. The surnames consist of English letters, spaces, and apostrophes (`A-Z`, `a-z`, ` `, `'`).\n\nIt is guaranteed that the part starting with the first capital letter is unique. Names have no leading, trailing, or consecutive spaces.\n\n## Output\n\nOutput the list of surnames, sorted according to the Dutch rules.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n7\nvan der Steen\nfakederSteenOfficial\nGroot Koerkamp\nBakker\nvan den Hecken the Younger\nde Waal\nvan 't Hek\n```\n\n### Sample Output 1\n```\nBakker\nGroot Koerkamp\nvan den Hecken the Younger\nvan 't Hek\nvan der Steen\nfakederSteenOfficial\nde Waal\n```\n\n### Sample Input 2\n```\n5\nvar Emreis\nan Gleanna\nTerzieff Godefroy\naep Ceallach\nof Rivia\n```\n\n### Sample Output 2\n```\naep Ceallach\nvar Emreis\nan Gleanna\nof Rivia\nTerzieff Godefroy\n```\n\n### Sample Input 3\n```\n7\nvan den Brand\nden Brand Heek\nBrand 'Heek\nvan Brand heek\nDeN bRAnD hEeK\nden brandHeek\nder Brandheek\n```\n\n### Sample Output 3\n```\nvan den Brand\nBrand 'Heek\nden Brand Heek\nvan Brand heek\nder Brandheek\nDeN bRAnD hEeK\nden brandHeek\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2022_H", "prompt": "# Problem H: Controllers\n## SWERC 2022-2023\n\n## Problem Statement\n\nYou are at your grandparents' house and you are playing an old video game on a strange console. Your controller has only two buttons, and each button has a number written on it.\n\nInitially, your score is 0. The game is composed of $n$ rounds. For each $1 \\le i \\le n$, the $i$-th round works as follows:\n- On the screen, a symbol $s_i$ appears, which is either + (plus) or - (minus).\n- Then you must press one of the two buttons on the controller once. Suppose you press a button with the number $\\alpha$ written on it: your score will increase by $\\alpha$ if the symbol was + and will decrease by $\\alpha$ if the symbol was -.\n- After you press the button, the round ends.\n\nAfter you have played all $n$ rounds, you win if your score is 0.\n\nOver the years, your grandparents bought many different controllers, so you have $q$ of them. The two buttons on the $j$-th controller have the numbers $a_j$ and $b_j$ written on them. For each controller, you must compute whether you can win the game playing with that controller.\n\n## Input\n\nThe first line contains a single integer $n$ ($1 \\le n \\le 2 \\times 10^5$) - the number of rounds.\nThe second line contains a string $s$ of length $n$ \u2014 where $s_i$ is the symbol that will appear on the screen in the $i$-th round. It is guaranteed that $s$ contains only the characters + and -.\nThe third line contains an integer $q$ ($1 \\le q \\le 10^5$) \u2014 the number of controllers.\nThe following $q$ lines contain two integers $a_j$ and $b_j$ each ($1 \\le a_j, b_j \\le 10^9$) \u2014 the numbers on the buttons of controller $j$.\n\n## Output\n\nOutput $q$ lines. On line $j$ print YES if the game is winnable using controller $j$, otherwise print NO.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n8\n+-+---+-\n5\n2 1\n10 3\n7 9\n10 10\n5 3\n```\n\n### Sample Output 1\n```\nYES\nNO\nNO\nNO\nYES\n```\n\n### Explanation of Sample 1\nOne possible way to get a score of 0 using the first controller is by pressing the button with number 1 in rounds 1, 2, 4, 5, 6, and 8, and pressing the button with number 2 in rounds 3 and 7. It is possible to show that there is no way to get a score of 0 using the second controller.\n\n### Sample Input 2\n```\n6\n+-++\n2\n9 7\n1 1\n```\n\n### Sample Output 2\n```\nYES\nYES\n```\n\n### Sample Input 3\n```\n20\n+-----+--+--------+-\n2\n1000000000 99999997\n250000000 1000000000\n```\n\n### Sample Output 3\n```\nNO\nYES\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2024_D", "prompt": "# Problem Statement\n\nThe process of forming the Dutch government has taken more than half a year for three elections in a row. Perhaps we can streamline the initial stages of coalition building?\n\nThe first step after the election results is to find a group of parties (called a *coalition*) with enough seats to have a strict majority. Your task is to count the number of candidate coalitions that satisfy specific conditions. A coalition is considered a *candidate coalition* if it meets these two criteria:\n\n- **Strict Majority:** The total number of seats held by the coalition must be strictly more than half of the total seats across all parties.\n- **No Superfluous Parties:** The coalition must be minimal in the sense that removing any one party from the coalition would cause it to lose its strict majority.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($1 \\le n \\le 60$), the number of parties.\n- One line with $n$ integers $p$ ($1 \\le p \\le 10\\,000$), the number of seats each party has.\n\n## Output\n\nOutput the total number of candidate coalitions that satisfy the criteria above.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n5\n3 1 4 1 5\n```\n\n### Sample Output 1\n```\n4\n```\n\n### Sample Input 2\n```\n11\n191 24 148 38 8 28 9 1 3 3 12\n```\n\n### Sample Output 2\n```\n38\n```\n\n### Sample Input 3\n```\n4\n1 2 3 4\n```\n\n### Sample Output 3\n```\n3\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2023_B", "prompt": "# Problem: Brickwork\n\nBob the Builder is tired of building tiny houses and paving narrow roads, and he strives for something bigger. The new job given to him by a very eccentric client is exactly what he needs: He is tasked with building a wall of a certain width that is infinitely high! His client assured him that he does not need to worry about the building material, and that an infinite supply of various kinds of bricks has already been ordered for him. Of course, building a stable wall takes very careful planning, especially if it is supposed to be infinitely high. In particular, a wall is only stable if no two gaps between bricks in consecutive rows end up directly above each other, as shown in the figure below.\n\nBob knows from his long-time experience that if it is possible to build such a wall, then it can be done by alternating just two row configurations.\n\n**Figure:**\nOn the left, we see an unstable wall using the brick types of Sample Input 1. On the right, we see a stable wall using the same brick types. Note that even though only two rows of the wall are shown, it is possible to build an infinitely high wall by repeating these two row configurations.\n\nGiven the types of bricks available, is it possible to build a stable wall of width exactly $w$ and infinite height? If yes, how should Bob build it using only two alternating row configurations?\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $w$ $(1 \\leq n, w \\leq 3 \\cdot 10^5)$, the number of brick types and the width of the wall.\n- One line with $n$ integers $b$ ($1 \\leq b \\leq w$), the widths of the brick types.\n\nNote that Bob has an infinite supply of all brick types.\n\n## Output\n\nIf it is possible to build a wall, then output `possible`. Otherwise, output `impossible`.\n\nIf a wall can be built, provide two row configurations that can be used in an alternating fashion. For both rows, first output the number of bricks needed for that row, followed by the lengths of the bricks in the order you want to use them. Your solution is considered valid if alternating the two rows infinitely would result in a stable wall.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Input 1\n\n```\n4 12\n3 2 7 2\n```\n\n## Sample Output 1\n\n```\npossible\n5\n2 2 3 2 3\n3\n3 2 7\n```\n\n## Sample Input 2\n\n```\n3 11\n6 7 8\n```\n\n## Sample Output 2\n\n```\nimpossible\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2022_G", "prompt": "### Problem G: Parmigiana With Seafood\n\n**SWERC 2022-2023**\n\n#### Time Limit:\n2.0S\n\n#### Memory Limit:\n2048MB\n\nThe \"Parmigiana di melanzane\" is a typical Italian dish. Alessandro and Bianca have very different tastes when it comes to it: Alessandro loves to eat Parmigiana with seafood, but Bianca thinks it is an atrocity! To decide which ingredients to include in the dish they prepare, they play the following game.\n\nThere are $n$ possible ingredients, labeled from 1 to $n$. The higher the label, the closer the ingredient is to being seafood. The ingredients are connected by $n - 1$ edges, in such a way as to form a tree. Alessandro and Bianca take turns, with Alessandro going first. They alternately choose a terminal ingredient $a$, that is an ingredient currently connected to at most one other ingredient, and remove it from the tree. If the terminal ingredient was chosen by Alessandro, it goes in the recipe; if it was chosen by Bianca, it is discarded.\n\nThe taste of the Parmigiana is measured as the maximum label of an ingredient in the recipe. Alessandro wants to maximize the taste, while Bianca wants to minimize the taste. If both play optimally, what is the taste of the Parmigiana?\n\n#### Input\nThe first line contains an integer $n$ ($2 \\leq n \\leq 100000$) \u2014 the number of ingredients.\n\nEach of the following $n - 1$ lines contain two integers $u_i$ and $v_i$ ($1 \\leq u_i, v_i \\leq n$, $u_i \\neq v_i$) \u2014 the ingredients that the $i$-th edge connects.\n\nIt is guaranteed that the edges form a tree (i.e., any pair of ingredients is connected by the edges, possibly indirectly).\n\n#### Output\nPrint the value of the taste if both Alessandro and Bianca play optimally.\n\n#### Sample Inputs and Outputs\n\n**Sample Input 1**\n```\n4\n1 2\n1 3\n1 4\n```\n\n**Sample Output 1**\n```\n4\n```\n\n**Explanation of Sample 1**\nAlessandro can choose terminal ingredient 4 in the first turn. This ingredient is added to the recipe. Since 4 is the maximum label of an ingredient, the taste is 4 regardless of the choices that follow.\n\n**Sample Input 2**\n```\n5\n1 5\n5 3\n3 4\n4 2\n```\n\n**Sample Output 2**\n```\n3\n```\n\n**Explanation of Sample 2**\nBianca can make sure that neither ingredient 4 nor 5 are included in the recipe, in which case Alessandro can include 3. Thus, the taste is 3.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2022_A", "prompt": "# Problem A: Walking Boy\n## SWERC 2022-2023\n\n## Problem Statement\n\nOne of the SWERC judges has a dog named Boy. Besides being a good competitive programmer, Boy loves fresh air, so she wants to be walked at least twice a day. Walking Boy requires 120 consecutive minutes. Two walks cannot overlap, but one can start as soon as the previous one has finished.\n\nToday, the judge sent $n$ messages to the SWERC Discord server. The $i$-th message was sent $a_i$ minutes after midnight. You know that, when walking Boy, the judge does not send any messages, but he can send a message right before or right after a walk. Is it possible that the judge walked Boy at least twice today?\n\nNote that a day has 1440 minutes, and a walk is considered to happen today if it starts at a minute $s \\geq 0$ and ends right before a minute $e \\leq 1440$. In that case, it must hold that $e - s = 120$ and, for every $i = 1, 2, \\ldots, n$, either $a_i \\leq s$ or $a_i \\geq e$.\n\n## Input\n\nEach test contains multiple test cases. The first line contains an integer $t$ ($1 \\leq t \\leq 100$) - the number of test cases. The descriptions of the $t$ test cases follow.\n\nThe first line of each test case contains an integer $n$ ($1 \\leq n \\leq 100$) \u2014 the number of messages sent by the judge.\n\nThe second line of each test case contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($0 \\leq a_1 < a_2 < \\ldots < a_n < 1440$) - the times at which the messages have been sent (in minutes elapsed from midnight).\n\n## Output\n\nFor each test case, output one line containing `YES` if it is possible that Boy has been walked at least twice, and `NO` otherwise.\n\n## Sample\n\n### Sample Input 1\n\n```\n6\n14\n100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400\n12\n100 200 300 400 600 700 800 900 1100 1200 1300 1400\n13\n100 200 300 400 500 600 700 800 900 1100 1200 1300 1400\n13\n101 189 272 356 463 563 659 739 979 1071 1170 1274 1358\n1\n42\n5\n0 1 2 3 4\n```\n\n### Sample Output 1\n\n```\nNO\nYES\nNO\nYES\nYES\nYES\n```\n\n### Explanation of Sample 1\n\n- In the first test case, the judge has sent a message at each time multiple of 100 (excluding 0). It is impossible that he has walked Boy even once.\n- In the second test case, the times are the same as above, but 500 and 1000 are missing. The judge could have walked Boy, for instance, during the time intervals [440, 560] and [980, 1100].\n- In the third test case, the times are the same as in the first test case, but 1000 is missing. The judge could have walked Boy at most once.\n- In the fourth test case, Boy could have been walked during the time intervals [739, 859] and [859, 979].\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "nwerc2024_E", "prompt": "# Problem Statement\n\n**Create a new word from an existing word $s$ ($|s| \\leq 10^5$) by applying the following method up to $10^{18}$ times:**\n\n- Take every second letter of $s+s$, starting with the first letter.\n- For example, applying this method to the word \"etymology\" once would result in \"eyooytmlg\".\n\n**Eelco has recently started to gain interest in the field that studies the origin of words: etymology.** He especially likes how words can evolve in many different ways: pronunciation changes over time, words are borrowed from different languages, and the meaning of words can change based on culture. Eelco is eager to attend the Networking With Etymologists: Revolutionary Conference for the first time ever. To make a good first impression, he is going to present a completely new method to make new words from existing words.\n\n**To make a new word from an existing word $s$, Eelco proposes to take every second letter of $s+s$, starting with the first letter.** For example, applying this method to the word \"etymology\" would result in \"eyooytmlg\". Of course, to design even more words, this process can be repeated many times. Eelco would like to prepare a list of new words to present at the conference, so he writes a program that applies his method some predetermined number of times.\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $k$ ($1 \\leq n \\leq 10^5$, $1 \\leq k \\leq 10^{18}$), the length of the original word and the number of times to apply the method.\n- One line with a string $s$ of length $n$, only consisting of English lowercase letters (a-z), the original word.\n\n## Output\n\nOutput the resulting word after applying the method to the original word $k$ times.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n9 1\netymology\n```\n\n### Sample Output 1\n```\neyooytmlg\n```\n\n### Sample Input 2\n```\n4 1\nword\n```\n\n### Sample Output 2\n```\nwrwr\n```\n\n### Sample Input 3\n```\n5 1000000000000000000\ndelft\n```\n\n### Sample Output 3\n```\ndelft\n```\n\n### Sample Input 4\n```\n5 5\neceol\n```\n\n### Sample Output 4\n```\neelco\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2022_D", "prompt": "# Problem D: Crossing the Railways\n## SWERC 2022-2023\n\n## Problem Statement\n\nIsona is in a train station. This station has two platforms, and between them are $m$ parallel railways that can be viewed as infinite straight lines. Each railway is identified with an integer from 1 to $m$, with railway 1 being the closest to the first platform and railway $m$ being the farthest. There is a 1 meter distance between consecutive railways, as well as between each platform and its closest railway.\n\nIsona is standing on the inner border of the first platform, and she realizes that she forgot to validate her ticket! There is a validating machine on the second platform, exactly opposite her current position (thus, the distance between Isona and the validating machine is $m + 1$ meters). There are only $s$ seconds left to validate the ticket, and the bridge designated to cross the railways is too far from the validating machine. Therefore, Isona (who is very brave and a little bit careless) will cross the railways running in a straight line perpendicular to the railways themselves. Isona can only run forward (not backward) and she can stay still. When she runs at maximum speed, she needs $v$ seconds to traverse 1 meter. She can run at any speed less than or equal to her maximum speed.\n\nThere is only one problem: $n$ trains are programmed to transit through the railways. The $i$-th train will use the railway $r_i$. It will start crossing the straight line between Isona and the validating machine at $a_i$ seconds from now and it will end at $b_i$ seconds from now. Of course, Isona cannot cross a railway when a train is passing. Formally, for every $i = 1, 2, \\ldots, n$, Isona is not allowed to be on railway $r_i$ at any time $t$ with $a_i < t < b_i$ (but she is allowed to cross at times $a_i$ or $b_i$).\n\nIsona is a really good runner, but she gets tired every time she has to change her running speed. What is the minimum number of speed changes she has to perform to get to the validating machine on the other platform within $s$ seconds from now? Note that at the beginning Isona is not running. She can start to run anytime. The instant she starts to run (i.e., her speed becomes positive) is not counted as a speed change.\n\n## Input\n\nThe first line of the input contains four integers $n$, $m$, $s$, $u$ ($1 \\leq n \\leq 500$, $1 \\leq m \\leq 10$, $1 \\leq s, u \\leq 100$) \u2014 the number of trains, the number of railways, the maximum time in seconds Isona can spend crossing the railways, and the number of seconds she needs to traverse 1 meter at maximum speed.\n\nEach of the next $n$ lines contains three integers $a_i$, $b_i$, $r_i$ ($1 \\leq a_i < b_i \\leq 100$, $1 \\leq r_i \\leq m$) \u2014 the start and end times of the $i$-th train crossing the straight line between Isona and the validating machine, and the railway it will be using.\n\nIt is guaranteed that, for any two trains $i$ and $j$ that go through the same railway (i.e., $r_i = r_j$), there is at least 1 second between them (that is, either $a_j \\geq b_i + 1$ or $a_i \\geq b_j + 1$).\n\n## Output\n\nPrint the minimum number of speed changes Isona has to perform to get to the validating machine in time. If this is impossible, print -1.\n\n## Samples\n\n### Sample Input 1\n```\n4 3 5 1\n1 2 1\n3 4 1\n2 3 2\n3 4 3\n```\n\n### Sample Output 1\n```\n0\n```\n\n### Explanation of Sample 1\nIf Isona starts running at time $t = 0$ at maximum speed (1 m/s), she will cross each railway just when a train is about to traverse it, and she will arrive at the other platform at time 4 = $s - 1$ without changing speed.\n\n### Sample Input 2\n```\n3 3 12 2\n2 10 1\n1 6 2\n8 12 3\n```\n\n### Sample Output 2\n```\n2\n```\n\n### Explanation of Sample 2\nA possible solution with 2 speed changes is the following: for the first 2 seconds Isona goes at maximum speed (0.5 m/s), then she slows down to 0.25 m/s for 4 seconds until she reaches the second railway. At that point, she goes at maximum speed again until she reaches the other platform.\n\n### Sample Input 3\n```\n8 4 13 2\n1 4 1\n5 13 1\n1 5 2\n6 13 2\n1 9 3\n10 13 3\n1 10 4\n11 13 4\n```\n\n### Sample Output 3\n```\n2\n```\n\n### Explanation of Sample 3\nIsona can wait 2 seconds before starting running. She then runs for 5 seconds at maximum speed (0.5 m/s). After that, she waits for 1 second not running (or running at 0 m/s), and finally she runs again at maximum speed for the last 5 seconds. Overall, she changes speed twice.\n\n### Sample Input 4\n```\n1 1 2 2\n1 2 1\n```\n\n### Sample Output 4\n```\n-1\n```\n\n### Explanation of Sample 4\nIt is impossible for Isona to cross the railway within the given time constraints because the train is crossing the only railway for the entire duration of the available time.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2022_A", "prompt": "# Problem: Alternating Algorithm\n\nIn recent years, CPU manufacturers have found it increasingly difficult to keep up with Moore's law of doubling the number of transistors on integrated circuit chips every two years. To address this, manufacturers have instead started creating CPUs with an increasingly higher number of cores. In fact, you just purchased a CPU with a staggering $n$ number of cores, no less!\n\nIncidentally, you also have an array of $n+1$ integers, $a_0, a_1, \\ldots, a_n$, that you need to sort. To make good use of the large number of cores on your CPU, you have devised a parallel sorting algorithm in which there is a dedicated core for comparing each adjacent pair of integers. As long as the array is not sorted in non-decreasing order, the algorithm proceeds in rounds that alternate between:\n\n- **Odd rounds (starting with the first):** The first core compares $a_0$ and $a_1$, the third core compares $a_2$ and $a_3$, the fifth core compares $a_4$ and $a_5$, and so on. If a pair of compared elements are out of order, the corresponding core will swap their positions. If $n$ is even, $a_n$ will be left untouched.\n- **Even rounds:** The second core compares $a_1$ and $a_2$, the fourth core compares $a_3$ and $a_4$, the sixth core compares $a_5$ and $a_6$, and so on. If a pair of compared elements are out of order, the corresponding core will swap their positions. If $n$ is odd, $a_n$ will be left untouched, and $a_0$ will be left untouched no matter what the parity of $n$ is.\n\nNote that in both types of rounds some cores may be idle.\n\nBefore implementing this algorithm, you have decided to do some analysis. In particular, you noticed that the time complexity of the algorithm does not depend on the value of $n$, but rather it depends on the number of rounds that the algorithm runs. Given the initial contents of the array, determine the number of rounds that the parallel sorting algorithm runs before the array becomes sorted.\n\n## Input\nThe input consists of:\n- One line with an integer $n$ ($1 \\leq n \\leq 4 \\cdot 10^5$), the number of cores and the size of the array.\n- One line with $n+1$ integers $a_0, a_1, \\ldots, a_n$ ($0 \\leq a_i \\leq 10^9$ for each $i$), the initial contents of the array.\n\n## Output\nOutput the number of rounds that the parallel sorting algorithm runs before the array becomes sorted in non-decreasing order.\n\n## Sample Input/Output\n\n### Sample Input 1\n```\n3\n8 13 4 10\n```\n\n### Sample Output 1\n```\n3\n```\n\n### Sample Input 2\n```\n5\n13 12 14 10 14 12\n```\n\n### Sample Output 2\n```\n3\n```\n\n### Sample Input 3\n```\n2\n2 2 1\n```\n\n### Sample Output 3\n```\n3\n```\n\nIllustration of Sample Input 1, where the array is sorted after three rounds. (Note: This illustration is not included in the markdown output.)\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2024_B", "prompt": "# Problem Statement\n\nYou are given an undirected graph with $n$ vertices and $m$ edges. Each vertex $v$ has a number $a_v$ written on it. This number is either $0$ or $1$.\n\nA *walk* is a sequence $v_1 v_2 \\dots v_k$ of vertices in the graph such that any two consecutive vertices are connected by an edge. We call a binary sequence $s = s_1 s_2 \\dots s_k$ *walkable* if there is a walk $v_1 v_2 \\dots v_k$ in the graph that satisfies $a_{v_1} a_{v_2} \\dots a_{v_k} = s$.\n\nIn other words, a binary sequence is walkable if it is possible to obtain $s$ by walking in the graph and writing down the binary numbers in the order that they are visited. An example is visualized in the following figure.\n\nYour task is to find the length of a shortest binary sequence that is not walkable.\n\n## Input\nThe input consists of:\n- One line with two integers $n$ and $m$ ($1 \\leq n \\leq 3 \\cdot 10^5$, $0 \\leq m \\leq 3 \\cdot 10^5$), the number of vertices and the number of edges.\n- One line with $n$ integers $a_1, \\dots, a_n$ ($a_v \\in \\{0, 1\\}$ for each $v$), where $a_v$ is the number written on vertex $v$.\n- $m$ lines, each with two integers $u$ and $v$ ($1 \\leq u, v \\leq n$, $u \\neq v$), denoting that the vertices $u$ and $v$ are connected by an edge. It is guaranteed that every pair of vertices is connected by at most one edge.\n\n## Output\nIf every binary sequence is walkable, output \"infinity\". Otherwise, output the length of a shortest binary sequence that is not walkable.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n4 4\n0 0 1 1\n1 2\n1 3\n2 3\n3 4\n```\n\n### Sample Output 1\n```\n4\n```\n\n### Sample Input 2\n```\n6 7\n0 0 1 1 0 1\n1 2\n3 1\n1 4\n2 3\n4 2\n3 4\n5 6\n```\n\n### Sample Output 2\n```\ninfinity\n```\n\n### Sample Input 3\n```\n1 0\n0\n```\n\n### Sample Output 3\n```\n1\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2024_M", "prompt": "# Problem: M: Ook? Ook!\n\nWhen Arthur Evans excavated Knossos, along with the famous Linear A and Linear B tablets, he also found evidence of a much earlier language, the Ook language, whose only letters are O and K.\n\nAs he was deciphering this language, he telegraphed to London lists of Ook words that he was gathering. At the time, the Morse language was different from the one you know, and letters had Pseudo-Morse translations different from the ones they have today. Unfortunately, he was so excited by this discovery that he forgot to include pauses between letters when telegraphing.\n\nAs the operator in London, you have received this message from sir Arthur: `.-.-.-`, and through a side-channel, you have learnt this sequence can represent two different Ook words: OK and KO. You have also received the sequence `.-.-.-.-.-`, and have learnt it means OOK.\n\nYou need to ask sir Arthur to translate a few more Ook words for you into English. Can your program send them as Pseudo-Morse over the wire? You are as excited as sir Arthur, so you forget pauses in what you send as well.\n\n## Input\n\nThe input consists of a single line. This line contains a single Ook word $W$, which only contains letters `O` and `K`, followed by an end-of-line character.\n\n## Output\n\nThe output should contain a single string, the translation of $W$ in the pseudo-Morse language, without pauses.\n\n## Limits\n\n- $1 \\leq |W| \\leq 1\\,000$.\n\n## Sample Input/Output\n\n### Sample 1\n```\nOK\n```\n```\n.-.-.-\n```\n\n### Sample 2\n```\nKO\n```\n```\n.-.-.-\n```\n\n### Sample 3\n```\nOOK\n```\n```\n.-.-.-.-.-\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "nwerc2024_H", "prompt": "# Problem Statement\n\nFor security reasons, TU Delft is going to place locks with numeric keypads on the doors of a large number of rooms. Each room will have its own pass code. The task of setting up the server on which all codes will be stored is given to Harry and Sharon.\n\nHaving paid attention in cybersecurity class, they know that the codes should be passed through a **hash function**, preferably multiple times, before storing.\n\nSharon came up with the nifty idea of letting the room number be the number of times the code is passed through the hash function. That way, even if two rooms happen to have the same pass code, they will not (necessarily) end up with the same hash value. However, they find that for some combinations of room number and code, the hash value happens to be the same as the original code, presenting a security risk.\n\nNot to be outdone by Sharon, Harry came up with an idea of his own: to switch the roles, that is, let the code be the number of times the hash function is applied to the room number. In other words, if $c$ is the code and $r$ is the room number, the hash value will be $f^c(r) = \\underbrace{f(\\cdots f(}_{c~\\text{times}}r)\\cdots)$.\n\nAfter some thought, Sharon claimed that, regardless of what the function $f$ is, it would always still be the case for some room numbers and codes that the hash value is the same as the code; that is, that $f^c(r) = c$. In fact, Sharon thinks it would not be too difficult to find two such numbers, even without knowing the full details of $f$.\n\nThis dismissive statement made Harry angry, who believed that Sharon was just jealous of his idea. After a big argument that led nowhere, Harry decided to make Sharon prove her claim: he has written a program that, upon sending it a query, will return the hash value $f^c(r)$ for the $c$ and $r$ given in the query, using a secret hash function $f$ he has chosen. The hash function accepts any $r$ in $\\{1, \\dots, n\\}$, where $n$ is given, and returns a value in the same range. The value of $c$ should also be in the same range. The challenge for Sharon is to find $c$ and $r$ such that $f^c(r) = c$, using a limited number of queries.\n\nYou know that Sharon is right about her claim and decide to help her.\n\n## Interaction\n\nThis is an interactive problem. Your submission will be run against an interactor, which reads the standard output of your submission and writes to the standard input of your submission. This interaction needs to follow a specific protocol:\n\n1. The interactor first sends one line with an integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), indicating that the domain of the hidden function $f$ is $\\{1, \\dots, n\\}$.\n2. Then, your program should make at most 1000 queries to find the answer.\n - Each query is made by printing one line of the form `? $c$ $r$` ($1 \\leq c, r \\leq n$).\n - The interactor will respond with an integer $h$ ($1 \\leq h \\leq n$), the value of $f^c(r)$.\n3. When you have determined some values of $c$ and $r$ such that $f^c(r) = c$, print one line of the form `! $c$ $r$` ($1 \\leq c, r \\leq n$), after which the interaction will stop.\n - Printing the answer does not count as a query.\n4. If there are multiple valid solutions, you may output any one of them.\n5. The interactor is not adaptive: the hidden function $f$ is fixed up front, and does not depend on your queries.\n6. Make sure you flush the buffer after each write.\n7. Using more than 1000 queries will result in a wrong answer.\n\n## Sample Input and Output\n\n### Sample Input 1\n```\n6\n4 3 5 2 4 6\n```\n\n### Sample Output 1\n```\n! 4 1\n```\n\n### Sample Input 2\n```\n4\n2 4 2 2\n```\n\n### Sample Output 2\n```\n! 2 1\n```\n\nIn the first sample case, the value of $n$ is 6, and the hidden function is given by $f(1) = 4$, $f(2) = 3$, $f(3) = 5$, $f(4) = 2$, $f(5) = 4$, and $f(6) = 6$.\n\nIn the second sample case, the value of $n$ is 4, and the hidden function is given by $f(1) = 2$, $f(2) = 4$, $f(3) = 2$, and $f(4) = 2$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2023_K", "prompt": "# Problem: Klompendans\n\nIn traditional Dutch clog dancing, you as the dancer need to follow a very specific sequence of movements. The dance takes place on a square grid of square tiles, and at the start of the dance you stand on the top left corner tile of the grid. You then alternate between two types of dance move, moving from tile to tile in the grid for as long as you want. Your first move may be of either kind, but after that you need to strictly alternate between the two kinds of moves.\n\nBoth moves are similar to knight moves in chess:\n- In the first type of move, you go from your current square to a square that is $a$ tiles away along one axis of the grid and $b$ tiles away along the other axis.\n- Similarly, in the second type of move, you need to move $c$ and $d$ tiles along the respective axes.\nAs you can freely swap the two axes and choose the movement direction along each axis, there can be up to 8 ways of performing a given type of move.\n\nStarting on the top left corner tile, how many different tiles could you reach while doing a clog dance? It is not allowed to step outside of the grid and you do not count tiles that you are simply stepping over while doing a move. Note that you need to count all tiles that can be reached during some performance of the dance, but not necessarily during the same one.\n\n## Input\nThe input consists of:\n- One line with an integer $n$ ($3 \\leq n \\leq 500$), the side length of the square.\n- One line with two integers $a$ and $b$ ($1 \\leq a, b < n$), describing the first dance move.\n- One line with two integers $c$ and $d$ ($1 \\leq c, d < n$), describing the second dance move.\n\n## Output\nOutput the number of tiles you can reach using these dance moves.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n3\n2 1\n2 2\n```\n\n### Sample Output 1\n```\n6\n```\n\n### Sample Input 2\n```\n8\n1 2\n1 2\n```\n\n### Sample Output 2\n```\n64\n```\n\n### Sample Input 3\n```\n4\n1 2\n2 3\n```\n\n### Sample Output 3\n```\n13\n```\n\n### Sample Input 4\n```\n5\n1 2\n2 3\n```\n\n### Sample Output 4\n```\n25\n```\n\n### Sample Input 5\n```\n10\n3 3\n4 4\n```\n\n### Sample Output 5\n```\n50\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2024_J", "prompt": "# Problem: J: Recovering the Tablet\n\nA long time ago, before our modern civilization arose and before any of you were born, was the year -1966 (3961 Before SWERC). During this dark period, there were no streaming services nor any programming contests. Thus, to entertain themselves, humans had rudimentary games that they played on clay tablets.\n\nThis year, a mysterious game was created: Kakurus. We know close to nothing about Kakurus (the Internet Archive had not yet been created), except for a few rules described on an artifact you have discovered:\n1. The game is played on an $M \\times N$ grid;\n2. Each cell is either black or white;\n3. White cells are originally empty, but you will have to put an integer from $1$ to $9$ (inclusive) inside each white cell;\n4. **Horizontal constraint**: A black cell can contain an integer corresponding to the sum of the consecutive white cells to its right (until the first black cell or the limit of the grid);\n5. **Vertical constraint**: A black cell can contain an integer corresponding to the sum of the consecutive white cells below it (until the first black cell or the limit of the grid).\n\nNote that the last two rules are independent from each other: a black cell can have $0$, $1$ or $2$ integers inside it. **Note also that no constraint is placed on repetitions of numbers.** Finally, since we want this problem to be interesting, every white cell is covered by exactly one vertical constraint and by exactly one horizontal constraint.\n\nAt the bottom of your artifact lies a grid of Kakurus. It is already filled, but not necessarily with a correct solution -- probably a deterioration due to the age of this antique artifact. Can you find a valid solution that is as close as possible to this proposed solution?\n\nIf the number you write on a white cell is $X$ and the value of the proposed solution for this cell is $T$, then the closeness score is $|X-T|$. The final closeness score of the grid is the sum of all closeness scores of the cells. Your objective is to find the minimum closeness score that can be achieved.\n\n## Input\n\nThe first line of the input consists of three integers, $M$, $N$ and $S$, respectively the number of lines and columns of this grid, and the number of sum constraints.\n\nThen, $M$ lines follow. The $i$th of these lines only contains digits from $0$ to $9$. The $j$th character equals $0$ if and only if the cell at line $i$ and column $j$ ($1 \\leq i \\leq M$, $1 \\leq j \\leq N$) is black, and otherwise is equal to the value of this cell (which is thus white) in the proposed solution.\n\nThen $S$ lines follow. Each line is of the form $c\\ i\\ j\\ s$ where $c$ is equal to either `H` or `V`, $1 \\leq i \\leq M$, $1 \\leq j \\leq N$ and $s$ is an integer between 1 and 135, inclusive. The sum of the consecutive white cells at the right of (when $c=$ `H`) or below (when $c=$ `V`) the cell at line $i$ and column $j$ must be equal to $s$ in your solution.\n\nIt is guaranteed that every white cell is covered by exactly one vertical and one horizontal constraint.\n\n## Output\n\nIf the grid has no solution, you must output `IMPOSSIBLE`.\nOtherwise, your output should consist of the minimum closeness score that can be achieved.\n\n## Limits\n\n- $1 \\leq M \\leq 16$;\n- $1 \\leq N \\leq 16$;\n- $0 \\leq S \\leq 2 \\times M \\times N$.\n\n## Sample Input 1\n\n```\n4 4 7\n0000\n0032\n0233\n0204\nH 3 1 9\nV 1 3 6\nH 2 2 5\nV 2 2 5\nV 1 4 9\nH 4 1 2\nH 4 3 4\n```\n\n## Sample Output 1\n\n```\n1\n```\n\n## Sample Input 2\n\n```\n3 4 5\n0000\n0012\n0345\nH 2 2 3\nH 3 1 12\nV 2 2 3\nV 1 3 5\nV 1 4 6\n```\n\n## Sample Output 2\n\n```\nIMPOSSIBLE\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2024_G", "prompt": "# Problem Statement\n\nA sliding puzzle consists of square tiles on a rectangular grid. Exactly one of the grid positions is empty, so that you can move the tile above, below, to its left, or to its right into the empty square and back.\n\nEach tile is labelled with a unique number, as shown in Figure 1. To solve a sliding puzzle, you need to find a sequence of moves that puts the tile numbers in ascending order, from left to right and top to bottom, such that the empty square ends up at the bottom right position in the grid, as shown in Figure 2. Such a sequence of moves does not exist for all sliding puzzles.\n\nWhile cleaning out your garage, you grapple with the garage goblins over a glowing box full of goodies. They offer a gamble: the box is yours if you can solve all their sliding puzzles. You accept to give it a go, only to find out that the garage goblins have glued some tiles in place!\n\nHowever, all sliding puzzles share the following properties:\n- The empty square is at the bottom right position.\n- Every glued tile is in its correct position.\n- For each tile that can move, there is a sequence of moves that leaves the empty square in its position instead.\n- From any glued tile, there is a path to the border of the sliding puzzle across glued tiles only, when stepping to the tile above, below, to the left, or to the right at each step. That is, no glued tiles are encircled by tiles that can move.\n\nDetermine whether it is possible to solve a given sliding puzzle.\n\n## Input\nThe input consists of:\n- One line with two integers $h$ and $w$ ($1 \\le h, w \\le 500$), the height and width of the sliding puzzle's grid.\n- $h$ lines with $w$ characters, each character being either `\\texttt{.}` or `\\texttt{\\#}`. The bottom right character, at the position of the empty square, is `\\texttt{.}`. Otherwise, `\\texttt{.}` denotes a tile that can move, and `\\texttt{\\#}` denotes a glued tile.\n- $h$ lines with $w$ integers $a_{i,j}$ ($1 \\le i \\le h$, $1 \\le j \\le w$, $0 \\le a_{i,j} \\le h \\cdot w - 1$). The bottom right integer is $a_{h,w} = 0$, representing the empty square. Otherwise, $a_{i,j}$ is the label on the tile at position $(i,j)$.\n\nThe set of all $a_{i,j}$ ($1 \\le i \\le h, 1 \\le j \\le w$) contains each of the numbers $0, 1, \\dots, h \\cdot w - 1$ once.\n\n## Output\nOutput `possible` if the sliding puzzle can be solved, or `impossible` if not.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n3 4\n....\n....\n....\n10 8 2 3\n6 7 5 9\n11 1 4 0\n```\n\n### Sample Output 1\n```\npossible\n```\n\n### Sample Input 2\n```\n2 4\n....\n....\n2 1 3 4\n5 6 7 0\n```\n\n### Sample Output 2\n```\nimpossible\n```\n\n### Sample Input 3\n```\n3 4\n..#.\n....\n#...\n5 1 3 4\n2 6 7 8\n9 10 11 0\n```\n\n### Sample Output 3\n```\npossible\n```\n\n### Sample Input 4\n```\n3 4\n..#.\n....\n#...\n7 1 3 4\n5 6 2 8\n9 10 11 0\n```\n\n### Sample Output 4\n```\nimpossible\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2024_D", "prompt": "# Problem: Temple Architecture\n\nYou are excavating what remains of a very old Indian temple. The architecture of the temple is very curious: you found a line of $N$ towers of different heights (no two towers have the same height), all spaced by one meter (the radius of each tower is supposed to be negligible).\n\nDuring the excavations, you find something which might explain this curious architecture: the tomb of the architect. You find the following epitaph on the tomb:\n\n> O thou temple-builder, \n> To achieve perfection, visit each tower; \n> For each, compute the distance to the closest tower that is taller; \n> Add every such distance. \n> If thou can follow this guidance, \n> Enlightened shalt thou be by this result, \n> And great in thy temple shall be the cult.\n\nThe closest taller tower can be on the left or on the right. For the tallest tower, this distance is undefined and should not be considered in the final sum.\n\nYou wonder how to compute this sum, this \"enlightenment score\" of the temple.\n\nYou are given a positive integer $N$ corresponding to the number of towers, and an array $H$ of $N$ distinct non-negative integers corresponding to the heights of the towers. $H_0$ is the height of the leftmost tower, $H_1$ is the height of the tower to the right of $H_0$, and so on. Finally, $H_{N-1}$ is the height of the rightmost tower. Observe that the distance between any two towers, in meters, is the absolute value of the difference of their respective indices in the array $H$.\n\nLet $p$ denote the index of the tallest tower in $H$ and define, for every $i \\neq p$,\n$$\nd(i) = \\min\\{ |i - j| \\text{ for every } j \\text{ such that } H_j > H_i \\}.\n$$\nNote that $d(p)$ is not defined. The \"enlightenment score\" of the temple is then given by\n$$\n\\sum_{i=0, i \\neq p}^{N-1} d(i).\n$$\n\n## Input\n\nThe first line contains the integer $N$.\nThe second line contains the list of elements $H_0, \\dots, H_{N-1}$ of the array $H$ of heights, separated by spaces.\n\n## Output\n\nThe output should contain one line with the enlightenment score of the temple.\n\n## Limits\n\n- $2 \\leq N \\leq 200,000$\n- $0 \\leq H_i \\leq 10^{18}$, for $i = 0, \\dots, N-1$\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n5\n7 3 2 100 1\n```\n\n### Sample Output 1\n```\n6\n```\n\n### Explanation for Sample 1\n- Distance of the 1st tower to the closest taller tower (4th tower): 3\n- Distance of the 2nd tower to the closest taller tower (1st tower): 1\n- Distance of the 3rd tower to the closest taller tower (2nd or 4th tower): 1\n- Distance of the 5th tower to the closest taller tower (4th tower): 1\nThe tallest tower (the 4th) is not considered. Hence, $3 + 1 + 1 + 1 = 6$.\n\n### Sample Input 2\n```\n8\n45 13 18 10 8 56 17 19\n```\n\n### Sample Output 2\n```\n13\n```\n\n### Explanation for Sample 2\n- Distance of the 1st tower to the closest taller tower (6th tower): 5\n- Distance of the 2nd tower to the closest taller tower (1st or 3rd tower): 1\n- Distance of the 3rd tower to the closest taller tower (1st tower): 2\n- Distance of the 4th tower to the closest taller tower (3rd tower): 1\n- Distance of the 5th tower to the closest taller tower (4th or 6th tower): 1\n- Distance of the 7th tower to the closest taller tower (6th or 8th tower): 1\n- Distance of the 8th tower to the closest taller tower (6th tower): 2\nThe tallest tower (the 6th) is not considered. Hence, $5 + 1 + 2 + 1 + 1 + 1 + 2 = 13$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "nwerc2024_F", "prompt": "# Problem Statement\n\n## Bill's Champagne Fountain\n\nLast week, Bill filled a champagne fountain for the first time. Delighted by the champagne pouring from one glass into another, he decided that he wants to organize an even bigger champagne fountain for the next World Finals. He already ordered $n$ glass bowls with different capacities to stack on top of each other to form a huge glass fountain. However, he is still unsure how to pour the champagne into the fountain. One bottle will not be enough and just pouring from the top might not fill every bowl. Bill wants to try out different ways to fill the fountain, but wasting any champagne would be such a shame.\n\nThis is your time to shine! You are tasked with writing a program that simulates the process of pouring champagne into a given fountain. If a bowl in some level is already filled up, then the champagne spills over to the first level below it with larger capacity. If the next larger level is also filled, the champagne spills over even further until eventually seeping into the ground, wasting the good champagne. Additionally, Bill also wants to know at some times during the simulation process how much champagne currently is in a certain level.\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $q$ ($1 \\leq n, q \\leq 3 \\cdot 10^5$), the number of levels and the number of queries.\n- One line with $n$ distinct integers $c$ ($1 \\leq c \\leq 10^9$), the capacity of each level in litres. The levels are given in order from top to bottom.\n- $q$ lines, each describing a query. The first symbol $t$ ($t \\in \\{\\text{`\\texttt{+}'}, \\text{`\\texttt{?}'}\\}$) describes the type of the query. The format of the rest of the line depends on $t$:\n - $t = \\text{`\\texttt{+}'}$: Two integers $\\ell$ and $x$ follow ($1 \\leq \\ell \\leq n$, $1 \\leq x \\leq 10^9$), the level into which Bill wants to pour $x$ litres of champagne.\n - $t = \\text{`\\texttt{?}'}$: One integer $\\ell$ follows ($1 \\leq \\ell \\leq n$), the level for which Bill requests the current amount of champagne in litres.\n\nIt is guaranteed that there is at least one query of type `\\texttt{?}'.\n\n## Output\n\nFor each query of type `\\texttt{?}', output the amount of champagne in the requested level in litres.\n\n## Sample Input 1\n\n```\n4 4\n1 2 3 4\n+ 1 6\n? 4\n+ 1 6\n? 4\n```\n\n## Sample Output 1\n\n```\n0\n4\n```\n\n## Sample Input 2\n\n```\n4 8\n2 4 3 5\n+ 1 4\n? 2\n+ 2 3\n? 4\n+ 3 4\n? 4\n+ 2 10\n? 4\n```\n\n## Sample Output 2\n\n```\n2\n1\n2\n5\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2022_B", "prompt": "# Problem: Bottle Flip\n\nIt marks the year 2022 where the *bottle flip challenge* finally reached the last people on earth; the NWERC Jury. As you may know, the objective of the challenge is to flip a bottle of water $360^\\circ$ through the air and hope that it lands standing upright. Figure 1 demonstrates a successful bottle flip.\n\nAfter many failed attempts, we noticed that this task gets significantly easier if the bottle is filled with just the right amount of water. The simple reason for this is that the amount of water affects the centre of mass of our bottle as it is about to land. For the sake of completeness, we define the centre of mass as the unique point at which the whole mass of the bottle could be concentrated without changing the bottle's reaction to gravity, regardless of the orientation of the bottle. Note that we implicitly assume that the water will stay at the bottom of the bottle. This defines exactly what you would intuitively think of as centre of mass.\n\nA lower centre of mass makes it easier for the bottle to stay upright after it lands. Unfortunately, the optimal amount of water depends on the bottle, and we already wasted enough time on this challenge\\dots\n\nGiven that our bottle is a perfect cylinder of height $h$ and radius $r$, determine the optimal amount of water the bottle should contain so that our chances of landing a successful bottle flip are maximised. You can assume that both the water and the air contained in the bottle have uniform density, and that the weight of the bottle itself is negligible.\n\n## Input\nThe input consists of:\n- One line with four integers $h$, $r$, $d_a$, and $d_w$ ($1 \\leq h, r, d_a, d_w \\leq 1000$, $d_a < d_w$), where $h$ and $r$ are the height and radius of the bottle, and $d_a$ and $d_w$ are the densities of air and water, respectively.\n\n## Output\nOutput the height such that filling the bottle with water up to this height results in the lowest possible centre of mass while the bottle is standing upright. Your answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n22 4 1 4\n```\n\n## Sample Output 1\n```\n7.3333333333\n```\n\n## Sample Input 2\n```\n7 2 655 988\n```\n\n## Sample Output 2\n```\n3.1415941720\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "swerc2024_C", "prompt": "# Problem: Phryctoria\n\nLusius Quietus, one of the generals of Trajan, the Roman emperor, is sending signals to his army using signal towers, where the fires you lit can be seen from afar.\n\nHe wants to send the string $S$ describing military manoeuvres. However, sending long messages via fire signals is time-consuming, so Lusius decides to use a shorthand system. To abbreviate the message, Lusius can replace any substring of $S$ with the special character `*'. For example, if $S$ is ``swerc'', then some possible abbreviations are: ``swe*'', ``*sw*r*'', ``swerc'', ``*'', etc. Note that `*' can match the whole string or no character at all, so ``*sw*r*'' is indeed considered a valid abbreviation of ``swerc'' even though it's longer (Lusius is not always clever).\n\nHowever, there is a problem: the recipient might misinterpret Lusius's message. If the abbreviation he sends is also a valid abbreviation of the string $T$, which is a word used to signal retreat, it could lead to losing the war.\n\nHelp Lusius find the length of the shortest possible abbreviation of $S$ that cannot be interpreted as an abbreviation of $T$.\n\n## Input\n\nThe first line contains two integers $N$ and $M$, the lengths of the strings $S$ and $T$, respectively.\nThe second line contains the string $S$.\nThe third line contains the string $T$.\n\n## Output\n\nThe length of the shortest abbreviation of $S$.\n\n## Limits\n\n- $1 \\leq N \\leq 500$.\n- $1 \\leq M \\leq 500$.\n- $S \\neq T$.\n- $S$ and $T$ contain only lowercase English letters.\n\n## Sample Input\n\n```\n5 5\nswerc\nseerc\n```\n\n## Sample Output\n\n```\n3\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2022_J", "prompt": "# Problem Statement: Justice Served\n\nYou finally managed to produce the ultimate stroopwafel with just the right number of squares on it. After the hard work, you left the stroopwafel unattended for a few seconds to get yourself a hot drink. Full of anticipation for your delicious treat, you came back just to see that your stroopwafel was gone! Even though you were only away for a short time, someone used the opportunity to steal it.\n\nYou looked at the security recordings and saw a total of $n$ suspects that had been in the room where you left your stroopwafel, each entering and leaving the room exactly once. After seeing this, you already had a good idea who took it since your archrival Rob -- who has some background in robberies -- was among the suspects. But you wanted to give him the benefit of the doubt and decided to interrogate every suspect. Unsurprisingly, every suspect claimed their own innocence. However, some suspects also provided an alibi for other suspects. Specifically, a suspect $A$ provided an alibi for suspect $B$ if and only if $A$ was in the room for the entire duration $B$ was in the room.\n\nYou feel like a suspect is more convincing if they have an alibi provided by a suspect who is convincing themselves. Formally, a suspect without an alibi has *convincingness* $0$. Otherwise, their convincingness is $1$ more than the convincingness of the most convincing suspect who provides them with an alibi. Your task is to compute the convincingness of each suspect.\n\n## Input\n\nThe input consists of:\n- One line with a single integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), the number of suspects.\n- $n$ lines, each with two integers $a$ and $t$ ($1 \\leq a, t \\leq 10^9$), the time at which each suspect arrived and the duration they stayed.\n\nIt is guaranteed that no two suspects who arrived at the same moment stayed for the same duration.\n\n## Output\n\nOutput the convincingness of each suspect.\n\n## Sample Input 1\n\n```\n4\n2 8\n1 7\n4 5\n5 2\n```\n\n## Sample Output 1\n\n```\n0 0 1 2\n```\n\n## Sample Input 2\n\n```\n5\n2 4\n3 3\n2 2\n4 2\n4 1\n```\n\n## Sample Output 2\n\n```\n0 1 1 2 3\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2022_H", "prompt": "# High-quality Tree\n\nThe binary search tree is one of the most useful data structures in computer science. Many methods exist to keep them balanced, such as using tree rotations (like in AVL-trees) or randomness (like in treaps). One thing that these methods have in common is that they are all somewhat slow and complicated.\n\nBut this is all about to change! Rob the computer scientist has invented a new method to keep rooted binary trees balanced, that is much better than the current state-of-the-art. The main idea is to repeatedly perform an operation Rob calls a *robbery*. One robbery is to take a leaf from the tree, and remove it. By applying robberies at the right times, Rob is able to keep a tree balanced in $\\mathcal{O}(1)$ amortized time.\n\nSome people have criticized Rob's revolutionary discovery, saying that removing elements from the tree makes the algorithm incorrect. Rob does not agree that this is a big problem; if you plan to store $2 \\cdot 10^5$ numbers, you probably do not need all of them. But Rob accepts the criticism and decides to find a way to minimize the number of robberies.\n\nYou are given a rooted binary tree with $n$ vertices. The vertices are numbered from $1$ to $n$, and vertex $1$ is the root. Your task is to find the minimum number of robberies to make the tree *strongly balanced*, meaning that all of its subtrees are balanced. A rooted binary tree is called balanced if the depth of its left and right subtrees differ by at most one. Recall that a robbery is simply to take a leaf and remove it, and doing so may turn its parent vertex into a leaf. See the illustration below for an example.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), the number of vertices in the tree.\n- $n-1$ lines, each with two integers $u$ and $v$ ($1 \\leq u, v \\leq n$, $u \\neq v$), indicating an edge between vertices $u$ and $v$.\n\nIt is guaranteed that the given edges form a valid binary tree with vertex $1$ as the root. However, the edges can appear in any order and are not directed: $u$ can be the parent of $v$ or the other way around.\n\n## Output\n\nOutput the minimum number of leaves you need to remove to make the tree strongly balanced.\n\n## Sample Input 1\n```\n6\n1 2\n1 3\n3 4\n3 5\n5 6\n```\n\n## Sample Output 1\n```\n1\n```\n\n## Sample Input 2\n```\n12\n1 2\n2 3\n3 4\n3 5\n1 6\n6 7\n7 8\n7 9\n9 10\n6 11\n11 12\n```\n\n## Sample Output 2\n```\n3\n```\n\n### Illustration of Sample Input 2\nThe tree becomes strongly balanced after removing the three vertices marked in red ($4$, $5$, and $10$); the minimum number of vertices that need to be removed to make the tree strongly balanced.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2023_F", "prompt": "### Problem Statement: Programming-Trampoline-athlon!\n\n**Time Limit:** 1 second\n\nProgramming competitions are fun and exciting. Programming should be an Olympic sport! At least, this is what we believe. However, when we suggested this to some of our friends, they did not seem to share our excitement. So, we decided to suggest a combined sport that will be more interesting to watch: Programming-Trampoline-athlon! (We are still working on the name.)\n\nThe idea is as follows. This is a team sport, where each team comprises of 3 members. The team has at its disposal 1 hour, 1 computer, and 1 trampoline. At all times, there must be at most one team member using the computer and at least one team member jumping on the trampoline. At the beginning of the competition, the team is given 6 programming problems and 6 trampoline elements (exercises).\n\nThe team decides how to partition the trampoline elements between its members, such that each team member has to perform 2 of the given elements on the trampoline. The programming tasks are solved cooperatively by the team members, but no one member can spend more than 25 minutes on the computer in total. The scoring is comprised of two parts, which are added together:\n- The programming score ranges between 0 and 60. The team receives 10 points for every correctly solved problem.\n- The trampoline score ranges between 0 and 40. Each of the 6 trampoline elements receives a score from the judges that ranges between 0 and 10. The final trampoline execution score is determined by dropping the highest and lowest of the 6 scores, and then adding up the remaining 4 scores.\n\nBefore we pitch this new sport to the International Olympic Committee, we want everything to be ready in order to show them just how serious we are. Thus, each team should receive a medal when no more than two other teams obtained a strictly higher score. However, in order to cope with a recent shortage of medals, the jury was instructed to make sure that there would be no more than 1,000 teams deserving a medal. We ask you to write a program that determines the medallists, given the performance of the different teams.\n\n#### Input\nThe first line contains the number $N$ of competing teams. Then follow $N$ lines. Each of these lines describes a team and contains space-separated values $C$, $P$, $E_1$, $E_2$, $E_3$, $E_4$, $E_5$, $E_6$; where:\n- $C$ is a five-letter code used to identify the team.\n- $P$ is an integer specifying the number of problems the team solved.\n- $E_i$ is an integer specifying the execution score of trampoline element number $i$.\n\n#### Output\nThe output should contain $M$ lines, where $M$ is the number of medallists. Each line should represent a medallist team, by containing two space-separated values $C$ and $S$, where:\n- $C$ is the team code.\n- $S$ is the total score of the team.\n\nThe medallist teams should be listed in decreasing total score order. In case of ties, they should be listed by input order.\n\n#### Limits\n- $3 \\leq N \\leq 100,000$\n- $3 \\leq M \\leq 1,000$\n- $C$ consists of five uppercase English letters.\n- $0 \\leq P \\leq 6$\n- $0 \\leq E_i \\leq 10$ for all $1 \\leq i \\leq 6$\n- Different teams always have different team codes.\n\n### Sample Input 1\n```\n5\nEMAIL 3 5 6 7 8 9 10\nCRASH 2 7 1 8 2 8 1\nMOUSE 4 0 9 3 9 1 7\nSWERC 6 3 1 4 1 5 9\nPAINT 6 0 0 0 0 0 10\n```\n\n### Sample Output 1\n```\nSWERC 73\nEMAIL 60\nMOUSE 60\nPAINT 60\n```\n\n### Sample Input 2\n```\n4\nCRAZY 4 0 2 4 6 8 10\nJAZZY 2 9 9 9 9 9 9\nJUICY 3 2 9 10 9 10 1\nFUZZY 5 0 1 1 2 3 5\n```\n\n### Sample Output 2\n```\nCRAZY 60\nJUICY 60\nFUZZY 57\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2023_E", "prompt": "### Problem Statement\n\nParis is so crowded with tourists during the Olympic games! You want to escape the city and go on a hike on a linear trail path, going from left to right. Every kilometre on that trail, including at the start and end, is a milestone, on which is written the stone's altitude. The slope between two consecutive stones is constant, and no two stones have the same altitude.\n\nPlanning to come back with your friends, you try to identify the point of the hike at which you had the nicest view. The beauty of a point of view is defined as the distance (measured in kilometres) between your position and the leftmost position that you can see on your hike and that is at the same altitude as you are. If such a previous position fails to exist, it means that you can see the city and its smog, and the beauty of that view is zero.\n\nYou have listed the altitudes of the milestones. What is the maximal beauty on your hike?\n\n### Input\nThe input consists of two lines. The first line contains a single integer $N$, which is the number of milestones on the trail path. The second line contains $N$ space-separated integers $H_1, H_2, \\ldots, H_n$; each integer $H_k$ is the altitude (measured in metres) of the $k$-th milestone on the path.\n\n### Output\nThe output should contain a single line, consisting of a single number $S$: the best beauty score on your hike. This number is written either as an integer or as an irreducible fraction $N / D$ for which $D \\geq 2$; we recall that a fraction $N / D$ is irreducible when the greatest common divisor of $N$ and $D$ is 1.\n\n### Limits\n- $1 \\leq N \\leq 100000$;\n- $0 \\leq H_k \\leq 1000000$ for all $k \\leq N$;\n- the integers $H_k$ are pairwise distinct.\n\n### Sample Input 1\n```\n7\n0 5 3 1 4 8 2\n```\n\n### Sample Output 1\n```\n13/4\n```\n\n### Sample Input 2\n```\n5\n3 5 8 7 1\n```\n\n### Sample Output 2\n```\n0\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2023_K", "prompt": "### Problem: Team Selection\n\n**Time limit:** 6 seconds\n\nTwo team leaders get to assemble their teams by choosing team members among a set of players that are numbered from 1 to $N$. The leaders take turns, each picking the $k$th player among the remaining ones, according to their ideas of which one of the remaining players would be the best addition to their teams.\n\nGiven the choices of the two leaders (the first team leader starts first), please compute the list of players in each team.\n\n#### Input\nThe input consists of three lines:\n- The first line contains a single integer $N$.\n- The second line contains $N / 2$ space-separated integers $a_1, a_2, \\ldots, a_{N/2}$ representing the choices of the first team leader: during the $(2k - 1)$th turn, the first leader chose the $a_k$th remaining player.\n- The third line contains $N / 2$ space-separated integers $b_1, b_2, \\ldots, b_{N/2}$ representing the choices of the second team leader: during the $2k$th turn, the second leader chose the $b_k$th remaining player.\n\n#### Output\nThe output should contain two lines, each containing $N / 2$ space-separated integers:\n- The first line should contain the list $x_1, x_2, \\ldots, x_{N/2}$ of the players chosen to become members of the first team, in the order they were chosen: the player $x_k$ was chosen during the $(2k - 1)$th turn.\n- The second line should contain the list $y_1, y_2, \\ldots, y_{N/2}$ of the players chosen to become members of the second team, in the order they were chosen: the player $y_k$ was chosen during the $2k$th turn.\n\n#### Limits\n- $2 \\le N \\le 4000000$\n- $N$ is a multiple of 2\n- The choices of the team leaders are valid: at each step, they are between 1 and the number of remaining players (inclusive).\n\n#### Sample Input\n```\n4\n1 1\n2 1\n```\n\n#### Sample Output\n```\n1 2\n3 4\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2022_I", "prompt": "# Interview Question\n\n**Fizz Buzz** is a party game that is often used as a programming exercise in job interviews. In the game, there are two positive integers $a$ and $b$, and the game consists of counting up through the positive integers, replacing any number by `Fizz` if it is a multiple of $a$, by `Buzz` if it is a multiple of $b$, and by `FizzBuzz` if it is a multiple of both $a$ and $b$. The most common form of the game has $a=3$ and $b=5$, but other parameters are allowed.\n\nYour task here is to solve the reverse problem: given a transcript of part of the game (not necessarily starting at 1), find possible values of $a$ and $b$ that could have been used to generate it.\n\nFigure 1 shows some sample sequences for various values of $a$ and $b$.\n\n**Example sequences for Fizz Buzz:**\n\n- $a=3, b=5:$ `1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz`\n- $a=6, b=2:$ `1 Buzz 3 Buzz 5 FizzBuzz 7 Buzz 9 Buzz 11 FizzBuzz 13`\n- $a=4, b=4:$ `1 2 3 FizzBuzz 5 6 7 FizzBuzz 9 10 11 FizzBuzz 13 14`\n\n## Input\n\nThe input consists of:\n- One line with two integers $c$ and $d$ ($1 \\le c \\le d \\le 10^5$), indicating that your transcript starts at $c$ and ends at $d$.\n- One line with $d-c+1$ integers and strings, the contents of the transcript.\n\nIt is guaranteed that the transcript is valid for some integers $a$ and $b$ with $1 \\le a, b \\le 10^6$, according to the rules laid out above.\n\n## Output\n\nOutput two positive integers $a$ and $b$ ($1 \\le a, b \\le 10^6$) that are consistent with the given transcript.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n7 11\n7 8 Fizz Buzz 11\n```\n\n### Sample Output 1\n```\n3 5\n```\n\n### Sample Input 2\n```\n49999 50002\n49999 FizzBuzz 50001 Fizz\n```\n\n### Sample Output 2\n```\n2 125\n```\n\n### Sample Input 3\n```\n8 11\nBuzz Buzz FizzBuzz Buzz\n```\n\n### Sample Output 3\n```\n10 1\n```\n\n### Sample Input 4\n```\n10 15\n10 11 12 13 14 15\n```\n\n### Sample Output 4\n```\n8 23\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "easy"} +{"id": "nwerc2022_G", "prompt": "# Problem: Going in Circles\n\nHercule Poirot, world-renowned detective, was having a lovely cup of tea in his compartment on the Disorient Express when the train conductor rushed in. \"We have lost track of the number of train carriages,\" exclaimed the conductor. You see, this was no ordinary train, and had no first or last train carriage. Instead, the train carriages were connected to form a large cycle, causing the conductor's confusion.\n\nHercule thought for a moment. \"That is most peculiar,\" he said. \"But I may be able to help you.\" He reached over and grabbed the lamp from the side table. \"You see, each train carriage has a light switch like this one. By moving between the carriages and toggling these switches, we can determine the number of train carriages.\"\n\nThe conductor was sceptical, but agreed to try it. \"We are in a hurry,\" he said, \"so please determine $n$, the number of carriages that the train consists of, in at most $3n + 500$ steps.\" Here a step counts as either moving to an adjacent carriage or toggling a light switch in the current carriage. \"The only thing I am certain of is that $n$ is at least $3$ and at most $5000$.\"\n\n## Interaction\n\nThis is an interactive problem. Your submission will be run against an interactor, which reads the standard output of your submission and writes to the standard input of your submission. This interaction needs to follow a specific protocol:\n\nThe interactor first sends an integer $s$ ($s \\in \\{0,1\\}$), the state of the light switch in Hercule's initial carriage.\n\nYour submission may then send at most $3n + 500$ steps for Hercule to carry out, each by printing one line of the form `? $a$`, where $a$ is one of the following:\n\n- `left`, to move to the adjacent train carriage in the clockwise direction,\n- `right`, to move to the adjacent train carriage in the counter-clockwise direction, or\n- `flip`, to toggle the light switch in the current train carriage.\n\nAfter every step, the interactor replies with an integer $s$ ($s \\in \\{0,1\\}$), the state of the light switch in the train carriage that Hercule is currently in, after he has carried out the requested step.\n\nWhen you have determined the number of train carriages $n$, print one line of the form `! $n$` ($3 \\leq n \\leq 5000$), after which the interaction will stop. Printing the answer does not count as a query.\n\nThe interactor is not adaptive; the initial state of the light switches is determined by the interactor before any interaction takes place. Make sure you flush the buffer after each write. Using more than $3n + 500$ queries will result in a wrong answer verdict.\n\nA testing tool is provided to help you develop your solution.\n\n## Sample Interaction\n\n### Example 1\n```\n1\n? left\n0\n? right\n1\n? flip\n0\n? left\n1\n? right\n0\n! 3\n```\n\n### Example 2\n```\n0\n? flip\n1\n? left\n1\n? left\n0\n? right\n1\n? right\n0\n! 4\n```\n\nNote: The actual number of train carriages in the test case is not known in advance, and the interactor only provides the state of the light switch in the current carriage after each step.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2022_L", "prompt": "# Problem L: Vittorio Plays with LEGO Bricks\n**SWERC 2022-2023**\n\n## Problem Statement\n\nVittorio is playing with his new LEGO Duplo bricks. All the bricks have the shape of a square cuboid with a $2 \\times 2$ square base and a height of $1$. They can be arranged in the 3D space to build structures, provided that the following rules are met:\n1. No two bricks can intersect, but they can touch on their faces.\n2. The corners of every brick must have integer coordinates (so bricks are axis-aligned) and the $z$ coordinates of all corners must be non-negative.\n3. The square bases of every brick must be parallel to the ground (i.e., the plane $z = 0$).\n4. The lower base of any brick that is not touching the ground must touch the upper base of some other brick in a region of positive area (when this happens, the two bricks stay attached to each other thanks to small studs).\n\nFor example, this is a valid structure:\n\nVittorio wants to build a structure that includes purple bricks in the following $n$ positions: $(a_i, 0, h)$, where $1 \\leq i \\leq n$ \u2014 these are the coordinates of the centers of their lower bases; note that all of these bricks have $y$ coordinate equal to $0$ and $z$ coordinate equal to $h$. Vittorio will use additional bricks of other colors to support the purple bricks. He is willing to place bricks only in positions where the center of the lower base has $y$ coordinate equal to $0$. What is the minimum number of additional bricks needed?\n\nIt can be shown that a valid construction always exists.\n\n## Input\nThe first line contains two integers $n$ and $h$ ($1 \\leq n \\leq 300$, $0 \\leq h \\leq 10^9$) \u2014 the number of purple bricks and their common $z$ coordinate.\nThe second line contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq 10^9$, $a_i < a_{i+1}$) \u2014 the $x$ coordinates of the purple bricks (centers of the bases), given in increasing order.\n\n## Output\nPrint the minimum number of additional bricks needed.\n\n## Samples\n\n### Sample Input 1\n```\n4 0\n2 7 11 13\n```\n\n### Sample Output 1\n```\n0\n```\n\n### Explanation of Sample 1\nAll the purple bricks lie on the ground, so no additional bricks are needed.\n\n### Sample Input 2\n```\n4 1\n2 7 11 13\n```\n\n### Sample Output 2\n```\n3\n```\n\n### Explanation of Sample 2\nVittorio will have to place supporting bricks under the purple bricks, and he can use a single brick to support both the third and the fourth purple bricks. For example, he can place additional bricks at positions $(3, 0, 0)$, $(7, 0, 0)$, and $(12, 0, 0)$. It can be shown that it is impossible to build a valid construction using less than 3 additional bricks.\n\n### Sample Input 3\n```\n4 100\n2 7 11 13\n```\n\n### Sample Output 3\n```\n107\n```\n\n### Sample Input 4\n```\n4 3\n2 5 8 11\n```\n\n### Sample Output 4\n```\n8\n```\n\n### Explanation of Sample 4\nA possible structure that minimizes the number of additional bricks is shown in the problem description.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2023_I", "prompt": "### Problem: Isolated Island\n\nOn a small island far, far away, a handful of old men live isolated from the rest of the world. The entire island is divided into plots of land by fences, and each old man owns a single plot of land bounded by fences on all sides. (The region outside all fences is the ocean.) Each of the inhabitants needs fish to survive, and the only place where they can fish is the ocean surrounding them. Since not every plot of land is connected to the ocean, some of the men might need to pass through the land of others before being able to fish. The men can cross a single fence at a time, but cannot go through fenceposts or locations where fences intersect.\n\nUnfortunately, the old men are greedy. They demand one fish each time a person wants to enter their land. Since they do not want to lose too much fish to the others, every old man chooses a route that minimizes the number of fish he has to pay to get to the ocean.\n\nOver the years, this has led to rivalry between the old men. Each man hates all other men who have to pay less than him to reach the ocean. Two men only *like* each other if they have to pay the same amount of fish to reach the ocean.\n\nThe natural question which now occurs is: are there some old men on this island who are neighbours (owning land on opposite sides of a single fence) and like each other? See the illustrations of the first three Sample Inputs for examples of islands with opposite answers to this question.\n\n#### Input\nThe input consists of:\n- One line with an integer $n$ ($3 \\le n \\le 1000$), the number of fences.\n- $n$ lines, each with four integers $x_1$, $y_1$, $x_2$, and $y_2$ ($\\left|x_1\\right|, \\left|y_1\\right|, \\left|x_2\\right|, \\left|y_2\\right| \\leq 10^6$, $(x_1,y_1) \\neq (x_2,y_2)$), indicating a straight fence between fenceposts at $(x_1,y_1)$ and $(x_2, y_2)$.\n\nNote that fences may intersect internally, and that three or more fences may intersect in the same location. It is guaranteed that any two fences intersect only in at most one point. Furthermore, after crossing a single fence, one always ends up in a different region. All regions together form a single island, where any region can be reached from any other region.\n\n#### Output\nIf there exists a pair of neighbours who like each other, then output \"yes\". Otherwise, output \"no\".\n\n#### Sample Inputs and Outputs\n\n**Sample Input 1**\n```\n6\n-3 -3 0 3\n-3 -3 0 0\n-3 -3 3 -3\n0 0 0 3\n0 0 3 -3\n0 3 3 -3\n```\n**Sample Output 1**\n```\nyes\n```\n\n**Sample Input 2**\n```\n6\n-6 -3 0 3\n0 3 6 -3\n6 -3 -6 -3\n-3 0 3 0\n3 0 0 -3\n0 -3 -3 0\n```\n**Sample Output 2**\n```\nno\n```\n\n**Sample Input 3**\n```\n8\n0 1 2 1\n2 2 0 0\n1 2 1 0\n1 0 2 1\n0 0 2 0\n1 2 2 2\n0 1 0 0\n2 2 2 0\n```\n**Sample Output 3**\n```\nyes\n```\n\n**Sample Input 4**\n```\n4\n0 0 1 0\n1 0 1 1\n1 1 0 1\n0 1 0 0\n```\n**Sample Output 4**\n```\nno\n```\n\n**Illustrations of the Samples**\n- In Sample Input 1, every man has direct access to the ocean, so they all like each other.\n- In Sample Input 2, there does not exist a pair of neighbours who like each other, because the man living in the middle needs to pay one fish, whereas all of his neighbours do not have to pay any fish to reach the ocean.\n- In Sample Input 3, there are six men, some of whom are friendly neighbours.\n- In Sample Input 4, there are no pairs of neighbours who like each other.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2024_C", "prompt": "# Problem Statement\n\nIn the town of Nattanham, all roads run either north to south, or east to west, and span the entire town. Furthermore, all roads are an equal distance apart. This makes navigating the town extremely easy.\n\nUnfortunately, the roads are quite poor and could do with a fresh layer of asphalt. However, there is not enough money to fix all the roads, so some sections of road need to be given priority.\n\nThe mayor has selected five locations in town that he considers to be of great importance: the city hall, the police station, the hospital, the fire department, and of course the mayor's house. Each of these locations is at an intersection.\n\nThe mayor wishes that, for each pair of these important locations, it becomes possible to get from one to the other along a shortest path that consists entirely of refurbished road. Within this restriction, the mayor would like to refurbish the smallest amount of road. The intersections do not count toward this amount.\n\nGiven are five locations in a city grid with square blocks, with coordinates up to $1000$. Refurbish a set of streets in the grid, such that:\n- for any two locations there exists a shortest path between them that only uses refurbished streets; and\n- the total length of the refurbished streets is minimized.\n\nOutput the minimum number of road segments that need to be refurbished.\n\n## Input\n\nThe input consists of:\n- Five lines, each with two integers $x$ and $y$ ($0 \\le x, y \\le 1000$), the grid coordinates of each of the five important locations.\n\nIt is guaranteed that the locations are distinct.\n\n## Output\n\nOutput the minimum number of road segments that need to be refurbished.\n\n### Sample Input 1\n```\n8 1\n3 4\n6 7\n10 4\n1 2\n```\n\n### Sample Output 1\n```\n22\n```\n\n### Sample Input 2\n```\n0 0\n0 10\n20 0\n20 10\n3 3\n```\n\n### Sample Output 2\n```\n70\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2024_M", "prompt": "# Problem Statement\n\nYou are given a convex polygon with $n$ vertices ($3 \\le n \\le 2 \\cdot 10^5$), with a mouse sitting at each vertex. A cat jumps to some point inside that polygon. For any location of the cat, one can count the number of *encirclements*: sets of three mice such that the cat is in the triangle spanned by the mice. Find the expected value for the number of encirclements when the location of the cat is uniformly random inside the polygon. The coordinates $x, y$ are up to $10^7$ in absolute value. The absolute or relative error of your answer must be at most $10^{-4}$.\n\n## Input\nThe input consists of:\n- One line with an integer $n$ ($3 \\leq n \\leq 2 \\cdot 10^5$), the number of mice.\n- $n$ lines, each with two integers $x$ and $y$ ($|x|, |y| \\leq 10^7$), the coordinates of a mouse.\n\nThe coordinates of the mice are given in counterclockwise order and form a strictly convex polygon with non-zero area. A strictly convex polygon is a convex polygon such that no three consecutive vertices are on a straight line.\n\n## Output\nOutput the expected number of encirclements after Medea lands inside the polygon.\n\nYour answer should have an absolute or relative error of at most $10^{-4}$.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```plaintext\n4\n0 0\n1 0\n1 1\n0 1\n```\n\n### Sample Output 1\n```plaintext\n2.0\n```\n\n### Sample Input 2\n```plaintext\n5\n0 0\n1 0\n2 1\n1 2\n0 2\n```\n\n### Sample Output 2\n```plaintext\n3.66666667\n```\n\n### Sample Input 3\n```plaintext\n3\n-3141592 -2718281\n-3141593 -2718281\n-3141592 -2718282\n```\n\n### Sample Output 3\n```plaintext\n1.0\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "nwerc2023_F", "prompt": "# Fixing Fractions\n\nMaths is hard. But it could be easier! And the internet has found some excellent ways to make it easier. Take a look at the following true equations:\nFollowing the patterns, we come to the conclusion that the following equation should also be true:\nHowever, this is actually wrong in boring old standard maths. Therefore, we define a new kind of funky maths where it is allowed to cancel out digits on the left side of the equality sign. This surely will make everyone's life easier. Except yours, since you have to evaluate if two given fractions are equal in our new funky maths.\n\n## Input\nThe input consists of:\n- One line with four integers $a$, $b$, $c$, and $d$ ($1 \\leq a, b, c, d < 10^{18}$), describing the two fractions $\\frac{a}{b}$ and $\\frac{c}{d}$.\n\n## Output\nIf there exist integers $a'$ and $b'$ obtained from $a$ and $b$ by cancelling out the same digits and with $\\frac{a'}{b'} = \\frac{c}{d}$ in standard mathematics, output \"possible\", followed by $a'$ and $b'$.\nOtherwise, output \"impossible\".\n\nIf there are multiple valid solutions, you may output any one of them.\n\nNote that neither $a'$ nor $b'$ is allowed to contain leading zeroes after cancelling digits.\n\n## Sample Input 1\n```\n163 326 1 2\n```\n\n## Sample Output 1\n```\npossible\n1 2\n```\n\n## Sample Input 2\n```\n871 1261 13 39\n```\n\n## Sample Output 2\n```\npossible\n87 261\n```\n\n## Sample Input 3\n```\n123 267 12339 23679\n```\n\n## Sample Output 3\n```\nimpossible\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2023_A", "prompt": "# Problem: Arranging Adapters\n\nIt is the day before the NWERC and you and your team are on the train towards Delft. The journey is long and boring but you came up with a good idea: \"Let's do some *train*ing.\"\n\n-- silence --\n\nYou take your laptop out and try to plug it in when you notice that the only socket is already in use. Your friends smirk and reply: \"No socket for you, no *train*ing for us.\" Their smirks quickly fade as you pull out a power strip, unplug the charger from the socket, and plug it back into the power strip. Now, there is enough space for your charger as well.\n\nHowever, as soon as more sockets are available, your friends suddenly take out more devices that need to be charged. You realize that you will not get them to train like this, so you decide to trick them into solving a problem instead.\n\nYour power strip comprises a row of $s$ sockets, and each socket is $3\\,\\text{cm}$ in diameter. Furthermore, as you examine the chargers, you notice that they all have integer lengths. The plug of each charger is always on one of the two ends, and each charger can only be used in two orientations. Chargers cannot overlap, but can touch, and can extend beyond the end of the power strip as long as they are plugged into a socket.\n\nNow you challenge them to charge as many devices as possible. This is visualized in the illustration below. Hoping that this allows them to avoid the *train*ing, your friends agree to write a program to solve this.\n\n## Input\nThe input consists of:\n- One line with two integers $n$ and $s$ ($1 \\leq n \\leq 2 \\cdot 10^5$, $1 \\leq s \\leq 10^9$), the number of chargers you have and the number of sockets on the power strip.\n- One line with $n$ integers $w$ ($3 \\leq w \\leq 10^9$), the width of each charger in centimetres.\n\nNote that you are allowed to rotate chargers by $180^\\circ$ before plugging them in.\n\n## Output\nOutput the maximum number of chargers you can plug into the power strip at the same time.\n\n## Sample Input 1\n```\n5 7\n7 4 4 5 8\n```\n\n## Sample Output 1\n```\n5\n```\n\n## Sample Input 2\n```\n8 9\n7 4 3 6 4 8 5 6\n```\n\n## Sample Output 2\n```\n6\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2024_K", "prompt": "# Problem Statement\n\n## Problem Title\n\nEvery week, Karlijn and her teammates join the competitive programming training at their university. Thinking and coding for such a long time is quite exhausting, and they need a ton of snacks to get through training. They have divided the chore of bringing snacks neatly: while the other two bring stroopwafels and salt sticks, Karlijn's duty is to provide kruidnoten.\n\nShe usually gets them on the way from home to university just before training. The bicycle network in her home town consists of intersections which are connected by cycleways of different lengths. The intersections are numbered from $1$ to $n$. Karlijn's house is at intersection $1$, and her university is at intersection $n$.\n\nThere are multiple stores that sell kruidnoten, but some of them are often out of stock. Karlijn wants to get to university as quickly as possible, so she has a habit of looking up online which stores still have kruidnoten before leaving her house. Using this information, she then takes the shortest path via some stocked store. An example is visualized in the figure below.\n\nNow, she wonders how much time she should usually plan for her way to training. From long-time experience, Karlijn knows for each store how likely it is that they have not sold out. In particular, she observed that the stock of kruidnoten is independent for each store. What is the expected length of a shortest path from Karlijn's house to university if she wants to visit some store that has kruidnoten in stock?\n\n## Input\nThe input consists of:\n- One line with three integers $n$, $m$, and $k$ ($2 \\leq n \\leq 2 \\cdot 10^5$, $1 \\leq m \\leq 2 \\cdot 10^5$, $1 \\leq k \\leq n$), the number of intersections, cycleways, and stores that may sell kruidnoten.\n- $m$ lines, each with three integers $i$, $j$, and $\\ell$ ($1 \\leq i, j \\leq n$, $i \\neq j$, $1 \\leq \\ell \\leq 10^6$), indicating that the intersections $i$ and $j$ are connected by a cycleway of length $\\ell$. It is guaranteed that every pair of intersections is connected by at most one cycleway. Further, it is possible to get from every intersection to every other intersection by bike.\n- $k$ lines, each with one integer $i$ ($1 \\leq i \\leq n$) and one floating-point number $p$ ($0 < p \\leq 1$ with at most four digits after the decimal point), indicating that there is a store located at intersection $i$, and that the probability that it still has kruidnoten is $p$. It is guaranteed that there is at most one kruidnoten store at each intersection.\n\n## Output\n\nIf the event that Karlijn cannot get any kruidnoten on her way has probability $> 0$, output \"impossible\". Otherwise, output the expected length of a shortest path from her home to university if she gets kruidnoten on the way. Your answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n5 5 3\n1 2 6\n3 1 4\n4 5 2\n1 4 1\n3 4 5\n2 1.0\n3 0.4\n5 0.1\n```\n\n## Sample Output 1\n```\n12.36\n```\n\n## Sample Input 2\n```\n6 5 2\n1 2 1\n1 3 1\n4 5 3\n5 6 1\n6 3 2\n1 0.6283\n4 0.3142\n```\n\n## Sample Output 2\n```\nimpossible\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "nwerc2022_F", "prompt": "# Problem Statement\n\n## Problem Title: Faster Than Light\n\n* Determine whether it is possible to hit all rooms in a spaceship with a single, infinite-length beam.\n* The spaceship is represented by a set of $1 \\leq n \\leq 2 \\cdot 10^5$ axis-aligned non-intersecting rectangles ($0 \\leq x_1 < x_2 \\leq 10^9$ and $0 \\leq y_1 < y_2 \\leq 10^9$).\n\n![Illustration of Sample Input 1, which consists of five grey rooms. The hull beam in red hits all rooms and is the only valid solution in this case.](sample)\n\n## Input\n\nThe input consists of:\n* One line with an integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), the number of rooms.\n* $n$ lines, each with four integers $x_1$, $y_1$, $x_2$, and $y_2$ ($0 \\leq x_1 < x_2 \\leq 10^9$ and $0 \\leq y_1 < y_2 \\leq 10^9$), describing the coordinates of two opposite corners ($x_1$,$y_1$) and ($x_2$,$y_2$) of a room.\n\nIt is guaranteed that no two rooms have a common interior point.\n\n## Output\n\nIf it is possible for the hull beam to pass through all rooms at once, output `possible`.\nOtherwise, output `impossible`.\n\n## Sample Input/Output\n\n### Sample Input 1\n```\n5\n1 3 3 4\n2 2 4 3\n4 1 5 3\n5 2 7 3\n6 3 8 4\n```\n\n### Sample Output 1\n```\npossible\n```\n\n### Sample Input 2\n```\n4\n1 1 2 2\n1 3 2 4\n3 1 4 2\n3 3 4 4\n```\n\n### Sample Output 2\n```\nimpossible\n```\n\n### Sample Input 3\n```\n3\n1 1 2 2\n1 3 2 4\n3 3 4 4\n```\n\n### Sample Output 3\n```\npossible\n```\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "hard"} +{"id": "swerc2022_F", "prompt": "# Problem F: Beppa and SwerChat\n## SWERC 2022-2023\n\n## Problem Description\n\nBeppa and her circle of geek friends keep up to date on a group chat in the instant messaging app SwerChat\u2122. The group has $n$ members, excluding Beppa. Each of those members has a unique ID between 1 and $n$. When a user opens a group chat, SwerChat\u2122 displays the list of other members of that group, sorted by decreasing times of last seen online (so the member who opened the chat most recently is the first in the list). However, the times of last seen are not displayed.\n\nToday, Beppa has been busy all day: she has only opened the group chat twice, once at 9:00 and once at 22:00. Both times, she wrote down the list of members in the order they appeared at that time. Now she wonders: what is the minimum number of other members that must have been online at least once between 9:00 and 22:00?\n\nBeppa is sure that no two members are ever online at the same time and no members are online when Beppa opens the group chat at 9:00 and 22:00.\n\n## Input\n\nEach test contains multiple test cases. The first line contains an integer $t$ ($1 \\leq t \\leq 10000$) \u2014 the number of test cases. The descriptions of the $t$ test cases follow.\n\nThe first line of each test case contains an integer $n$ ($1 \\leq n \\leq 10^5$) \u2014 the number of members of the group excluding Beppa.\n\nThe second line contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq n$) \u2014 the list of IDs of the members, sorted by decreasing times of last seen online at 9:00.\n\nThe third line contains $n$ integers $b_1, b_2, \\ldots, b_n$ ($1 \\leq b_i \\leq n$) \u2014 the list of IDs of the members, sorted by decreasing times of last seen online at 22:00.\n\nFor all $1 \\leq i < j \\leq n$, it is guaranteed that $a_i \\neq a_j$ and $b_i \\neq b_j$.\n\nIt is also guaranteed that the sum of the values of $n$ over all test cases does not exceed $10^5$.\n\n## Output\n\nFor each test case, print the minimum number of members that must have been online between 9:00 and 22:00.\n\n## Sample Input\n\n```\n4\n5\n1 4 2 5 3\n4 5 1 2 3\n6\n1 2 3 4 5 6\n1 2 3 4 5 6\n8\n8 2 4 7 1 6 5 3\n5 6 1 4 8 2 7 3\n1\n1\n1\n```\n\n## Sample Output\n\n```\n2\n0\n4\n0\n```\n\n## Explanation of Sample 1\n\n- In the first test case, members 4 and 5 must have been online between 9:00 and 22:00.\n- In the second test case, it is possible that nobody has been online between 9:00 and 22:00.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "cpp", "difficulty": "medium"} +{"id": "swerc2022_E", "prompt": "# Problem E: Spinach Pizza\n## SWERC 2022-2023\n\n## Problem Statement\n\nThe two siblings, Alberto and Beatrice, have to eat a spinach pizza together. However, neither of them likes spinach, so they both want to eat as little as possible.\n\nThe pizza has the shape of a strictly convex polygon with $n$ vertices located at integer coordinates $(a_1, y_1), (a_2, y_2), \\ldots, (a_n, y_n)$ of the plane.\n\nThe siblings have decided to eat the pizza in the following way: taking turns, starting with Alberto, each sibling chooses a vertex of the remaining part of the pizza and eats out the triangle determined by its two neighboring edges. In this way, after each of the first $n - 3$ turns, the pizza will have one less vertex. The game ends after the $(n - 2)$-th turn, when all the pizza has been eaten.\n\nAssuming that Alberto and Beatrice choose the slices to eat optimally, which of the siblings manages to eat at most half of the pizza? You should identify a sibling that has a strategy to do so and help them choose the slices appropriately. Note that it is possible that both Alberto and Beatrice end up eating exactly half of the area if they choose their slices optimally.\n\n## Input\n\nThe first line contains a single integer $n$ ($4 \\leq n \\leq 100$) \u2014 the number of vertices.\n\nThe next $n$ lines contain two integers $a_i$ and $y_i$ each ($-10^6 \\leq a_i, y_i \\leq 10^6$) \u2014 the coordinates of the $i$-th vertex of the polygon representing the initial shape of the pizza.\n\nIt is guaranteed that the polygon is strictly convex and that its vertices are given in counterclockwise order.\n\n## Interaction\n\nFirst, you should print a line containing either the string `Alberto` or the string `Beatrice` \u2014 the sibling that you will help to win.\n\nThen, for the next $n - 2$ turns, you will alternate with the judge in choosing a slice of the pizza and removing it, starting with you if you chose to help Alberto, or starting with the judge if you chose to help Beatrice.\n\n- When it is your turn, print a single line containing an integer $p$ ($1 \\leq p \\leq n$) that has not been chosen before, indicating that you want to eat the slice determined by the vertex located at $(a_p, y_p)$.\n- When it is the judge's turn, read an integer $q$ ($1 \\leq q \\leq n$), indicating that the other player eats the slice determined by the vertex located at $(a_q, y_q)$. It is guaranteed that $q$ has not been chosen before.\n\nIf one of your interactions is malformed, the interactor terminates immediately and your program receives the verdict `WRONG-ANSWER`. Otherwise, you will receive `CORRECT` if at the end your player has eaten at most half of the pizza, and `WRONG-ANSWER` otherwise.\n\n## Notes\n\nAfter printing a line, do not forget to end the line and flush the output. Otherwise, you will get the verdict `TIMELIMIT`. To flush the output, use:\n- `fflush(stdout)` in C\n- `fflush(stdout)`, `cout << flush` or `cout.flush()` in C++\n- `System.out.flush()` in Java and Kotlin\n- `sys.stdout.flush()` in Python\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n4\n0 0\n6 1\n5 3\n1 4\n```\n\n### Sample Output 1\n```\nAlberto\n2\n```\n\n### Explanation of Sample 1\nThe pizza has an area of 15. Alberto can eat less than half of the pizza by eating the slice around vertex 2 (which has an area of 6.5) or around vertex 3 (which has an area of 3.5).\n\n### Sample Input 2\n```\n6\n0 0\n2 0\n3 2\n2 4\n0 4\n-1 2\n```\n\n### Sample Output 2\n```\nAlberto\n2\n```\n\n### Explanation of Sample 2\nIt can be proved that both players will eat exactly half of the pizza if they eat optimally. Therefore, it is possible to choose to help either Alberto or Beatrice.\n\n### Sample Input 3\n```\n7\n0 0\n2 0\n5 2\n4 5\n1 5\n-1 4\n-1 2\n```\n\n### Sample Output 3\n```\nBeatrice\n7\n2\n5\n4\n6\n```\n\n### Explanation of Sample 3\nIt is possible to show that only Beatrice has a strategy to eat at most half of the pizza. The following is an example of a valid interaction (after reading the input):\n\n| Contestant | Judge | Explanation |\n|------------|-------|------------|\n| Beatrice | | The contestant will help Beatrice |\n| 7 | | Alberto eats the triangle with vertices 6, 7, 1 and area 1 |\n| | 2 | Beatrice eats the triangle with vertices 1, 2, 3 and area 2 |\n| 5 | | Alberto eats the triangle with vertices 4, 5, 6 and area 1.5 |\n| | 4 | Beatrice eats the triangle with vertices 3, 4, 6 and area 8 |\n| 6 | | Alberto eats the triangle with vertices 3, 6, 1 and area 11 |\n| | | The total area eaten by Alberto is 13.5 and the total area eaten by Beatrice is 10, which is less than half the area of the whole pizza. The actions performed by the contestant and the judge in this example of interaction may be non-optimal. |\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2023_A", "prompt": "### Problem Statement\n\n**Card Game**\n\n**Time Limit:** 1 second\n\nThe Olympic Games in Paris are almost here, and you are thrilled! You and four of your friends managed to get five of the rare tickets for sports climbing, even though all tickets were sold out in less than two hours. While waiting for the games to start, you decide to do something fun to keep your mind off the wait: play your favourite card game.\n\nThe card deck contains four standard suits of different colours: silver (S), white (W), emerald (E), and red (R), as well as one trump suit coloured cyan (C). That is, the cyan cards outrank all other cards. There are $N$ cards of each suit, numbered from 1 to $N$. This means that, in total, the deck comprises $5N$ cards. At the beginning of the game, the deck is randomly distributed between the five players, such that each player gets $N$ cards.\n\nBefore you start playing, you want to organise your cards such that all cards of the same suit are next to each other in increasing order, and the trump cards appear at the end (also in increasing order). When you receive your cards, they appear in your hand as a sequence. To organise them, you perform a sequence of actions, where in each action you take one card out of your hand and put it back in your hand at another position (between two cards, before the first card, or after the last card).\n\nYou cannot help but wonder: what is the minimum number of actions you need to take in order to organise your hand?\n\n**Input:**\nThe input consists of two lines. The first line contains the number $N$. The second line contains $N$ space-separated values describing the sequence of cards in your hand. Each value is composed of one letter of the set [S, W, E, R, C] (describing the card suit), followed by an integer $V$ such that $1 \\leq V \\leq N$ (describing the card number).\n\n**Output:**\nThe output should contain a single line, consisting of a single number: the minimum number of actions required to organise your hand.\n\n**Limits:**\n- $1 \\leq N \\leq 100000$\n\n### Sample Inputs and Outputs\n\n**Sample Input 1**\n```\n4\nC1 R2 E4 R1\n```\n\n**Sample Output 1**\n```\n2\n```\n\n**Sample Input 2**\n```\n5\nS2 W4 E1 R5 C1\n```\n\n**Sample Output 2**\n```\n10\n```\n\n### Explanation\n\nIn the first sample input, the sequence of cards is \"C1 R2 E4 R1\". To organise the cards, you can perform the following actions:\n1. Move \"R1\" to the position before \"R2\" to get \"C1 R1 R2 E4\".\n2. Move \"E4\" to the end to get \"C1 R1 R2 E4\".\n\nThus, the minimum number of actions required is 2.\n\nIn the second sample input, the sequence of cards is \"S2 W4 E1 R5 C1\". The sequence needs to be organised as \"S1 S2 W1 W2 W3 W4 E1 E2 E3 E4 R1 R2 R3 R4 R5 C1\". The minimum number of actions required to achieve this is 10.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2022_B", "prompt": "# Problem B: Uniform Chemistry\n**SWERC 2022-2023**\n\n## Problem Statement\n\nIn a parallel universe, there are $n$ chemical elements, numbered from 1 to $n$. The element number $n$ has not been discovered so far, and its discovery would be a pinnacle of research and would bring the person who does it eternal fame and the so-called SWERC prize.\n\nThere are $m$ independent researchers, numbered from 1 to $m$, that are trying to discover it. Currently, the $i$-th researcher has a sample of the element $s_i$. Every year, each researcher independently does one fusion experiment. In a fusion experiment, if the researcher currently has a sample of element $a$, they produce a sample of an element $b$ that is chosen uniformly at random between $a + 1$ and $n$, and they lose the sample of element $a$. The elements discovered by different researchers or in different years are completely independent.\n\nThe first researcher to discover element $n$ will get the SWERC prize. If several researchers discover the element in the same year, they all get the prize. For each $i = 1, 2, ..., m$, you need to compute the probability that the $i$-th researcher wins the SWERC prize.\n\n## Input\n\nThe first line contains two integers $n$ and $m$ ($2 \\leq n \\leq 100$, $1 \\leq m \\leq 10$) \u2014 the number of elements and the number of researchers.\nThe second line contains $m$ integers $s_1, s_2, \\ldots, s_m$ ($1 \\leq s_i < n$) \u2014 the elements that the researchers currently have.\n\n## Output\n\nPrint $m$ floating-point numbers. The $i$-th number should be the probability that the $i$-th researcher wins the SWERC prize. Your answer is accepted if each number differs from the correct number by at most $10^{-8}$.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n2 3\n1 1 1\n```\n\n### Sample Output 1\n```\n1.0 1.0 1.0\n```\n\n**Explanation of Sample 1:**\nAll researchers will discover element 2 in the first year and win the SWERC prize.\n\n### Sample Input 2\n```\n3 3\n1 1 2\n```\n\n### Sample Output 2\n```\n0.5 0.5 1.0\n```\n\n**Explanation of Sample 2:**\nThe last researcher will definitely discover element 3 in the first year and win the SWERC prize. The first two researchers have a 50% chance of discovering element 2 and a 50% chance of discovering element 3, and only element 3 will bring them the prize.\n\n### Sample Input 3\n```\n3 3\n1 1 1\n```\n\n### Sample Output 3\n```\n0.625 0.625 0.625\n```\n\n**Explanation of Sample 3:**\nEach researcher has an independent 50% chance of discovering element 3 in the first year, in which case they definitely win the SWERC prize. Additionally, if they all discover element 2 in the first year, which is a 12.5% chance, then they will all discover element 3 in the second year and all win the prize.\n\n### Sample Input 4\n```\n100 7\n1 2 4 8 16 32 64\n```\n\n### Sample Output 4\n```\n0.178593469 0.179810455 0.182306771\n0.187565366 0.199300430 0.229356322\n0.348722518\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2022_K", "prompt": "### Problem K: Train Splitting\n\n**SWERC 2022-2023**\n\n#### Train Splitting\n\n**Time Limit:** 2.0s \n**Memory Limit:** 2048MB\n\nThere are $n$ big cities in Italy, and there are $m$ train routes between pairs of cities. Each route connects two different cities bidirectionally. Moreover, using the trains, one can reach every city starting from any other city.\n\nRight now, all the routes are operated by the government-owned Italian Carriage Passenger Company, but the government wants to privatize the routes. The government does not want to give too much power to a single company, but it also does not want to make people buy a lot of different subscriptions. Additionally, it would like to give a fair chance to all companies. In order to formalize all these wishes, the following model was proposed:\n\n- There will be $k \\geq 2$ private companies indexed by 1, 2, ..., $k$. Each train route will be operated by exactly one of the $k$ companies.\n- For any company, there should exist two cities such that it is impossible to reach one from the other using only routes operated by that company.\n- On the other hand, for any two companies, it should be possible to reach every city from any other city using only routes operated by these two companies.\n\nFind a plan satisfying all these criteria. It can be shown that a viable plan always exists. Please note that you can choose the number $k$ and you do not have to minimize or maximize it.\n\n#### Input\n\nEach test contains multiple test cases. The first line contains an integer $t$ ($1 \\leq t \\leq 1000$) \u2014 the number of test cases. The descriptions of the $t$ test cases follow.\n\nThe first line of each test case contains two integers $n$ and $m$ ($3 \\leq n \\leq 50$, $n - 1 \\leq m \\leq \\frac{n(n - 1)}{2}$) \u2014 the number of cities and the number of train routes.\n\nThe next $m$ lines contain two integers $u_i$ and $v_i$ each ($1 \\leq u_i, v_i \\leq n$, $u_i \\neq v_i$) \u2014 the $i$-th train route connects cities $u_i$ and $v_i$.\n\nIt is guaranteed that the routes connect $m$ distinct pairs of cities. It is guaranteed that using the trains, one can reach every city starting from any other city.\n\nThe sum of the values of $n$ over all test cases does not exceed 5000.\n\n#### Output\n\nFor each test case, on the first line print an integer $k$ ($2 \\leq k \\leq m$) \u2014 the number of companies in your plan; on the second line print $m$ integers $c_1, c_2, \\ldots, c_m$ ($1 \\leq c_i \\leq k$) \u2014 in your plan, company $c_i$ operates the $i$-th route.\n\nIf there are multiple valid plans, you may print any of them.\n\n#### Sample Input 1\n```\n2\n5 9\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n3 3\n1 2\n3 1\n2 3\n```\n\n#### Sample Output 1\n```\n4\n1 2 3 1 4 2 2 4 3\n3\n2 3 1\n```\n\n#### Explanation of Sample 1\n\nIn the first test case, the output is illustrated in the following picture, where different colors correspond to different companies (blue for 1, red for 2, green for 3, and yellow for 4):\n\n- If we consider, for example, only companies 2 and 3, we can see that from any city it is possible to reach every other city (picture on the left below).\n- However, if we restrict to company 2 alone, it becomes impossible to reach city 5 from city 1 (picture on the right).\n\nIn the second test case, the output is illustrated in the following picture:\n\n- The plan ensures that no single company can connect all cities, but any two companies together can.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2024_K", "prompt": "# Problem: Disk Covering\n\nOn a vast, flat green meadow, there are several golden disks in the shape of perfect circles from ancient times. According to legend, if one chants a spell, the area covered by the disks will turn into flames, fending off enemy attacks. When the enemy comes, you can hide in a place completely surrounded by disks, yet not on the disks, thus isolated from the outside world by the flames.\n\nGiven the positions and sizes of the disks, determine whether such a hiding place exists.\n\n## Input\n\nThe first line contains an integer $N$, representing the number of disks.\nIn the following $N$ lines, the $i$th line contains three integers that describe disk $i$: the x-coordinate $x_i$, the y-coordinate $y_i$ of its center, and its radius $r_i$.\n\n## Output\n\nA single integer, $1$ if such a place exists, or $0$ otherwise.\n\n## Limits\n\n- $1 \\leqslant N \\leqslant 250$\n- $-10^9 \\leqslant x_i, y_i \\leqslant 10^9$ for all $i \\leqslant N$\n- $1 \\leqslant r_i \\leqslant 10^9$ for all $i \\leqslant N$\n- There are no three disks whose circular outlines intersect at a common point\n- Among all intersection points of the circular outlines of any two disks, the distance between any two intersection points is greater than or equal to 1\n- There are no two disks whose circular outlines are tangent to each other (i.e., have exactly one intersection point)\n- For two disks whose circular outlines do not intersect, the distance between any point on the circular outline of one disk and any point on the circular outline of the other disk is always greater than or equal to 1\n\n## Sample Inputs and Outputs\n\n### Sample 1\n\n#### Input\n```\n4\n-6 0 8\n-4 10 7\n4 4 6\n8 14 2\n```\n\n#### Output\n```\n0\n```\n\n#### Explanation\nIn this sample, there isn't any place that is completely surrounded by disks, yet not on the disks.\n\n### Sample 2\n\n#### Input\n```\n5\n4 -2 5\n-4 -2 5\n-8 8 8\n4 6 5\n-6 4 2\n```\n\n#### Output\n```\n1\n```\n\n#### Explanation\nIn this sample, $(-0.5, 3)$ is one of the places we can hide. It is surrounded by disks, yet not on the disks. Note that although all the inputs are integers, the hiding place does not necessarily have to be an integer point.\n\n### Sample 3\n\n#### Input\n```\n3\n420 580 230\n200 200 200\n600 200 210\n```\n\n#### Output\n```\n0\n```\n\n#### Explanation\nIn this sample, there isn't any place that is completely surrounded by disks, yet not on the disks.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2024_B", "prompt": "# Problem: Divine Gifting\n\nA celestial scroll, detailing Zeus's latest whim unfurls before Hermes: the next few millenia will be a period of divine gifting for mortals. Hermes, the messenger god, is tasked with delivering these gifts. Not just any gifts, mind you, but exquisitely crafted items from the Olympian workshops: a lyre that plays melodies of pure joy, a quill that writes words of profound wisdom, and so on. Each of the $N$ gifts is unique, and, to complicate matters, each has an optimal delivery date, a day when its magic would be most potent. But a divine law forbids delivering gifts before their optimal delivery day, lest mortals become complacent and entitled. Of course, all gifts must be delivered.\n\nAdding to the challenge, Hermes, despite being the fastest god on Olympus, is always extremely busy. Between managing the celestial postal service and refereeing chariot races, he knows that he can only dedicate at most $K$ days for the deliveries (each of those days, Hermes can deliver any number of gifts). Furthermore, late deliveries incur penalties: for each gift, the penalty is the square of the difference between its actual delivery day and its optimal delivery day. If a lyre is delivered a day or two late, a village might experience a few hours of slightly off-key music. A minor inconvenience, to be sure. However, if the lyre is delivered a month or a year late, the consequences are far more dire: a full year of discordant melodies, enough to drive even the most stoic musician to madness. The potential for chaos is immense.\n\nAnd this is where you come in, mortal friend. Hermes, with his myriad responsibilities, could use a helping hand. Can you help him plan his divine calendar by determining the best days for delivering the gifts, so as to minimize the sum of late delivery penalties?\n\n## Input\n\nOn the first line of the input, two space-separated integers:\n\n- $N$, the number of gifts;\n- $K$, the maximum number of days Hermes dedicates to gifting.\n\nOn the second line, $N$ space-separated integers $d_{i}$, representing the optimal delivery date of each gift.\n\n## Output\n\nA single line of space-separated integers, where the $i$-th element is the day when Hermes should deliver the $i$-th gift. If there are multiple optimal solutions, they will all be accepted.\n\n## Limits\n\n- $1 \\leq N \\leq 5,000$\n- $1 \\leq K \\leq 20$\n- $0 \\leq d_i \\leq 1,000,000$ for all $i \\leq N$\n\n## Sample Input\n\n```\n5 2\n50 0 51 10 50\n```\n\n## Sample Output\n\n```\n51 10 51 10 51\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2024_L", "prompt": "# Problem Statement\n\n## Problem Name\n\nDuring the summer break, fewer students are dwelling on campus, so this is the perfect time to add new books to the TU Delft library. These new books all have the same width, but they have varying heights. Because all existing bookcases are already full, the management board of the library has decided that they will add a new bookcase to display these new books.\n\nThe new bookcase has a number of shelves with varying heights. Each shelf in the bookcase can fit $x$ books. Since there may be some leftover space, the management board would also like to display some art pieces in this bookcase, at most one per shelf. An art piece will only fit on a shelf if there are at most $y$ books next to it, because the art pieces take up the same amount of space as $x-y$ books. As an example, Figure 1 shows a bookcase where three of the shelves have enough space for an art piece.\n\n![Illustration of Sample Input 1. Three shelves can have art pieces in the hatched areas, while still fitting all new books.](sample.pdf)\n\nThe management board wants you to find the largest number of shelves on which you can place an art piece, whilst also being able to fit all the new books on the shelves.\n\n## Input\n\nThe input consists of:\n- One line with four integers $n$, $m$, $x$, and $y$ ($1 \\leq n, m \\leq 10^5$, $1 \\leq y < x \\leq 1000$), the number of shelves, the number of books, the number of books that fit on a full shelf, and the number of books that fit on a shelf next to an art piece.\n- One line with $n$ integers $a$ ($1 \\leq a \\leq 10^9$), the heights of the shelves.\n- One line with $m$ integers $b$ ($1 \\leq b \\leq 10^9$), the heights of the books.\n\n## Output\n\nIf it is possible to fit all the $m$ books into the $n$ shelves, output the largest number of art pieces you can place. Otherwise, output \"impossible\".\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n4 8 4 2\n4 8 6 2\n1 2 3 5 7 7 8 8\n```\n\n### Sample Output 1\n```\n3\n```\n\n### Sample Input 2\n```\n4 11 3 2\n2 2 2 2\n1 1 1 1 1 1 1 1 1 1 1\n```\n\n### Sample Output 2\n```\n1\n```\n\n### Sample Input 3\n```\n2 10 3 2\n8 6\n4 2 1 3 6 2 1 3 4 5\n```\n\n### Sample Output 3\n```\nimpossible\n```\n\n### Sample Input 4\n```\n3 8 8 3\n7 9 4\n2 3 4 5 6 7 8 9\n```\n\n### Sample Output 4\n```\n3\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2023_J", "prompt": "### Problem: Olympic Goodies\n\n**Time limit:** 0.25 second\n\nFreshly arrived on the market, retailer YAOGS (Yet Another Olympic Goodies Seller) sells very expensive Olympics-themed items. To make themselves better known to the public, they half-heartedly decide to give away some of these items via a contest: the first person to answer correctly the question \"How many circles are there in the Olympic Games logo?\" can thus gain up to $P$ very expensive but equally valued items.\n\nTo spice things up (and spend less), YAOGS however opts for an additional challenge, as follows. The $P$ available items are positioned along some, but possibly not all of the alleys of YAOGS's headquarters; each alley can thus contain 0, 1, or more items. For reasons unknown, these alleys form a connected, undirected, acyclic graph (i.e., a tree) with $N$ nodes, numbered from 0 to $N - 1$.\n\nThe winner knows $N$ but has no idea about either the tree structure or the items' placement. Once goodies are placed, her task is to choose a start node $m$ and an end node $n$. She can then collect all the items on the (unique) path from $m$ to $n$ in the tree.\n\nYAOGS decides to cleverly place the goodies so that they minimize the maximum number of items that can possibly be collected. Assuming they properly carry out this task, what is the maximum number of items the winner can collect?\n\n**Input:**\nEach line contains two space-separated integers. The first line contains the numbers $N$ and $P$. Then follow $N - 1$ lines; the $k$-th such line contains two integers $a_k$ and $b_k$, meaning that there is an edge between the nodes $a_k$ and $b_k$ of the tree.\n\n**Output:**\nThe output should contain a single line, consisting of a single integer: the maximum number of items that can be collected by the winner.\n\n**Limits:**\n- $1 \\leq N \\leq 100000$\n- $1 \\leq P \\leq 100000$\n- $0 \\leq a_k \\leq N - 1$ and $0 \\leq b_k \\leq N - 1$ for all $k \\leq N - 1$\n- The set of edges in the input file describes a valid tree structure.\n\n**Sample Input:**\n```\n5 5\n0 1\n0 2\n2 3\n2 4\n```\n\n**Sample Output:**\n```\n4\n```\n\n**Sample Explanation:**\nFor the tree in the sample input, an optimal item placement by YAOGS guarantees that the winner cannot collect more than four items. The figures below show two possible item placements to achieve this optimality. In the first one, the four items may be collected by choosing, for instance, nodes 1 and 3. In the second one, the four items may be collected by choosing, for instance, nodes 0 and 4.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2024_H", "prompt": "# Problem: H: The King of SWERC\n\nThat's it! After years of research, you finally managed to find who was the king of the infamous South Western Egyptian River City (SWERC)!\n\nWell, not exactly. You have found the actual votes. But considering that the person who got the most votes got elected, and considering that there wasn't a tie for first place, can your code deduce who was the actual king of SWERC?\n\n## Input\n\nThe first line of the input is an integer, $N$, the number of votes. The next $N$ lines describe the votes, and each contains a name $V_i$ in capital English letters, without spaces.\n\nIt is guaranteed one name appears strictly more than the others.\n\n## Output\n\nThe output should contain a single string, the name of the king of SWERC.\n\n## Limits\n\n- $1 \\leqslant N \\leqslant 500$.\n- $1 \\leqslant |V_i| \\leqslant 20$, for $i = 1, \\ldots, N$.\n\n## Sample Input 1\n\n```\n1\nRAMSES\n```\n\n## Sample Output 1\n\n```\nRAMSES\n```\n\n## Sample Input 2\n\n```\n4\nJON\nJOFFREY\nTYWIN\nJON\n```\n\n## Sample Output 2\n\n```\nJON\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2023_D", "prompt": "### Problem Statement\n\n**Problem:** Flag Performance\n\n**Time Limit:** 2 seconds\n\nYou are in charge of a team of sorted gymnastics. This new discipline involves teams of $N$ members. Each team member dresses with a different colour (a number from 1 to $N$) and holds a coloured flag. Flags have unique colours, also numbered from 1 to $N$. A performance consists of exactly $K$ steps. At each step, two members exchange their flags. You are free to choose the initial configuration of the flags. The only constraint is that, at the end of the performance, each participant must hold the flag corresponding to the colour of his outfit.\n\nBeing the team captain, you would like the performance to be as unpredictable as possible. You consider $T$ possible initial configurations of flags among the team members, and wonder: in how many ways can the team perform the task for each of these initial configurations?\n\nFor each of the given $T$ initial configurations, compute the number of possible ways to do the performance. As the answers may be very large, return them modulo the prime number $1{,}000{,}000{,}007$.\n\n### Input\n\nEach line consists of space-separated integers. The first input line contains the numbers $N$, $K$, and $T$. Then follow $T$ lines. The $k$-th such line consists of $N$ distinct space-separated integers $C_{k,1}, C_{k,2}, \\ldots, C_{k,N}$, representing the $k$-th initial configuration of flags among team members. Here, $C_{k,j}$ is the colour number of the flag initially in the hands of the team member whose outfit colour is $j$.\n\n### Output\n\nThe output should contain $T$ lines. The $k$-th such line should consist of a single number: the number of possible sequences of exchanges that start from the $k$-th configuration and satisfy the constraints listed above, modulo $1{,}000{,}000{,}007$.\n\n### Limits\n\n- $2 \\leq N \\leq 30$\n- $1 \\leq K \\leq 50$\n- $1 \\leq T \\leq 10{,}000$\n\n### Sample Input 1\n\n```\n4 2 1\n4 1 2 3\n```\n\n### Sample Output 1\n\n```\n0\n```\n\n### Sample Explanation 1\n\nIt is impossible to sort the flags with two exchanges.\n\n### Sample Input 2\n\n```\n4 3 1\n4 1 2 3\n```\n\n### Sample Output 2\n\n```\n16\n```\n\n### Sample Input 3\n\n```\n6 15 10\n5 6 1 2 4 3\n2 4 1 6 5 3\n4 1 3 6 5 2\n1 3 2 4 5 6\n4 5 6 1 2 3\n1 2 5 3 6 4\n6 4 2 3 1 5\n3 6 4 1 2 5\n4 5 1 2 6 3\n6 1 4 3 2 5\n```\n\n### Sample Output 3\n\n```\n310571736\n0\n745108126\n996135367\n597596468\n745108126\n0\n0\n310571736\n0\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2023_D", "prompt": "# Problem: Date Picker\n\nThe NWERC is coming up and your agenda is filling up with meetings. One of your teammates wants to plan a meeting, and asks for your input. However, instead of asking you for your exact agenda, you have to fill out two separate polls: one for indicating which days you are available, and one for the hours!\n\nAs a computer scientist, you plan your meetings only on whole hours and each meeting takes an integer number of hours. Therefore, your agenda can be modelled as a matrix of $\\days$ rows (days), and $\\hours$ columns (hours). Each cell in this matrix is either `\\texttt{.}' or `\\texttt{x}', meaning that hour of that day you are either free or have a meeting, respectively.\n\nYou have to pick at least $d$ days in the first poll and $h$ hours in the second poll, and we assume the meeting will take place on any of your picked hour/day combinations with equal probability. What is the probability that you can attend the meeting if you fill in the polls optimally?\n\n## Input\nThe input consists of:\n- $\\days$ lines with $\\hours$ characters, each character being either `\\texttt{.}' or `\\texttt{x}', with `\\texttt{.}' indicating the time slots you are available.\n- One line with two integers $d$ and $h$ ($1 \\leq d \\leq \\days$, $1 \\leq h \\leq \\hours$), the minimum number of days and hours you have to fill in.\n\n## Output\nOutput the probability that you are available at the chosen meeting time.\n\nYour answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\nxxxxxx..xx..xxxxxxxxxxxx\nxxxxxxxxxxxxx....xxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxx..xx..xxxxxxxxxxxx\nxxxxxxxxxxxxx...x..xxxxx\nxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxx\n2 5\n```\n\n## Sample Output 1\n```\n0.8\n```\n\n## Sample Input 2\n```\nxxxxxxxxx.....x...xxxxxx\nxxxxxxxx..x...x...xxxxxx\nxxxxxxxx......x...x.xxxx\nxxxxxxxx...xxxxxxxxxxxxx\nxxxxxxxx...xxxxxxxxxxxxx\nxxxxxxxx...xxxxxxxx.xxxx\n......xxxxxxxxxxxxxxxxxx\n3 8\n```\n\n## Sample Output 2\n```\n0.958333333333333\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2023_C", "prompt": "### Metro Quiz\n\n**Time Limit:** 5 seconds\n\nTwo Olympics spectators are waiting in a queue. Each holds a copy of the metro map of Paris, and they devise a little game to kill time. First, player A thinks of a metro line (chosen uniformly at random among all metro lines) that player B needs to guess. To guess, player B repeatedly asks whether the line stops at a metro station of her choice, and player A answers truthfully. After enough questions, player B will typically know with certainty which metro line player A had in mind. Of course, player B wants to minimize the number of questions she needs to ask.\n\nYou are given the map of the $M$ metro lines (numbered from 1 to $M$), featuring a total of $N$ metro stations (numbered from 0 to $N - 1$) and indicating, for each line, those stations at which the line stops. Please compute the expected number of questions that player B needs to ask to find the answer, using the optimal strategy.\n\nIn other words, given a strategy $S$, let $Q_{s,j}$ be the number of questions asked by the strategy if the metro line in the solution is line $j$. Then, let\n$$ E_s = E[Q_s] = \\frac{1}{M} \\sum_{j=1}^{M} Q_{s,j} $$\nbe the expected value of $Q_{s,j}$ assuming that $j$ is uniformly chosen from the set of all metro lines. Your task is to compute $\\min_s E_s$.\n\nIf it is not always possible for player B to know which line player A had in mind with certainty, output \"not possible\".\n\n### Input\nThe first line contains the number $N$. The second line contains the number $M$. Then follow $M$ lines:\n- The $k$-th such line contains first a positive integer $n \\leq N$, then a space, and then $n$ space-separated integers $s_1, s_2, \\ldots, s_n$; these are the metro stations at which line $k$ stops. A line stops at a given station at most once.\n\n### Output\nThe output should contain a single line, consisting of a single number: the minimum expected number of questions that player B must ask in order to find the correct metro line, or \"not possible\" (in lowercase characters). Answers within $10^{-4}$ of the correct answer will be accepted.\n\n### Limits\n- $1 \\leq N \\leq 18$\n- $1 \\leq M \\leq 50$\n\n### Sample Input 1\n```\n5\n4\n3 0 3 4\n3 0 2 3\n3 2 3 4\n2 1 2\n```\n\n### Sample Output 1\n```\n2\n```\n\n### Sample Input 2\n```\n3\n3\n1 0\n1 1\n1 2\n```\n\n### Sample Output 2\n```\n1.66666666666667\n```\n\n### Sample Explanation 2\nAsk the first question about station 0: this is optimal by symmetry of the problem. This lets us distinguish between line 1, which stops at station 0, and lines 2 and 3, which do not. If needed, ask a second question to distinguish between lines 2 and 3.\n\nPlayer B asks one question if the answer is line 1, and two questions otherwise. Thus, the expected number of questions she will ask is $\\frac{1 + 2 \\times 2}{3}$.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2023_L", "prompt": "# Problem Statement\n\n## Lateral Damage\n\nYou are playing *Battleships* in a large ocean with large ships. More precisely, there is a large square grid of size at most $100 \\times 100$ and inside it are up to $10$ of the largest type of ship in Battleships -- the aircraft carrier -- which has a length of five tiles, placed either horizontally or vertically. The ships do not overlap, but they are allowed to be adjacent to each other. See Figure 1 for an example.\n\nUnfortunately, your opponent appears to bend the rules to their liking. It looks like they do not always determine the placement of their ships before you start shooting. You are not impressed by their attempt at cheating, and decide to try and win the game anyway.\n\nYour goal is to locate and sink all your opponent's aircraft carriers in at most $2500$ shots, that is, you must hit each of the five tiles of all their ships.\n\n![Illustration of Sample Interaction 1 after the first four shots were fired.](sample)\n\n## Interaction\n\nThis is an interactive problem. Your submission will be run against an *interactor*, which reads from the standard output of your submission and writes to the standard input of your submission. This interaction needs to follow a specific protocol:\n\n1. The interactor first sends one line with two integers $n$ and $k$ ($5 \\le n \\le 100$, $1 \\le k \\le 10$), the size of the grid and the number of ships. It is guaranteed that it is possible to place $k$ aircraft carriers in the grid without overlap.\n2. Then, your program needs to start firing shots. Each shot is fired by printing one line of the form `x y` ($1 \\le x, y \\le n$), indicating you shoot at position $(x, y)$.\n3. The interactor will respond with `hit` if the shot was a hit, `sunk` if the shot caused an aircraft carrier to sink, and `miss` otherwise. If you have shot the same location before, the response will be `miss`.\n4. Once you sink the last aircraft carrier, the interaction will stop and your program must exit.\n5. The interactor is adaptive: the positions of the ships may be determined during the interaction, and may depend on where you decide to shoot.\n6. Make sure you flush the buffer after each write.\n7. A testing tool is provided to help you develop your solution.\n8. Firing more than $2500$ shots will result in a wrong answer.\n\n## Sample Interaction\n\n### Input\n```\n7 2\n2 0 0\nh 1 3\nv 6 2\n```\n\n### Output\n```\n1 3\n6 2\n```\n\n### Explanation\n- The interactor sends the grid size $n = 7$ and the number of ships $k = 2$.\n- The first ship is placed horizontally at position $(1, 3)$.\n- The second ship is placed vertically at position $(6, 2)$.\n- Your program fires shots at positions $(1, 3)$ and $(6, 2)$, and the interactor responds accordingly.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2024_A", "prompt": "# Problem: Titanomachy\n\nIn ancient Greek mythology, it is believed that the Olympian gods acquired their power from a long-lasting war with the Titans.\n\nAfter some recent excavations, an archaeological team found manuscripts explaining how people thought this war happened.\n\nZeus, the leader of the Olympian gods, and Kronos, the leader of the Titans, each picked their best $N$ soldiers in order to fight.\n\nThen, the soldiers arranged themselves in two rows, one row containing only the Olympian gods, and the other containing the Titans, such that each soldier faced exactly one opponent.\n\nAt the beginning of the battle, each such pair $i$ ($1 \\leq i \\leq N$) of soldiers had a score, $A_i$, which is an integer representing which side of the war had the advantage. A positive number represented an advantage for Zeus and the Olympian gods, a negative number an advantage for the Titans.\n\nDuring the war, $Q$ events occurred. These events could be of two kinds: either the relative strength of all pairs of soldiers changed due to the actions of Zeus and Kronos (for example, breaking down mountains with lightning), or Zeus conducted a strategic assessment of his army's advantage.\n\nIn the first case, the same integer $X$ got added to every single $A_i$. If $X$ was greater than $0$, it meant that Zeus increased the strength of his army, while a negative value meant that the Titans increased their strength, and a value of $0$ meant that nothing changed.\n\nIn the second case, Zeus focused on an interval $[L,R]$ of soldiers ($1 \\leq L \\leq R \\leq N$): he considered every possible subinterval, that is, all $l, r$ such that $L \\leq l \\leq r \\leq R$, and computed the sum $A_l + A_{l+1} + \\cdots + A_r$ for each of them. He computed the maximum value $M$ of such sums over all possible subintervals, and declared that $V = \\max(M, 0)$ was the strategic assessment of his army's advantage.\n\nObviously, Zeus's wisdom allowed him to compute such values instantaneously, but unfortunately, he did not record them anywhere.\n\nYour task as a philologist is to provide the values of all the strategic assessments made by Zeus during the war.\n\n## Input\n\nThe first line of the input contains two space-separated integers $N$ and $Q$. The second line contains $N$ space-separated integers $A_i$, representing the state at the beginning of the war.\nThe following $Q$ lines describe the events of the war, in chronological order. Each of them is either:\n- The word `STRENGTH`, followed by a space and an integer $X$, meaning that the strength of an army changed.\n- The word `ASSESS` followed by space-separated integers $L$ and $R$, meaning that Zeus made a strategic assessment of his army's advantage by focusing on the interval $[L, R]$ ($1 \\leq L \\leq R \\leq N$).\n\n## Output\n\nFor every time Zeus made a strategic assessment of his army's advantage, and in the order they appear in the input, you must output one line with the value $V$ of each assessment.\n\n## Limits\n\n- $1 \\leq N \\leq 3 \\times 10^5$\n- $1 \\leq Q \\leq 3 \\times 10^5$\n- $-10^9 \\leq A_i \\leq 10^9$ for $i=1,\\dots,N$.\n- All $X$ integers are between $-10^9$ and $10^9$, inclusive.\n- At all times during the war, $-2 \\times 10^9 \\leq A_i \\leq 2 \\times 10^9$ for all $i=1,\\dots,N$ holds true.\n\n## Sample Input\n\n```\n4 6\n1 -2 3 4\nASSESS 1 4\nASSESS 1 2\nASSESS 2 2\nSTRENGTH 2\nASSESS 1 4\nASSESS 1 2\n```\n\n## Sample Output\n\n```\n7\n1\n0\n14\n3\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2022_J", "prompt": "# Problem J: Italian Data Centers\n## SWERC 2022-2023\n\n## Problem Statement\n\nAn Italian data center consists of a set of servers, each colored green, white, or red, and a set of wires connecting them. Each wire connects two distinct servers, and two servers are connected by at most one wire. Additionally, the data center is connected, meaning there is a way to transmit information between any two servers through a sequence of wires.\n\nTo judge all of the contestant submissions, SWERC has an Italian data center. Since the number of contestants doubles every year, the data center needs to grow to adapt to the extra load. To address this, SWERC builds a new data center based on the previous year's one by following these steps:\n\n- For each server $s$ in the old data center, the new data center contains two servers $s1$ and $s2$ of the same color as $s$. A wire is placed connecting the two servers $s1$ and $s2$.\n- For each wire connecting servers $s$ and $t$ in the old data center: if $s$ and $t$ have the same color, then a wire is placed in the new data center connecting $s1$ and $t1$ and another wire connecting $s2$ and $t2$; otherwise, a wire is placed in the new data center connecting $s1$ and $t2$ and another one connecting $s2$ and $t1$.\n\nOne can show that if the old data center is connected, then the new data center is also connected.\n\nYou are given the Italian data center that SWERC currently has, which contains $n$ servers (indexed by 1, 2, ..., $n$) and $m$ wires connecting them. The organization wants to know how good their data center will be after $k$ years, so you should determine the diameter of the data center SWERC will have in $k$ years. The diameter of the data center is the largest distance between any two servers, i.e., the shortest number of wires that have to be used to transmit something between the two servers.\n\n## Input\nThe first line contains three integers $n$, $m$, and $k$ ($2 \\leq n \\leq 100$, $n-1 \\leq m \\leq n(n-1)/2$, $0 \\leq k \\leq 100$) \u2014 the number of servers, the number of wires, and the number of years to consider.\nThe second line contains $n$ integers $c1, c2, \\ldots, cn$ ($1 \\leq ci \\leq 3$) \u2014 $ci$ is the color of server $i$ (where 1 stands for green, 2 for white, and 3 for red).\nEach of the next $m$ lines contains two integers $s_i$ and $t_i$ ($1 \\leq s_i, t_i \\leq n$) \u2014 the two servers the $i$-th wire connects.\n\nIt is guaranteed that the data center is connected, the endpoints of each wire are distinct, and that there are no repeated wires.\n\n## Output\nPrint the diameter of SWERC's data center after $k$ years.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n3 3 0\n1 2 3\n1 2\n2 3\n3 1\n```\n\n### Sample Output 1\n```\n1\n```\n\n### Explanation of Sample 1\nThe Italian data center is the following:\n- The distance between any pair of servers is 1, so the diameter is 1.\n\n### Sample Input 2\n```\n3 3 1\n1 2 3\n1 2\n2 3\n3 1\n```\n\n### Sample Output 2\n```\n2\n```\n\n### Explanation of Sample 2\nThe initial Italian data center is the one from the first sample.\nAfter one year, we obtain the following (where the numbers indicate which copy the server refers to):\n- Consider the highlighted servers. The distance between them is 2 and there is no pair of servers with a greater distance, so the diameter is 2.\n\n### Sample Input 3\n```\n3 3 2\n1 2 1\n1 2\n2 3\n3 1\n```\n\n### Sample Output 3\n```\n3\n```\n\n### Explanation of Sample 3\nThe data center after one year is the following:\n- After one more year:\n- Consider the highlighted servers. The distance between them is 3 and there is no pair of servers with a greater distance, so the diameter is 3.\n\n### Sample Input 4\n```\n8 14 100\n3 3 2 2 1 2 2 1\n2 7\n1 5\n7 8\n4 6\n2 8\n1 8\n2 6\n6 7\n1 6\n1 4\n3 5\n1 3\n4 5\n5 7\n```\n\n### Sample Output 4\n```\n53\n```\n\n### Explanation of Sample 4\nThe data center after 100 years has a diameter of 53.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2023_I", "prompt": "# Throwing Dice\n\n**Time Limit:** 1 second\n\nAlice and Bob are discussing penalty shoot-outs and their randomness: \"We might as well be throwing dice to determine the winner!\", Alice said. And so they started simulating penalty shoot-outs by each throwing dice, summing the points indicated on their dice, and comparing these sums. The player with the largest sum wins; in case both sums are equal, there is a tie.\n\nBut even in such situations, some player might have an edge over their opponent, depending on which dice they throw. Thus, just by looking at the dice they are about to throw, Alice and Bob want to determine who has the better edge.\n\nAlice has $M$ fair dice, with $A_1, A_2, \\ldots, A_M$ sides. For all integers $k$ and $l$ such that $1 \\leq k \\leq M$ and $1 \\leq l \\leq A_k$, the $k$-th die of Alice has a probability $1 / A_k$ of showing its face numbered $l$. Then, Alice's score is the sum of the numbers displayed by her $M$ dice. Similarly, Bob has $N$ fair dice, with $B_1, B_2, \\ldots, B_N$ sides.\n\nGiven these dice, Alice has a probability $P_A$ of having a strictly larger score than Bob, and Bob has a probability $P_B$ of having a strictly larger score than Alice. Which probability is the largest one?\n\n## Input\nThe input consists of three lines, each one containing space-separated integers:\n- The first line contains the numbers $M$ and $N$.\n- The second line contains the numbers $A_1, A_2, \\ldots, A_M$.\n- The third line contains the numbers $B_1, B_2, \\ldots, B_N$.\n\n## Output\nThe output should contain a single line, consisting of a single uppercase word:\n- `ALICE` if $P_A > P_B$,\n- `TIED` if $P_A = P_B$,\n- `BOB` if $P_A < P_B$.\n\n## Limits\n- $1 \\leq M \\leq 100000$\n- $1 \\leq N \\leq 100000$\n- $4 \\leq A_k \\leq 1000000000$ for all $k \\leq M$\n- $4 \\leq B_k \\leq 1000000000$ for all $k \\leq N$\n\n## Sample Input 1\n```\n8 1\n4 4 4 4 4 4 4 4\n6\n```\n\n## Sample Output 1\n```\nALICE\n```\n\n## Sample Explanation 1\nSince Alice has 8 dice, her score is always 8 or more; Bob's score is always 6 or less. Hence, Alice has a probability $P_A = 100\\%$ of beating Bob, and he has a probability $P_B = 0\\%$ of beating her. Consequently, $P_A > P_B$.\n\n## Sample Input 2\n```\n2 2\n6 4\n4 6\n```\n\n## Sample Output 2\n```\nTIED\n```\n\n## Sample Explanation 2\nAlice has a probability $P_A = 125/288$ of beating Bob; he also has a probability $P_B = 125/288$ of beating her.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "nwerc2022_E", "prompt": "# ETA\n\nYou want to design a level for a computer game. The level can be described as a connected undirected graph with vertices numbered from $1$ to $n$. In the game, the player's character is dropped at one of the $n$ vertices uniformly at random and their goal is to reach the exit located at vertex $1$ as quickly as possible. Traversing an edge takes exactly $1$ second.\n\nThe difficulty of the level is determined by the average optimal time to reach the exit. Given a target value for this average optimal time, construct a level so that this target value is reached. See the example below for an illustration.\n\n## Input\n\nThe input consists of:\n- One line with two coprime integers $a$ and $b$ ($1 \\le a, b \\le 1000$) separated by a `\\texttt{/}', giving the desired average optimal time to reach the exit as the fraction $\\frac{a}{b}$.\n\n## Output\n\nIf no connected graph with the average optimal time $\\frac{a}{b}$ to reach vertex $1$ exists, output `impossible`.\nOtherwise, output one such graph in the following format:\n- Two integers $n$ and $m$ ($1 \\le n, m \\le 10^6$), the number of vertices and the number of edges.\n- $m$ pairs of integers $u$ and $v$ ($1 \\le u, v \\le n$), indicating an edge between vertices $u$ and $v$.\n\nThe graph may include self loops and parallel edges. You are given that if there exists a valid graph, then there also exists one with $1 \\le n, m \\le 10^6$.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n1/2\n```\n\n### Sample Output 1\n```\n2 1\n1 2\n```\n\n### Sample Input 2\n```\n1/3\n```\n\n### Sample Output 2\n```\nimpossible\n```\n\n### Sample Input 3\n```\n7/4\n```\n\n### Sample Output 3\n```\n8 12\n1 2\n1 3\n2 3\n2 4\n3 5\n3 6\n4 5\n5 6\n4 7\n5 7\n4 8\n6 8\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2024_J", "prompt": "# Problem Statement\n\n## Given Problem\n\nBob was hired for a new job after last year's success of building an infinite wall. His first task is to set up multiple cranes on a new construction site. Each crane consists of a central tower with a horizontal beam (the *jib*) attached to the top that can freely rotate around the central tower. The towers have already been set up for Bob, at some fixed coordinates and with some fixed height. Only the jibs still need to be placed. However, Bob has to be careful with this:\n\n- The length of a jib may not exceed the height of its tower, as else the crane would simply topple over.\n- The length of a jib must be a positive integer number of metres.\n- No two cranes should be able to collide. Luckily, all the towers are of different height. Therefore, the only way two cranes could collide is if the jib of one tower crashed into the tower of another crane. Note that a jib touching the tower of another crane does not result in a crash.\n\nWith this in mind, Bob wants to maximize the area that can be reached with at least one of the cranes, that is, the area of points on the ground such that at least one of the jibs can be positioned above them through rotations. Which length should each of the jibs have so that Bob can maximize the covered area?\n\n## Input\n\nThe input consists of:\n- One line with one integer $n$ $(1 \\leq n \\leq 500)$, the number of cranes.\n- $n$ lines, each with three integers $x$, $y$, and $h$ $(0 \\leq x, y \\leq 10\\,000, 1 \\leq h \\leq 10\\,000)$, describing the position of the crane and its height in metres.\n\nIt is guaranteed that no two cranes are at the same position and that all heights are distinct.\n\n## Output\n\nFor each crane, output the positive integer length of its jib in metres, such that the covered area is maximized.\n\nIf there are multiple optimal solutions, you may output any one of them.\n\n## Sample Input and Output\n\n### Sample Input 1\n```\n3\n1 1 4\n4 1 5\n7 4 3\n```\n\n### Sample Output 1\n```\n5\n3\n```\n\n### Sample Input 2\n```\n3\n0 0 10\n4 6 8\n6 6 6\n```\n\n### Sample Output 2\n```\n10\n7\n1\n```\n\n### Sample Input 3\n```\n5\n2 6 2\n4 10 4\n5 6 6\n8 8 7\n10 2 8\n```\n\n### Sample Output 3\n```\n2\n4\n2\n6\n8\n```\n\n## Illustration of Sample Input 3\nThe number at the centre of each circle indicates the height of the crane at that position. The number at each arrow indicates the length of the jib for that crane.\n\n\\[\n\\begin{tikzpicture}[x=0.5cm,y=0.5cm]\n \\newcommand{\\addCircle}[5][]{\n \\begin{pgfonlayer}{background}\n \\fill[black,#1] (#2) circle (#4*0.5cm+0.2pt);\n \\end{pgfonlayer}\n \\fill[red!10,#1] (#2) circle (#4*0.5cm-0.2pt);\n \\begin{pgfonlayer}{foreground}\n \\draw[dashed,#1] (#2) circle (#4);\n \\fill[black] (#2) circle (2pt);\n \\node[anchor=north] at (#2) {#3};\n \\draw[line width=1.5pt,-stealth] (#2) -- ($(#2)+(#5:#4)$) node [midway, above, sloped] {#4};\n \\end{pgfonlayer}\n \\stepcounter{nextCircle}\n }\n \n \\addCircle{2,6}{2}{2}{200}\n \\addCircle{4,10}{4}{4}{160}\n \\addCircle{5,6}{6}{2}{330}\n \\addCircle{8,8}{7}{6}{-20}\n \\addCircle{10,2}{8}{8}{-20}\n\\end{tikzpicture}\n\\]\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2024_G", "prompt": "# Problem: G: Guess How the Ballet Will End\n\nIn ancient Greek theater, the chorus would often dance. The dances were a pleasure to watch; all the dancers on stage executed the same movements at the same time, going across the theater, left to right or right to left. Of course, no dancer could ever go past the borders of the scene. So if the instructions would have made them fall off the scene, they would simply have carried out the move until they reached the border and then stayed there until the next move. For instance, if the move said 5 steps to the right but the dancer only had space for two steps, he/she would have taken those two steps and would then have waited on the border for the next move.\n\nYou are excavating a theater and have found extraordinarily well-preserved papyri detailing the sequence of moves the dancers would make during many theater plays, a real treasure trove. The initial positions of the dancers are not known to you, since you have only found the papyri with the moves, and the rest of the instructions and the rest of the plays have been lost.\n\nThe instructions are a sequence of numbers, telling all the dancers to dance 3 steps to the left, 5 steps to the right, etc., all carrying out the same move at the same time. Adding a coordinate system to the scene, each dancer $i$ starts at the position $(X_i, i)$ and a move only impacts their $X$ coordinate (each dancer dances on his/her own line), so they cannot bump into each other. They also all move at the same speed; moving by $n$ steps means the same change of $X$ coordinate for all dancers, unless they hit the borders as explained above.\n\nYou have figured out that in some cases, because some dancers may need to cut some movements short due to the borders, it may happen that they will all end up in a perfect line (all at the same $X$ position) at the end of the dance. There are so many papyri that you have decided to write a program to find out if this is the case. Maybe you will learn interesting things about Greek dancing, depending on the number of plays where all the dancers end up all aligned.\n\n## Input\n\nOn the first two lines of the input:\n\n- $R$, an integer, the length of the scene. The valid $X$ positions of the dancers range from 0 (left of the scene) to $R$ (right of the scene). Going beyond that would make the dancers fall off the scene.\n- $N$, the number of movements the dancers shall carry out.\n\nOn the third line, $N$ integers $d_i$, separated by spaces, the signed lengths of the moves the dancers shall carry out (a positive number means the dancer is moving to the right, a negative number that he/she is moving to the left).\n\n## Output\n\nIf you can be sure that all the dancers will end up being aligned at the same $X$ position, a single integer, corresponding to the position (distance from the left of the scene) where all the dancers will end up at the end of the moves.\n\nOtherwise, output the string `uncertain`.\n\n## Limits\n\n- $1 \\leq R \\leq 10,000,000,000$\n- $1 \\leq N \\leq 1000$\n- $-10,000,000,000 \\leq d_i \\leq 10,000,000,000$\n\n## Sample Input/Output\n\n### Sample Input 1\n```\n100\n2\n110 -20\n```\n\n### Sample Output 1\n```\n80\n```\n\n### Sample Input 2\n```\n100\n1\n50\n```\n\n### Sample Output 2\n```\nuncertain\n```\n\n### Sample Input 3\n```\n100\n8\n50 30 -40 10 -30 -50 30 -10\n```\n\n### Sample Output 3\n```\n20\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2022_C", "prompt": "# Problem C: Another Wine Tasting Event\n**SWERC 2022-2023**\n\n## Problem Statement\n\nAfter the first successful edition, Gabriella has been asked to organize a second wine tasting event. There will be $2n - 1$ bottles of wine arranged in a row, each of which is either red wine or white wine.\n\nThis time, Gabriella has already chosen the type and order of all the bottles. The types of the wines are represented by a string $s$ of length $2n - 1$. For each $1 \\leq i \\leq 2n - 1$, it holds that $s_i = R$ if the $i$-th bottle is red wine, and $s_i = W$ if the $i$-th bottle is white wine.\n\nExactly $n$ critics have been invited to attend. The critics are numbered from $1$ to $n$. Just like last year, each critic $j$ wants to taste an interval of wines, that is, the bottles at positions $a_j, a_j + 1, \\ldots, b_j$ for some $1 \\leq a_j \\leq b_j \\leq 2n - 1$. Moreover, they have the following additional requirements:\n- Each of them wants to taste at least $n$ wines, that is, it must hold that $b_j - a_j + 1 \\geq n$.\n- No two critics must taste exactly the same wines, that is, if $j \\neq k$ it must hold that $a_j \\neq a_k$ or $b_j \\neq b_k$.\n\nGabriella knows that, since the event is held in a coastal region of Italy, critics are especially interested in the white wines, and don't care much about the red ones. (Indeed, white wine is perfect to accompany seafood.) Thus, to ensure fairness, she would like all critics to taste the same number of white wines.\n\nHelp Gabriella find an integer $\\ell$ (with $0 \\leq \\ell \\leq 2n - 1$) such that there exists a valid assignment of intervals to critics where each critic tastes exactly $\\ell$ white wines. It can be proved that at least one such $\\ell$ always exists.\n\n## Input\nThe first line contains the integer $n$ ($1 \\leq n \\leq 10^6$) \u2014 where $2n - 1$ is the number of bottles, and $n$ is the number of critics.\nThe second line contains a string $s$ of length $2n - 1$ that represents the arrangement of the wines. The $i$-th character of $s$ ($1 \\leq i \\leq 2n - 1$) is $R$ for a red wine and $W$ for a white wine.\n\n## Output\nPrint an integer $\\ell$ \u2014 the number of white wines that each critic will taste.\nIt can be proved that at least one solution exists. If multiple solutions exist, any of them will be accepted.\n\n## Samples\n\n### Sample Input 1\n```\n5\nRWWRRRWWW\n```\n\n### Sample Output 1\n```\n2\n```\n\n### Explanation of Sample 1\nThere are 5 critics and $2 \\cdot 5 - 1 = 9$ bottles of wine. A possible set of intervals that makes each critic taste 2 white wines is the following: $[2, 6]$, $[1, 6]$, $[4, 8]$, $[1, 5]$, $[3, 7]$. Note that all intervals contain at least 5 bottles.\n\n### Sample Input 2\n```\n1\nR\n```\n\n### Sample Output 2\n```\n0\n```\n\n### Explanation of Sample 2\nThere is 1 critic and $2 \\cdot 1 - 1 = 1$ bottle of wine. The only possible interval is $[1, 1]$, which gives $\\ell = 0$.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2022_I", "prompt": "# Problem I: Library Game\n## SWERC 2022-2023\n\n## Problem Statement\n\nAlessia and Bernardo are discovering the world of competitive programming through the books of their university library.\n\nThe library consists of $m$ sections numbered from 1 to $m$. Each section contains only books dedicated to a particular subject, and different sections correspond to different subjects. To prevent students from wandering in the library, the university has established a system of passes. Each pass has a length $y$ associated with it and allows access to an interval of $y$ consecutive sections in the library. During a visit, the student must choose exactly one book from one of these sections and leave the library. Each pass can be used only once.\n\nAt the moment, Alessia and Bernardo have $n$ passes of lengths $a_1, a_2, \\ldots, a_n$. They have different opinions on the best way to improve: Alessia thinks that it is important to study many different topics, while Bernardo believes that it is important to study deeply at least one topic. So, Alessia wants to use the $n$ passes to get $n$ books on distinct topics, while Bernardo would like to get at least two books on the same topic.\n\nThey have reached the following agreement: for each of the following $n$ days, Alessia will choose a pass of length $y$ among those which are still available and an interval of $y$ sections in the library, and Bernardo will go into the library and will take exactly one book from one of those sections.\n\nCan Bernardo manage to get at least two books on the same subject, or will Alessia be able to avoid it?\n\nYou should decide whether you want to be Alessia or Bernardo, and you have to fulfill the goal of your chosen character. The judge will impersonate the other character. Note that, even if at some moment Bernardo has already taken two books on the same subject, the interaction should go on until the end of the $n$ days.\n\n## Input\n\nThe first line contains two integers $n$ and $m$ ($1 \\leq n \\leq 100$, $n \\leq m \\leq 5000$) \u2014 the number of passes and the number of sections.\nThe second line contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq m$) \u2014 the lengths of the passes available.\n\n## Interaction\n\nFirst, you should print a line containing either the string `Alessia` or the string `Bernardo` \u2014 the character that you want to impersonate.\n\nThen, for each of the $n$ turns:\n- If you are taking the role of Alessia, print a single line consisting of two integers $y$ and $a$ ($1 \\leq a \\leq m - y + 1$) \u2014 you are choosing a pass of length $y$ and the interval of sections $[a, a + y - 1]$. Note that at least one pass of length $y$ must still be available. After this, read a single integer $b$ ($a \\leq b \\leq a + y - 1$) \u2014 the subject of the book selected by Bernardo.\n- If you are taking the role of Bernardo, read two integers $y$ and $a$ ($1 \\leq a \\leq m - y + 1$) \u2014 the length of the pass chosen by Alessia and the index of the first section of the interval. It is guaranteed that there is at least one pass of length $y$ available. Then, print a single integer $b$ ($a \\leq b \\leq a + y - 1$) \u2014 the subject from which you choose to take a book.\n\nIf one of your interactions is malformed, the interactor terminates immediately and your program receives the verdict `WRONG-ANSWER`. Otherwise, you will receive the verdict according to the game's criteria described above.\n\nAfter printing a line, do not forget to end the line and flush the output. Otherwise, you will get the verdict `TIME-LIMIT`. To flush the output, use:\n- `fflush(stdout)` in C\n- `fflush(stdout)`, `cout << flush` or `cout.flush()` in C++\n- `System.out.flush()` in Java and Kotlin\n- `sys.stdout.flush()` in Python\n\n## Samples\n\n### Sample Input 1\n```\n5 14\n3 7 2 3 10\n```\n\n### Sample Output 1\n```\nAlessia\n3 11\n13\n10 2\n9\n7 1\n4\n2 10\n10\n3 6\n7\n```\n\n### Explanation of Sample 1\nIt can be shown that Alessia can accomplish her goal. An example of interaction (after reading the input) follows:\n- Contestant (as Alessia) chooses $y = 3$ and $a = 11$.\n- Judge (as Bernardo) selects $b = 13$.\n- Contestant (as Alessia) chooses $y = 10$ and $a = 2$.\n- Judge (as Bernardo) selects $b = 9$.\n- Contestant (as Alessia) chooses $y = 7$ and $a = 1$.\n- Judge (as Bernardo) selects $b = 4$.\n- Contestant (as Alessia) chooses $y = 2$ and $a = 10$.\n- Judge (as Bernardo) selects $b = 10$.\n- Contestant (as Alessia) chooses $y = 3$ and $a = 6$.\n- Judge (as Bernardo) selects $b = 7$.\n\nThe program of the contestant wins because all the books chosen by Bernardo pertain to different topics. The actions performed by the contestant and the judge in this example of interaction may be non-optimal.\n\n### Sample Input 2\n```\n4 10\n4 1 6 4\n```\n\n### Sample Output 2\n```\nBernardo\n4 1\n4\n1 10\n10\n6 3\n4\n4 5\n8\n```\n\n### Explanation of Sample 2\nIt can be shown that Bernardo can manage to fulfill his goal. An example of interaction (after reading the input) follows:\n- Contestant (as Bernardo) selects $b = 4$.\n- Judge (as Alessia) chooses $y = 1$ and $a = 10$.\n- Contestant (as Bernardo) selects $b = 10$.\n- Judge (as Alessia) chooses $y = 6$ and $a = 3$.\n- Contestant (as Bernardo) selects $b = 4$.\n- Judge (as Alessia) chooses $y = 4$ and $a = 5$.\n- Contestant (as Bernardo) selects $b = 8$.\n\nThe program of the contestant wins because Bernardo has selected two books on topic number 4. The actions performed by the contestant and the judge in this example of interaction may be non-optimal.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2024_I", "prompt": "# Problem Statement\n\n## Counting Multiplicative Magic $3 \\times 3$ Squares\n\nEveryone knows that a $3 \\times 3$ magic square must meet two criteria:\n1. All nine numbers must be positive and distinct.\n2. The sums along all rows, columns, and diagonals are equal.\n\nEveryone, except maybe Matt Parker (Recreational mathematician, author, comedian, YouTube personality, and science communicator).\nHe wants to create a magic square of squares, that is, a magic square that also meets a third criterion:\n3. Each number is a square of a positive integer.\n\nHis \"result\" can be seen in the picture in the corner.\nAs you may notice, his square is not that magic...\nNot only do most of the values appear twice, it also has a diagonal with the wrong sum.\nTo be honest, apart from containing non-square values, there is not much that could make this square worse.\nWell, at least he tried!\n\nBut that is all in the past.\nAfter finding the *Parker Square*, he decided to completely ignore property 3 from now on and to instead give property 2 a new twist.\nHe now considers multiplicative magic squares, which are exactly like normal magic squares except that the *products* along all rows, columns, and diagonals have to be equal, instead of the sums.\nWho knows, Matt might even manage to find a proper multiplicative magic square in the future!\n\nWith this definition at hand, Matt wrote some terrible Python code -- his words, not ours -- to count the number of multiplicative magic $3 \\times 3$ squares where the product of the numbers in a single row, column, or diagonal is at most $n$.\nAs you may have guessed by now, his code is way too slow.\nTherefore, we task you to do the same, just more efficiently.\nGiven an integer $n$, count the number of multiplicative magic $3 \\times 3$ squares with product at most $n$.\n\n## Input\nThe input consists of:\n- One line with an integer $t$ ($1 \\leq t \\leq 10^5$), the number of test cases.\n- $t$ lines, each with an integer $n$ ($1 \\leq n \\leq 10^{18}$), the maximum product.\n\n## Output\nFor each test case, output the number of multiplicative magic squares with product at most $n$.\n\n## Sample Input\n```\n3\n500\n1000\n3000\n```\n\n## Sample Output\n```\n8\n16\n56\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2023_J", "prompt": "# Problem: Jogging Tour\n\nYou may know that in the 17th century, a group of Dutchmen founded a settlement called New Amsterdam on Manhattan Island that later went on to become New York City. Less well-known is the story of another group of Dutchmen that also moved over to America and founded a city called *New Delft*. Like its bigger counterpart, New Delft has been built on a grid made up of two sets of parallel streets that meet each other at a perpendicular angle.\n\nSome stroopwafel bakeries have already been built in New Delft, but none of the streets have been constructed. Your task is to lay out the grid of streets. For this, you need to decide on an orientation for the grid so that there are two orthogonal directions for the two types of streets. Once the orientation is fixed, you may build arbitrary streets, as long as each of them has one of the two given directions, as shown in the illustration. Each street can be traversed in either direction.\n\nThe street layout should be created in an optimal way for the annual *Stroopwafel Run*. This is an event in which a group of runners visits all the bakeries in some order of their choosing, and they may start and end their run at any point in the city. Your task is to come up with a grid layout that makes this shortest path as short as possible.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($2 \\le n \\le 12$), the number of stroopwafel bakeries in New Delft.\n- $n$ lines, each with two integers $x$ and $y$ ($0 \\le x, y \\le 10^6$), the coordinates of one of the bakeries.\n\nThe bakeries are at distinct coordinates, so for any $1 \\le i, j \\le n$ with $i \\neq j$, it holds that $(x_i, y_i) \\neq (x_j, y_j)$.\n\n## Output\n\nOutput the length of the shortest possible path that visits all bakeries in some order, assuming an optimal grid layout.\n\nYour answer should have an absolute or relative error of at most $10^{-6}$.\n\n### Sample Input 1\n\n```\n3\n0 1\n1 2\n3 0\n```\n\n### Sample Output 1\n\n```\n4.24264068712\n```\n\n### Sample Input 2\n\n```\n4\n1 4\n6 0\n5 3\n2 6\n```\n\n### Sample Output 2\n\n```\n11.1566387517\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2023_B", "prompt": "### Problem Statement: Supporting Everyone\n\n**Time Limit:** 0.25 second\n\nAlice is attending a sport event with many national teams and one thing is important to her: supporting every country. There are $N$ countries represented, and she has two ways to support a country: either have the flag drawn on her or have a pin with the name of the country. Alice has a list containing, for each country, the colours needed to make its flag. A total of $M$ colours may appear across all flags, and in Alice's list, each colour is conveniently represented as an integer between 1 and $M$.\n\nEach crayon and pin costs 1, but her budget is tight. Can you help her find the minimum she can spend to support everyone?\n\n### Input\nThe first line contains two space-separated numbers $N$ and $M$. Then follow $2N$ lines, grouped in pairs; the $(2i - 1)$th and $2i$th lines represent the $i$th country. More precisely, the $(2i-1)$th line contains a single integer $k_i$: the number of colours in the flag of the $i$th country. Then, the $2i$th line contains $k_i$ space-separated numbers $C_{i,1}, C_{i,2}, \\ldots, C_{i,k_i}$: these are the colours in the flag of the $i$th country.\n\n### Output\nThe output should contain a single line, consisting of a single number: the minimum amount Alice can spend on crayons and pins to represent every country.\n\n### Limits\n- $1 \\leq N \\leq 1000$\n- $1 \\leq M \\leq 100$\n- $1 \\leq k_i \\leq M$ for all $i \\leq N$\n- $1 \\leq C_{i,j} \\leq M$ for all $i \\leq N$ and $j \\leq k_i$\n- For all $i \\leq N$, the $M$ colour numbers $C_{i,j}$ are pairwise distinct.\n\n### Sample Input 1\n```\n7 6\n3\n1 4 5\n3\n1 4 5\n3\n1 4 5\n3\n3 4 5\n3\n3 4 5\n3\n3 4 5\n3\n2 5 6\n```\n\n### Sample Output 1\n```\n5\n```\n\n### Sample Explanation 1\nThe first three countries could be France, the Netherlands, and the Czech Republic, all represented by blue (1), white (4), and red (5). The next three countries could be Italy, Hungary, and Bulgaria, with green (3), white (4), and red (5). The last country could be Germany, with black (2), red (5), and yellow (6). The minimum cost is 5: we buy four crayons (for blue, green, white, and red) and one pin (for Germany).\n\n### Sample Input 2\n```\n8 12\n2\n7 9\n12\n1 2 3 4 5 6 7 8 9 10 11 12\n2\n7 9\n2\n7 9\n3\n3 4 11\n2\n7 9\n2\n7 9\n2\n7 9\n```\n\n### Sample Output 2\n```\n4\n```\n\n### Sample Explanation 2\nWe can buy two crayons for the colours 7 and 11 and buy two pins for a total cost of 4. All six countries with flag colours 7 (red) and 11 (white) could be Canada, Indonesia, Japan, Malta, Monaco, and Poland. The flag of Belize has 12 colours, including red and white, and the fifth country could be Botswana.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2022_D", "prompt": "# Problem: Delft Distance\n\nYou are currently in your hotel at the north-west corner of Delft, and want to go to the contest site at the university in the south-east corner of Delft. To get there, you have to go right through the historical centre of the city. Like Manhattan, the city consists of a grid of $h \\times w$ buildings. But unlike Manhattan, the city does not only contain square residential buildings but also some round medieval towers. All the square buildings are axis aligned with a side length of $10~\\text{m}$ and all round towers have a diameter of $10~\\text{m}$. There is just enough space for a small alley of negligible width between two neighbouring buildings.\n\nSince you are already late for the contest start, you need to find a shortest path from your hotel to the contest site. Fortunately, you have a map of the city. See the illustration below for an example.\n\n## Input\nThe input consists of:\n- One line with two integers $h$ and $w$ ($1 \\leq h, w \\leq 700$), the number of rows and the number of columns of buildings shown on the map of the city.\n- $h$ lines, each with $w$ characters which are either `O` (for round towers) or `X` (for square buildings) describing the shapes of the buildings.\n\nThe map is oriented with the north side up.\n\n## Output\nOutput the length of a shortest path from the north-west corner to the south-east corner of Delft in metres. Your answer may have a relative or absolute error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n3 5\nXOOXO\nOXOXO\nXXXXO\n```\n\n## Sample Output 1\n```\n71.4159265359\n```\n\n## Sample Input 2\n```\n1 4\nXOOX\n```\n\n## Sample Output 2\n```\n45.7079632679\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2023_G", "prompt": "# Galaxy Quest\n\nYou are travelling through the galaxy in your spaceship. There are $n$ planets in the galaxy, numbered from $1$ to $n$ and modelled as points in $3$-dimensional space.\n\nYou can travel between these planets along $m$ space highways, where each highway connects two planets along the straight line between them. Your engine can accelerate (or decelerate) at $1\\,\\text{m}/\\text{s}^2$, while using fuel at a rate of $1$ litre per second. There is no limit to how fast you can go, but you must always come to a complete standstill whenever you arrive at the planet at the end of a highway.\n\nIt is possible for a highway to pass through planets other than the ones it connects. However, as your spaceship is equipped with special hyperspace technology, it simply phases through these obstacles without any need of stopping. Another consequence of using this technology is that it is impossible to jump from one highway to another midway through: highways must always be travelled in full.\n\nYou need to fly several missions, in which you start at your home planet (with number $1$) and need to reach a given target planet within a given time limit. For each mission, determine whether it can be completed, and if so, find the least amount of fuel required to do so. As an example, the figure below shows the optimal route for the second mission of the first sample.\n\n![Illustration of Sample Input 1, showing highways in blue, and a route from planet $1$ to planet $3$. The green start of a highway indicates acceleration, and the red end indicates deceleration.](sample1.pdf)\n\n## Input\n\nThe input consists of:\n- One line with three integers $n$, $m$, and $q$ ($1 \\le n,m,q \\le 10^5$, $n \\ge 2$), where $n$ is the number of planets, $m$ is the number of space highways, and $q$ is the number of missions.\n- $n$ lines, each with three integers $x_i$, $y_i$, and $z_i$ ($\\left|x_i\\right|,\\left|y_i\\right|,\\left|z_i\\right| \\le 10^3$, $1 \\le i \\le n$), the coordinates of planet $i$.\n- $m$ lines, each with two integers $a$ and $b$ ($1 \\le a,b \\le n$, $a \\neq b$), describing a space highway that connects planets $a$ and $b$. It can be traversed in either direction.\n- $q$ lines, each with two integers $c$ and $t$ ($2 \\le c \\le n$, $1 \\le t \\le 10^3$), the target planet and time limit for each mission.\n\nThe $n$ planets are in distinct locations. Their coordinates are given in metres, and the time limits of the missions are given in seconds. No two highways connect the same pair of planets. For each mission, both the absolute and relative differences between the given time limit and the shortest possible completion time are at least $10^{-6}$.\n\n## Output\n\nFor each mission, output the least amount of fuel in litres required to reach the target location within the time limit. If the target location cannot be reached within the time limit, output `impossible`.\n\nYour answers should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n\n```\n4 4 3\n-30 0 0\n0 0 0\n50 0 0\n-30 10 0\n1 2\n2 3\n3 4\n4 1\n2 10\n3 25\n4 7\n```\n\n## Sample Output 1\n\n```\nimpossible\n19.0538441903\n4.0000000000\n```\n\n## Sample Input 2\n\n```\n4 2 5\n-3 0 2\n7 -9 -3\n4 4 -6\n8 -1 8\n1 2\n2 3\n2 1000\n2 100\n3 1000\n3 100\n4 1000\n```\n\n## Sample Output 2\n\n```\n0.0287058122\n0.2874671888\n0.1120998619\n1.1272896971\nimpossible\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2022_L", "prompt": "# Problem: Last Guess\n\nIf you spent any amount of time on social media at the end of last year, you are probably familiar with the word finding game *Wordle*, in which you need to find a five-letter English word using at most six guesses. After each guess, the letters in that guess are marked in either green, yellow, or black to provide information about the hidden word:\n\n- Green indicates that the letter is in the hidden word and appears in the same position.\n- Yellow indicates that the letter is in the hidden word, but in a different position.\n- Black indicates that the letter has no more occurrences in the hidden word.\n- If a letter appears more than once in the guessed word, first all the green markings for that letter are placed. Then, from left to right in the guessed word, yellow markings are placed for each remaining occurrence of the letter in the hidden word. Finally, black markings are placed for any surplus of the letter in the guessed word. See the example below for more clarity.\n\nIn this problem, we consider a variant of Wordle where you need to find a hidden word of length $\\ell$ in at most $g$ guesses. Additionally, there is *no* requirement that the hidden word or any of the guesses are words of any language; any string consisting of lowercase English letters is fine.\n\nIn your current play of this variant, you have already used all but one of your guesses, and now you need to find the hidden word using your final guess. Find any word that could be the hidden word based on the information you have.\n\n## Input\n\nThe input consists of:\n- One line with two integers $g$ and $\\ell$ ($2 \\leq g \\leq 500$, $1 \\leq \\ell \\leq 500$), the maximal number of guesses allowed in the game and the length of the word.\n- $g-1$ lines, each with two strings $s$ and $t$ of length $\\ell$, where $s$ is one of the guesses so far and $t$ gives the colours for that guess according to the rules above. The string $s$ consists of lowercase English letters (a-z) and the string $t$ consists of uppercase letters `G', `Y', and `B' indicating green, yellow, and black respectively.\n\nIt is guaranteed that the input describes a valid state of a Wordle game before the last guess and that a valid solution exists, in the form of a length $\\ell$ word consisting of lowercase English letters.\n\n## Output\n\nOutput a valid last guess that gives you a chance of winning.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Input 1\n\n```\n4 5\nreply YYGBB\nrefer BBBGG\npuppy YYGBB\n```\n\n## Sample Output 1\n\n```\nupper\n```\n\n## Sample Input 2\n\n```\n2 12\naabbccddeeff GGGYGBYYYBBB\n```\n\n## Sample Output 2\n\n```\naabdcbegdhij\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2023_H", "prompt": "### Problem Statement\n\n**Break a leg!**\n\nTime limit: 0.5 second\n\nFor the first time, breakdance will be featured in the Olympics. And you get to participate! Well, you get to participate in the jury... More precisely, you get to build the table in front of which the jury will be seated: still, that is an impressive feat, congratulations!\n\nActually, the top of the table is already built: it is plane, has constant width and constant density, and its shape consists of the interior of an $N$-sided non-crossing polygon $P_1 P_2 \\ldots P_N$ in which no three vertices are collinear (i.e., no line goes through three vertices or more). You have three table legs of the same length and negligible width. Your task is to place them at distinct corners of the table so that the table remains stable when standing on these legs. In other words, you must choose three vertices $P_i$, $P_j$, and $P_k$ of the polygon such that the center of gravity of the polygon lies in the interior of the triangle $P_i P_j P_k$ (and not on its boundary).\n\nIn how many different ways can you do this? If two ways of placing legs differ only by a permutation of the legs, they are not counted as different ways.\n\n### Input\n\nThe first line contains the number $N$. Then follow $N$ lines: the $i$-th of these lines contains two space-separated integers $x_i$ and $y_i$, which are the $x$-coordinate and the $y$-coordinate of the vertex $P_i$.\n\n### Output\n\nThe output should contain a single line, consisting of a single integer: the number of ways of placing legs such that the table remains stable.\n\n### Limits\n\n- $3 \\le N \\le 100000$\n- $-1000000 \\le x_i \\le 1000000$ and $-1000000 \\le y_i \\le 1000000$ for all $i \\le N$\n- Whenever $1 \\le i < j < k \\le N$, the vertices $P_i$, $P_j$, and $P_k$ are not collinear\n- The polygonal shape $P_1 P_2 \\ldots P_N$ is non-crossing\n\n### Sample Input/Output\n\n#### Sample Input 1\n```\n4\n0 0\n1 0\n1 1\n0 1\n```\n\n#### Sample Output 1\n```\n0\n```\n\n#### Sample Input 2\n```\n4\n0 0\n5 0\n6 6\n0 5\n```\n\n#### Sample Output 2\n```\n1\n```\n\n#### Sample Input 3\n```\n5\n0 0\n2 0\n2 20\n1 1\n0 20\n```\n\n#### Sample Output 3\n```\n5\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2024_I", "prompt": "# Problem: Divination\n\nIn Yinxu, the archaeological site of the late capital of the Shang Dynasty, there are $N$ divination papers written in oracle bone script, numbered $1, 2, ..., N$. Some papers may cite other papers, but no paper can cite itself. Additionally, there are no circular citations, meaning it's not possible to see the following situation: $A_1$ cites $A_2$, $A_2$ cites $A_3$, ..., $A_{K-1}$ cites $A_K$, $A_K$ cites $A_1$ (where $2 \\leqslant K \\leqslant N$).\n\nAs per myth, a complete set of divination papers can predict the wars and peace of the next century, and it should have a complete citation chain, i.e., $A_1$ cites $A_2$, $A_2$ cites $A_3$, ..., $A_{N-1}$ cites $A_N$, without any papers missing. Please determine whether these $N$ divination papers constitute a complete set.\n\n## Input\n\nThe first line contains an integer $N$, represents the number of papers.\nThen $N$ lines follow, the $i$th of them represents the citations of the $i$th paper: the first integer $c_i$ represents the number of its citations, followed by $c_i$ integers $p_{i,1}, p_{i,2}, ..., p_{i,{c_i}}$ that represent the papers that it cites.\n\n## Output\n\nA single integer, 1 if they constitute a complete set of divination papers, or 0 otherwise.\n\n## Limits\n\n- $2 \\leqslant N \\leqslant 100\\ 000$;\n- $0 \\leqslant c_i \\leqslant N-1$ for all $i \\leqslant N$;\n- $0 \\leqslant c_1 + c_2 + ... + c_N \\leqslant 500\\ 000$;\n- $1 \\leqslant p_{i,j} \\leqslant N$ for all $i \\leqslant N$ and $j \\leqslant {c_i}$.\n- $p_{i,j} \\neq i$ for all $i \\leqslant N$ and $j \\leqslant {c_i}$.\n\n## Sample Input 1\n\n```\n4\n0\n2 1 4\n2 2 4\n1 1\n```\n\n## Sample Output 1\n\n```\n1\n```\n\n## Sample Input 2\n\n```\n4\n0\n1 1\n2 2 4\n1 1\n```\n\n## Sample Output 2\n\n```\n0\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2022_C", "prompt": "# Problem: Circular Caramel Cookie\n\nStroopwafels -- two crispy round waffles with a grid-like pattern on top, separated by a thin layer of gooey and delicious caramel -- are simply the most amazing Dutch treat ever. Everybody loves them and your factory is known for making the best and the biggest stroopwafels in town... At least, until now.\n\nThis year, your archrival Rob had the audacity to open up another factory for stroopwafels and they have already announced that their stroopwafels will be even bigger than yours. Although the exact size of the new stroopwafels is a well-kept secret, your industrial spy managed to find out that the grid-like pattern of the stroopwafel consists of at most $s$ whole squares. You know for a fact that the area of each square is $1~\\text{cm}^2$ and that the centre point of the stroopwafel always contains the common corner of the four adjacent squares in the centre (i.e., the squares are aligned to a Cartesian grid), as shown in the figure below.\n\nNeedless to say, there is no way that you will let Rob outdo you and you plan on releasing a new edition of bigger stroopwafels. Since the production of bigger stroopwafels is more expensive, you naturally want to make them as small as possible. Thus, you are interested in the minimum radius of a stroopwafel with strictly more than $s$ squares.\n\n## Input\nThe input consists of:\n- One line with an integer $s$ ($1 \\leq s \\leq 10^9$), the number of whole squares Rob's stroopwafel has at most.\n\n## Output\nOutput the minimum radius in centimetres of a stroopwafel with strictly more than $s$ whole squares. Your answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n11\n```\n\n## Sample Output 1\n```\n2.2360679775\n```\n\n## Sample Input 2\n```\n59\n```\n\n## Sample Output 2\n```\n5.0000000000\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2023_E", "prompt": "# Exponentiation\n\nIn her spare time, Zoe develops an online calculator. Unfortunately, the calculator was targeted by a denial-of-service attack last week. The attacker created a lot of integer variables, exponentiated them with each other, and tried to do a bunch of comparisons. The huge integers were too much for the server to handle, so it crashed. Before Zoe fixes the issue, she decides to actually perform the calculations that the attacker requested.\n\nThere are $n$ integer variables $x_1, x_2, \\dots, x_n$. At the start, each variable is set to $2023$. You have to perform $m$ instructions of the following two types:\n- **Operations**, of the form `! $i$ $j$`, where $i \\neq j$. This means that $x_i$ gets set to $x_i^{x_j}$.\n- **Queries**, of the form `? $i$ $j$`, where $i \\neq j$. This means that you should print `>` if $x_i$ is greater than $x_j$, `=` if $x_i$ is equal to $x_j$, and `<` if $x_i$ is smaller than $x_j$.\n\nConsider the first sample. After the $5$ operations, the values of the variables are:\n\\begin{align*}\nx_1 &= \\left(2023^{2023}\\right)^{2023^{2023}}, \\\\\nx_2 &= \\left(2023^{2023^{2023}}\\right)^{2023}, \\\\\nx_3 &= 2023, \\\\\nx_4 &= 2023^{2023}.\n\\end{align*}\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $m$ ($2 \\leq n \\leq 1000$, $1 \\leq m \\leq 1000$), the number of variables and the number of instructions.\n- $m$ lines, each containing a character $c$ (either `!` or `?`) and two integers $i$ and $j$ ($1 \\leq i, j \\leq n$, $i \\neq j$), describing the instructions.\n\n### Sample Input 1\n```\n4 8\n! 1 4\n! 2 1\n! 4 3\n! 1 4\n! 2 3\n? 3 4\n? 2 4\n? 2 1\n```\n\n### Sample Output 1\n```\n<\n>\n=\n```\n\n### Sample Input 2\n```\n4 9\n! 2 4\n! 1 2\n? 3 1\n? 1 2\n! 2 3\n? 1 2\n! 1 3\n! 3 2\n? 1 3\n```\n\n### Sample Output 2\n```\n<\n>\n>\n<\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2022_K", "prompt": "# Problem: Kebab Pizza\n\nAlice loves pizza and plans to throw a pizza party for her birthday, where she will make one big, round pizza for all her guests. She knows that her friends are a bit special when it comes to pizza:\n- Julie does not want any vegetables but loves kebab meat on her pizza.\n- Katy would never eat pizza with cheese on top.\n- Alice herself is a huge fan of pineapple on pizza, while Mickey absolutely hates it.\n- Instead, he wants to put spaghetti on it, which everybody else finds weird.\nThe list goes on and on. Briefly put, it is absolutely impossible to accommodate everybody.\n\nAs a compromise, Alice decides to let each person choose two toppings for their pizza slice in advance. Each person will be happy if their slice has exactly their two chosen toppings and none of the others. Note that a person may choose the same topping twice, in which case they just get twice the amount of that topping.\n\nOn the day of her party, Alice discovers that the rolled out pizza dough takes up so much space on her kitchen counter that she can only prepare one kind of topping at a time. To optimise the workflow and to make sure that the pizza is ready in time for her party, she wants to take out each chosen kind of topping only once and then add it on a consecutive range of pizza slices. Note that the whole pizza forms a consecutive range of pizza slices in a circular fashion. Determine whether it is possible to prepare the pizza in this way while satisfying all the chosen topping combinations. See the illustration below for an example.\n\nIllustration of Sample Input 1, with two toppings numbered on every slice in one possible solution. Note that each topping only occurs on a single range of pizza slices.\n\n## Input\nThe input consists of:\n- One line with two integers $n$ and $k$ ($3 \\leq n, k \\leq 10^5$), the number of pizza slices and the number of possible toppings which are numbered from $1$ to $k$.\n- $n$ lines, each with two integers $a$ and $b$ ($1 \\leq a, b \\leq k$), describing the toppings chosen by the $i$th person.\n\n## Output\nOutput `possible` if it is possible for Alice to select a consecutive range of pizza slices for each chosen topping such that the resulting pizza can be split into $n$ suitable slices. Otherwise, output `impossible`.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n7 6\n2 2\n3 6\n1 1\n1 5\n4 5\n6 6\n6 5\n```\n\n### Sample Output 1\n```\npossible\n```\n\n### Sample Input 2\n```\n5 5\n1 3\n1 5\n2 3\n2 5\n3 4\n```\n\n### Sample Output 2\n```\npossible\n```\n\n### Sample Input 3\n```\n6 7\n1 2\n2 3\n3 4\n4 5\n3 6\n6 7\n```\n\n### Sample Output 3\n```\nimpossible\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2024_L", "prompt": "# Problem L: The Charioteer\n\nAs you are studying ancient Greek mythology, you stumble upon the legend of Phaethon, son of Helios. After being recognized by Helios as his son, he asks him to drive his chariot. Despite the warnings of Helios that only he can control the horses, Helios obliges, giving Phaethon the control of the chariot.\n\nTragically, Phaethon loses control of the chariot, which gets too close to the Earth and burns it.\n\nHowever, you wonder if maybe the story could have ended differently. If Phaethon reaches the temple of Helios, then the chariot can be stopped by Helios himself. For that, you create a model that fits the story.\n\nGreece can be represented as a 2D infinite grid, with Phaethon and his chariot starting at coordinate $(0,0)$, facing the Ox axis in the direction of increasing X. The temple of Helios is placed in an unknown position $(X,Y)$ on this 2D grid. Initially, the velocity $V$ of the chariot is 1.\n\nAt each timestep, the following happens in order:\n1. Phaethon does one of the following 3 actions: turn the chariot left 90 degrees, continue facing front, or turn the chariot right 90 degrees;\n2. The chariot moves $V$ units in the direction it is facing;\n3. $V$ is increased by 1;\n4. The Oracle tells Phaethon the Manhattan distance between his position and the position of the temple of Helios.\n\nThe Manhattan distance between $(X1,Y1)$ and $(X2,Y2)$ is $|X1-X2|+|Y1-Y2|$.\n\nIf the velocity ever reaches $2 \\times 10^4$, the chariot gets uncontrolled and too close to the earth. If at the end of a step, the chariot is in $(X, Y)$, the chariot is stopped.\n\n## Input and Output\n\nThis is an interactive problem. As such, no initial input is provided in this problem, and you get to ask a question first.\n\nAt each step, you must print a line to act on the direction of the chariot. This line must follow the description `? c` followed by a newline, where `c` is either `L` to rotate counterclockwise, `R` to rotate clockwise, or `F` to keep the direction unchanged. If it does not respect this format, you will receive a WRONG-ANSWER verdict.\n\nAfter sending a line, you must always flush the output. Otherwise, you will get the verdict TIMELIMIT.\n\nThe Oracle then prints a single integer, that you can read on the standard input, denoting the Manhattan distance between your new position (after moving $V$ units in the specified direction) and the temple. $V$ is increased after updating your position.\n\nIf this distance is $0$, it means you arrived at the temple of Helios and thus should stop interaction immediately (exiting your program), receiving an ACCEPTED verdict.\n\nNotice that you must be in the temple after your move, just flying above the temple with the chariot does not count.\n\nIf your velocity ever reaches $2 \\times 10^4$, you will receive the verdict WRONG-ANSWER.\n\n## Limits\n\n- $|X| \\leq 10^6$\n- $|Y| \\leq 10^6$\n- $|V| \\leq 2 \\times 10^4$\n\n## Sample Interaction\n\nIn this section, to clarify what the input and output should be, `>` is printed before what your program should output, and `<` is printed before what your program can read on standard input. Do not include these characters in your real input/output.\n\nIn this example, the temple of Helios (whose position you must guess) is located at $X=1$, $Y=5$.\nThe left column is the I/O. The right column is the state of the chariot after the requested move happened.\n\n```\n> ? F\n< 5\n> ? L\n< 3\n> ? F\n< 0\n```\n\n| Output | State of the Chariot |\n|--------|----------------------|\n| `> ? F` | Chariot moves to (1, 0), orientation = right, $V$ = 2 |\n| `< 5` | Distance from (1,0) to (1,5) is 5 |\n| `> ? L` | Chariot moves to (1, 2), orientation = up, $V$ = 3 |\n| `< 3` | Distance from (1,2) to (1,5) is 3 |\n| `> ? F` | Chariot moves to (1, 5), orientation = up, $V$ = 4 |\n| `< 0` | Success |\n\nAn interactive Python script where you can enter commands and see how the judge would respond is also available on the Web version of this problem.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2024_F", "prompt": "# Problem: Yaxchil\u00e1n Maze\n\n## Problem Statement\n\nYears spent deciphering Mayan glyphs had led Dr. Wood, a famous archeologist, to this very moment: inside a chamber of the Yaxchil\u00e1n maze, in the middle of the Lacandon Jungle, the last undiscovered Mayan codex appeared before her. It was beautiful, protected by jaguar pelt and adorned with jade. However, as soon as she touched it, all the corridors of the maze closed. She was now a prisoner of the maze. Worse, she was not alone, but had a full team of archeologists with her that were also held prisoner in different chambers of the maze.\n\nAs she examined the codex, a series of intricate diagrams caught her eye. They depicted the maze, its corridors morphing into different configurations, each aligned with a specific position of the sun. Another set of diagrams showed intricately carved holes in the walls together with a chilling depiction of a giant wasp. A realization dawned on her \u2013 the Maya had designed this maze to change with the sun's position, and some chambers were booby-trapped with a giant nest of deadly wasps.\n\nNamely, there are $N$ chambers in the maze numbered $0, \\ldots, N-1$. Dr. Wood and the members of her team start in chambers $0, 1, \\ldots, A - 1$ (one person per chamber). There are $E$ exits: chambers $N - E, \\ldots, N - 1$. Initially, the maze contains no open corridors. At each hour (00:00, 01:00, 02:00, and so on, represented by integers 0, 1, 2, and so on), a new corridor between two chambers opens. This corridor stays open for exactly $M$ hours minus one minute. Corridors are bi-directional.\n\nAmong the $N$ chambers, $B$ are booby-trapped. The trap of a chamber triggers as soon as it is connected to at least $K$ other chambers. When triggered, a gigantic swarm of deadly wasps appears in the chamber and immediately spreads to all chambers connected to the booby-trapped chamber. Furthermore, as time progresses, the wasps never disappear from a chamber, and worse, they continue to spread instantaneously from chambers that contain wasps to newly connected chambers. Two chambers are considered connected at a given time when there exists a path of one or multiple open corridors that allows going from one chamber to the other.\n\nThanks to the codex and to her knowledge of the maze (and smartphones!), Dr. Wood and each member of her team have full information on the maze at hour 0, including all future events: in particular, they each know where they are in the maze, where corridors lead to, the exact time, when corridors open and close and which chambers they connect, the location of the booby-traps, exits, $K$, and can deduce which chambers are or will be filled with deadly wasps. All the archeologists can move freely and independently from each other using the open corridors at all times. They run fast and can move to any reachable chamber in less than 59 minutes. If an archeologist ends up in a chamber filled with deadly wasps, he or she dies and cannot exit the maze.\n\nThe exit chambers behave as the other chambers: they can be filled with wasps and be booby-trapped. As soon as an archeologist reaches any exit chamber not filled with wasps, she or he exits the maze and its dangers. Can you tell the earliest time when each archeologist can exit the maze?\n\n## Input\n\n- The first line contains the integer $A$, the number of archeologists.\n- The second line contains the integer $N$.\n- The third line contains the integer $M$.\n- The fourth line contains the integer $E$.\n- The fifth line contains the integer $T$, the number of hours at which corridors open.\n- The sixth line contains $B$, followed by the list of the $B$ space-separated booby-trapped chambers $b_i$.\n- The seventh line contains $K$.\n- In the next $T$ lines, line $t$ contains two space-separated integers $u_t, v_t$ representing a corridor that opens at hour $t$ and connects chambers $u_t$ and $v_t$. $t$ goes from $0$ to $T - 1$ (inclusive). Multiple corridors can connect the same two chambers. A corridor can connect a chamber to itself.\n\n## Output\n\nThe output should contain $A$ lines. The $i$-th line represents the $i$-th archeologist. If the $i$-th archeologist can exit the maze, it should be the integer representing the earliest hour at which she or he can exit. Otherwise, it should be \"IMPOSSIBLE\" (without quotes).\n\n## Limits\n\n- $1 \\leqslant A \\leqslant 50$\n- $2 \\leqslant N \\leqslant 50\\,000$\n- $1 \\leqslant M \\leqslant 100\\,000$\n- $1 \\leqslant E \\leqslant 100$\n- $A + E \\leqslant N$ (no chamber is both a starting chamber and an exit chamber)\n- $1 \\leqslant T \\leqslant 500\\,000$\n- $0 \\leqslant B \\leqslant N$\n- $0 \\leqslant b_i < N$ for $i=0,\\dots, B-1$\n- The $b_i$'s are unique\n- $0 \\leqslant K < N$\n- $0 \\leqslant u_t < N$ for $t=0,\\dots, T-1$\n- $0 \\leqslant v_t < N$ for $t=0,\\dots, T-1$\n\n## Sample Input 1\n\n```plaintext\n1\n5\n1\n1\n5\n0\n0\n0 1\n0 2\n2 3\n2 4\n0 4\n```\n\n## Sample Output 1\n\n```plaintext\n3\n```\n\n## Sample Input 2\n\n```plaintext\n1\n4\n1\n1\n3\n0\n0\n0 1\n2 3\n1 2\n```\n\n## Sample Output 2\n\n```plaintext\nIMPOSSIBLE\n```\n\n## Sample Input 3\n\n```plaintext\n4\n10\n2\n2\n11\n2 3 7\n2\n0 1\n1 2\n2 3\n1 4\n4 9\n5 6\n0 6\n5 7\n1 6\n7 8\n6 8\n```\n\n## Sample Output 3\n\n```plaintext\n9\n9\n9\nIMPOSSIBLE\n```\n\n## Explanation\n\n### Sample 1\n\nThere are no booby-traps. Dr. Wood (the only archeologist) starts at $0$ and the exit is $4$. After the corridor `0 2` opens, she goes from chamber $0$ to chamber $2$. She stays there until the corridor `2 4` opens, which allows her to reach chamber $4$ and exit at hour $3$.\n\n### Sample 2\n\nThere are no booby-traps. Dr. Wood (the only archeologist) starts at $0$ and the exit is $3$. Unfortunately, Dr. Wood can only reach chamber $2$ after the corridor `2 3` leading to the exit closed. She cannot exit the maze.\n\n### Sample 3\n\nThe fastest path to an exit for the first archeologist starting at 0 is to go to chamber 5 at hour $6$ using corridors `0 6` and `5 6`, then to chamber 7 at hour $7$ using the corridor `5 7`, and finally reach chamber 8 (an exit) at hour 9 using the corridor `7 8`. Note that chamber 7 is booby-trapped, but the wasps only appear at hour 10, after the first archeologist exited the maze.\n\nThe second archeologist starting at 1 can move to chamber 0 at hour 0 and then follow the path of the first archeologist.\n\nThe third archeologist starting at 2 can move to chamber 0 at hour 1 and then follow the first two archeologists.\n\nThe last archeologist starting at 3 is killed by the wasps at hour 2.\n\nAt the end, chambers 1, 2, 3, 4, 6, 7, 8, 9 are filled with wasps.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2023_C", "prompt": "# Chair Dance\n\nIn a deterministic version of *Musical Chairs* (you do not need to know the original game, but you can try to play it after the contest is over), there are $n$ chairs placed in a circle. The chairs are numbered from $1$ to $n$ in clockwise order. Initially, the $i$th player sits on the $i$th chair. During the game, the game master gives commands to all players at once.\n\nThe first type of command tells each player to move $x$ chairs farther in clockwise order, so they must move from chair $i$ to chair $i + x$.\n\nThe second type of command tells each player to move from chair $i$ to chair $i \\cdot x$. Both these calculations are done modulo $n$, where a remainder of $0$ corresponds to chair $n$.\n\nIf two or more people want to move to the same chair, then the player needing to travel the least in clockwise direction to reach the chair gets to take the seat, and the other players trying to reach the same chair are out of the game. This is illustrated in Figure 1, where the larger circles represent the chairs and their numbers are written on their inside. The smaller circles represent the players. The next command (`* 10`) tells player $10$ (now on seat $11$) and player $4$ (now on seat $5$) to move to chair $2$. However, since player $10$ needs to travel less, this player gets to take the seat. Note that the other $10$ players will also move to some other chairs, but this is omitted from the figure for the sake of readability.\n\nThe jury wasted most of their free time designing this game and now need to go back to work. Fortunately, the game is deterministic, so you can play the game without the help of the jury.\n\n## Input\n\nThe input consists of:\n\n- One line with two integers $n$ and $q$ ($2 \\leq n, q \\leq 5 \\cdot 10^5$), the number of chairs and the number of commands.\n- $q$ lines, each containing one of three command types:\n - `+ $x$`: The player on chair $i$ moves to chair $i + x$.\n - `* $x$`: The player on chair $i$ moves to chair $i \\cdot x$.\n - `? $x$`: Tell us the number of the player on chair $x$.\n\nAll of the values $x$ will satisfy $1 \\leq x \\leq n$.\n\n## Output\n\nFor each command of type `?`, output the number of the player on the requested chair. If the chair is currently empty, output $-1$ instead.\n\n## Sample Input 1\n\n```plaintext\n12 10\n? 12\n+ 1\n? 12\n* 10\n? 2\n* 5\n? 2\n* 6\n? 1\n? 12\n```\n\n## Sample Output 1\n\n```plaintext\n12\n11\n10\n6\n-1\n11\n```\n\n## Sample Input 2\n\n```plaintext\n32 11\n* 6\n? 8\n* 6\n+ 31\n* 28\n? 4\n+ 1\n* 2\n+ 1\n* 3\n? 1\n```\n\n## Sample Output 2\n\n```plaintext\n28\n32\n32\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2023_G", "prompt": "### Problem Statement: Favourite Dish\n\n**Time Limit:** 4 seconds\n\nFrance is a country of gastronomy. For a dish, both the taste and plating are important. Nevertheless, when different people evaluate a dish, some focus more on taste and some focus more on plating. At the Olympic Village dining hall, there are $N$ dishes, numbered from 1 to $N$; each dish has a score on its taste and a score on its plating. There are also $M$ persons, numbered from 1 to $M$; each person has a weight on taste and a weight on plating. One person's final score of a dish is the weighted average of the dish's scores on taste and plating.\n\nThe chefs at the Olympics want to provide everyone with their favourite dish on the evening of the closing ceremony. Your task is to calculate everyone's favourite dish. If multiple dishes tie for the highest score as a person's favourite, choose the one with the smallest number.\n\n**Input:**\n- The first line contains two space-separated integers $N$ and $M$.\n- The next $N$ lines each contain two integers $t_k$ and $p_k$, which are the scores of the dish $k$ on taste and on plating.\n- The next $M$ lines each contain two integers $T_e$ and $P_e$, which are the weights of person $e$ on taste and on plating.\n\n**Output:**\n- The output should contain $M$ lines. The $a$-th such line should contain one number: the number of the favourite dish of person $a$.\n\n**Constraints:**\n- $1 \\leq N \\leq 500000$\n- $1 \\leq M \\leq 500000$\n- $0 \\leq t_k \\leq 1000000$, $0 \\leq p_k \\leq 1000000$, and $(t_k, p_k) \\neq (0, 0)$ for all $k \\leq N$\n- $0 \\leq T_e \\leq 1000000$, $0 \\leq P_e \\leq 1000000$, and $(T_e, P_e) \\neq (0, 0)$ for all $e \\leq M$\n- The $N$ pairs $(t_k, p_k)$ are pairwise distinct.\n- The $M$ pairs $(T_e, P_e)$ are pairwise distinct.\n\n**Sample Input 1:**\n```\n4 3\n2 5\n3 4\n4 2\n1 6\n6 4\n2 8\n5 5\n```\n\n**Sample Output 1:**\n```\n2\n4\n1\n```\n\n**Sample Explanation 1:**\nHere is the score table for each person on each dish. Each person's favourite dish is indicated with a *:\n- Person 1: \n - Dish 1: $2 \\times 6 + 5 \\times 4 = 32$\n - Dish 2: $3 \\times 6 + 4 \\times 4 = 38$\n - Dish 3: $4 \\times 6 + 2 \\times 4 = 32$\n - Dish 4: $1 \\times 6 + 6 \\times 4 = 30$\n - Favourite: Dish 2\n- Person 2: \n - Dish 1: $2 \\times 2 + 5 \\times 8 = 44$\n - Dish 2: $3 \\times 2 + 4 \\times 8 = 38$\n - Dish 3: $4 \\times 2 + 2 \\times 8 = 24$\n - Dish 4: $1 \\times 2 + 6 \\times 8 = 50$\n - Favourite: Dish 4\n- Person 3: \n - Dish 1: $2 \\times 5 + 5 \\times 5 = 35$\n - Dish 2: $3 \\times 5 + 4 \\times 5 = 35$\n - Dish 3: $4 \\times 5 + 2 \\times 5 = 30$\n - Dish 4: $1 \\times 5 + 6 \\times 5 = 35$\n - Favourite: Dish 1 (smallest number among the tied dishes)\n\n**Sample Input 2:**\n```\n3 4\n1 0\n0 2\n0 1\n1 1\n2 2\n2 1\n1 0\n```\n\n**Sample Output 2:**\n```\n2\n2\n1\n1\n```\n\n**Sample Explanation 2:**\nHere is the score table for each person on each dish. Each person's favourite dish is indicated with a *:\n- Person 1: \n - Dish 1: $1 \\times 1 + 0 \\times 1 = 1$\n - Dish 2: $0 \\times 1 + 2 \\times 1 = 2$\n - Dish 3: $0 \\times 1 + 1 \\times 1 = 1$\n - Favourite: Dish 2\n- Person 2: \n - Dish 1: $1 \\times 2 + 0 \\times 2 = 2$\n - Dish 2: $0 \\times 2 + 2 \\times 2 = 4$\n - Dish 3: $0 \\times 2 + 1 \\times 2 = 2$\n - Favourite: Dish 2\n- Person 3: \n - Dish 1: $1 \\times 2 + 0 \\times 1 = 2$\n - Dish 2: $0 \\times 2 + 2 \\times 1 = 2$\n - Dish 3: $0 \\times 2 + 1 \\times 1 = 1$\n - Favourite: Dish 1\n- Person 4: \n - Dish 1: $1 \\times 1 + 0 \\times 0 = 1$\n - Dish 2: $0 \\times 1 + 2 \\times 0 = 0$\n - Dish 3: $0 \\times 1 + 1 \\times 0 = 0$\n - Favourite: Dish 1\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2024_E", "prompt": "# Problem Statement\n\n## Problem Name\nE: Building the Fort\n\n## Problem Description\nYou are a Roman general setting up a defence fort against the Barbarians. \n\nYou only know how to build straight walls, so your fort is going to be polygon-shaped.\n\nDue to the shape of the land, which has multiple hills located at all the integer coordinates, you know that the enemy artillery can only be installed in very specific ways, and that higher positions inside your fort are more vulnerable, which means that:\n- All the vertices of the polygon must have integer coordinates between $1$ and $10^9$ (inclusive).\n- $N$ known points $(x_i, y_i), i=1,\\dots,N$, with integer coordinates between $1$ and $10^9$ (inclusive), initially given, must be among the vertices of the polygon.\n- No point with integer coordinates can be located strictly inside the polygon, as it would be vulnerable to the enemy artillery otherwise.\n- The polygon has to be simple (a simple polygon is a polygon formed by a single closed path that does not intersect itself or overlap itself).\n\nIn addition, due to the cost of building this fort and the limited materials, you can only afford to build a polygon with a number of vertices smaller than or equal to $3N$.\n\nIt can be shown that such a polygon always exists.\n\n## Input\nThe first line contains the integer $N$. The next $N$ lines contain two space-separated integers $x_i$, $y_i$, the points that must be among the vertices of the polygon.\n\n## Output\nThe first line should contain $K$, the number of vertices of the polygon.\n\nThe next $K$ lines should contain two space-separated integers $x'_i$, $y'_i$, the coordinates of the vertices of the polygon. They must be in an order that forms a closed and non-intersecting path that defines the outline of the polygon.\n\nIf there are multiple solutions, you can output any of them.\n\n## Limits\n- $3 \\leqslant N \\leqslant 1\\,000$\n- $1 \\leqslant x_i \\leqslant 10^9$ for $i=1,\\dots,N$\n- $1 \\leqslant y_i \\leqslant 10^9$ for $i=1,\\dots,N$\n- All $(x_i, y_i)$ are unique\n- $1 \\leqslant x'_i \\leqslant 10^9$ for $i=1,\\dots,K$\n- $1 \\leqslant y'_i \\leqslant 10^9$ for $i=1,\\dots,K$\n- All $(x'_i, y'_i)$ must be unique\n\n## Sample Input and Output\n\n### Sample Input\n```\n4\n1 1\n1 3\n3 1\n3 3\n```\n\n### Sample Output\n```\n5\n1 1\n3 1\n3 3\n2 2\n1 3\n```\n\n### Explanation\nOn the other hand, the following polygons are **not** valid solutions:\n\n- A square with vertices at $(1,1)$, $(1,3)$, $(3,3)$, $(3,1)$.\n- A square with vertices at $(1,1)$, $(3,3)$, $(3,1)$, $(1,3)$.\n- A polygon with vertices at $(1,1)$, $(1,3)$, $(3,3)$, $(2,3)$, $(2,2)$, $(2,3)$, $(3,1)$.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2023_M", "prompt": "### Problem Statement\n\n#### In-order\n\n**Time limit:** 1 second\n\nThe opening ceremony for the Olympic Games will take place on the river with teams on boats. The layout of the athletes on top of the boat has been designed in a very specific way: for each team, the $N$ athletes (conveniently numbered from 1 to $N$) are arranged as a binary tree.\n\nThe organiser has also designed the pre-order traversal, post-order traversal, and a (possibly empty) consecutive part of the in-order traversal of the binary tree that each team must follow.\n\nNow, to make sure there are enough tree layouts so that each team can have a distinct one, you are asked to calculate the quantity of different possible in-order traversals, say $T$, modulo the prime number 999,999,937.\n\n#### Input\nThe input consists of four lines. The first line contains the number $N$. Each subsequent line contains a list of $N$ space-separated integers. The second line contains a list $A_1, A_2, \\ldots, A_N$, where $A_k$ is the number of the $k$-th athlete found in pre-order traversal. The third line contains a list $B_1, B_2, \\ldots, B_N$, where $B_k$ is the number of the $k$-th athlete found in post-order traversal. The fourth line contains a list $C_1, C_2, \\ldots, C_N$, where $C_k$ is either the number of the $k$-th athlete found in in-order traversal, or 0 if the organiser did not say who that $k$-th athlete should be.\n\n#### Output\nThe output should contain a single line, consisting of a single integer $S$: this is the only integer such that $0 \\leq S < 999,999,937$ and for which $T - S$ is divisible by 999,999,937.\n\n#### Limits\n- $1 \\leq N \\leq 500,000$\n- There exists at least one binary tree with such pre-order, post-order, and in-order traversals.\n- The integers $k$ for which $C_k \\geq 1$ form a (possibly empty) sub-interval of the set $\\{1, 2, \\ldots, N\\}$. In other words, whenever $k \\leq l$ and both $C_k$ and $C_l$ are positive, all the integers $C_k, C_{k+1}, \\ldots, C_l$ are positive.\n\n#### Sample Input 1\n```\n8\n1 2 3 5 6 4 7 8\n5 6 3 8 7 4 2 1\n0 0 6 2 4 0 0 0\n```\n\n#### Sample Output 1\n```\n2\n```\n\n#### Sample Explanation 1\nThe two possible binary trees have the following in-order traversals:\n- 5 3 6 2 4 8 7 1\n- 5 3 6 2 4 7 8 1\n\n#### Sample Input 2\n```\n3\n1 2 3\n3 2 1\n0 0 0\n```\n\n#### Sample Output 2\n```\n4\n```\n\n#### Sample Explanation 2\nThe four possible in-order traversals are:\n- 3 2 1\n- 2 3 1\n- 1 3 2\n- 1 2 3\n\n#### Sample Input 3\n```\n4\n1 2 3 4\n4 3 2 1\n0 4 0 0\n```\n\n#### Sample Output 3\n```\n3\n```\n\n#### Sample Explanation 3\nThe three possible in-order traversals are:\n- 2 4 3 1\n- 1 4 3 2\n- 3 4 2 1\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2024_A", "prompt": "# Problem Statement\n\n## Sort a List of Dutch Surnames\n\n- Sort a list of $n \\leq 1000$ Dutch surnames with lengths up to $50$ based on the Dutch rules, lexicographically, according to the values of the ASCII characters.\n- Consider only the part starting from the first capital letter.\n- The surnames consist of English letters, spaces, and apostrophes (`A-Z`, `a-z`, ` `, `'`).\n- It is guaranteed that the part starting with the first capital letter is unique.\n- Names have no leading, trailing, or consecutive spaces.\n- For example, the surname `van den Hecken the Younger` is sorted according to `Hecken the Younger`.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($1 \\leq n \\leq 1000$), the number of surnames.\n- $n$ lines, each with a string $s$ ($1 \\leq |s| \\leq 50$), one of the surnames. The surnames consist of English letters, spaces, and apostrophes (`A-Z`, `a-z`, ` `, `'`).\n\nIt is guaranteed that the part starting with the first capital letter is unique. Names have no leading, trailing, or consecutive spaces.\n\n## Output\n\nOutput the list of surnames, sorted according to the Dutch rules.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n7\nvan der Steen\nfakederSteenOfficial\nGroot Koerkamp\nBakker\nvan den Hecken the Younger\nde Waal\nvan 't Hek\n```\n\n### Sample Output 1\n```\nBakker\nGroot Koerkamp\nvan den Hecken the Younger\nvan 't Hek\nvan der Steen\nfakederSteenOfficial\nde Waal\n```\n\n### Sample Input 2\n```\n5\nvar Emreis\nan Gleanna\nTerzieff Godefroy\naep Ceallach\nof Rivia\n```\n\n### Sample Output 2\n```\naep Ceallach\nvar Emreis\nan Gleanna\nof Rivia\nTerzieff Godefroy\n```\n\n### Sample Input 3\n```\n7\nvan den Brand\nden Brand Heek\nBrand 'Heek\nvan Brand heek\nDeN bRAnD hEeK\nden brandHeek\nder Brandheek\n```\n\n### Sample Output 3\n```\nvan den Brand\nBrand 'Heek\nden Brand Heek\nvan Brand heek\nder Brandheek\nDeN bRAnD hEeK\nden brandHeek\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2022_H", "prompt": "# Problem H: Controllers\n## SWERC 2022-2023\n\n## Problem Statement\n\nYou are at your grandparents' house and you are playing an old video game on a strange console. Your controller has only two buttons, and each button has a number written on it.\n\nInitially, your score is 0. The game is composed of $n$ rounds. For each $1 \\le i \\le n$, the $i$-th round works as follows:\n- On the screen, a symbol $s_i$ appears, which is either + (plus) or - (minus).\n- Then you must press one of the two buttons on the controller once. Suppose you press a button with the number $\\alpha$ written on it: your score will increase by $\\alpha$ if the symbol was + and will decrease by $\\alpha$ if the symbol was -.\n- After you press the button, the round ends.\n\nAfter you have played all $n$ rounds, you win if your score is 0.\n\nOver the years, your grandparents bought many different controllers, so you have $q$ of them. The two buttons on the $j$-th controller have the numbers $a_j$ and $b_j$ written on them. For each controller, you must compute whether you can win the game playing with that controller.\n\n## Input\n\nThe first line contains a single integer $n$ ($1 \\le n \\le 2 \\times 10^5$) - the number of rounds.\nThe second line contains a string $s$ of length $n$ \u2014 where $s_i$ is the symbol that will appear on the screen in the $i$-th round. It is guaranteed that $s$ contains only the characters + and -.\nThe third line contains an integer $q$ ($1 \\le q \\le 10^5$) \u2014 the number of controllers.\nThe following $q$ lines contain two integers $a_j$ and $b_j$ each ($1 \\le a_j, b_j \\le 10^9$) \u2014 the numbers on the buttons of controller $j$.\n\n## Output\n\nOutput $q$ lines. On line $j$ print YES if the game is winnable using controller $j$, otherwise print NO.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n8\n+-+---+-\n5\n2 1\n10 3\n7 9\n10 10\n5 3\n```\n\n### Sample Output 1\n```\nYES\nNO\nNO\nNO\nYES\n```\n\n### Explanation of Sample 1\nOne possible way to get a score of 0 using the first controller is by pressing the button with number 1 in rounds 1, 2, 4, 5, 6, and 8, and pressing the button with number 2 in rounds 3 and 7. It is possible to show that there is no way to get a score of 0 using the second controller.\n\n### Sample Input 2\n```\n6\n+-++\n2\n9 7\n1 1\n```\n\n### Sample Output 2\n```\nYES\nYES\n```\n\n### Sample Input 3\n```\n20\n+-----+--+--------+-\n2\n1000000000 99999997\n250000000 1000000000\n```\n\n### Sample Output 3\n```\nNO\nYES\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2024_D", "prompt": "# Problem Statement\n\nThe process of forming the Dutch government has taken more than half a year for three elections in a row. Perhaps we can streamline the initial stages of coalition building?\n\nThe first step after the election results is to find a group of parties (called a *coalition*) with enough seats to have a strict majority. Your task is to count the number of candidate coalitions that satisfy specific conditions. A coalition is considered a *candidate coalition* if it meets these two criteria:\n\n- **Strict Majority:** The total number of seats held by the coalition must be strictly more than half of the total seats across all parties.\n- **No Superfluous Parties:** The coalition must be minimal in the sense that removing any one party from the coalition would cause it to lose its strict majority.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($1 \\le n \\le 60$), the number of parties.\n- One line with $n$ integers $p$ ($1 \\le p \\le 10\\,000$), the number of seats each party has.\n\n## Output\n\nOutput the total number of candidate coalitions that satisfy the criteria above.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n5\n3 1 4 1 5\n```\n\n### Sample Output 1\n```\n4\n```\n\n### Sample Input 2\n```\n11\n191 24 148 38 8 28 9 1 3 3 12\n```\n\n### Sample Output 2\n```\n38\n```\n\n### Sample Input 3\n```\n4\n1 2 3 4\n```\n\n### Sample Output 3\n```\n3\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2023_B", "prompt": "# Problem: Brickwork\n\nBob the Builder is tired of building tiny houses and paving narrow roads, and he strives for something bigger. The new job given to him by a very eccentric client is exactly what he needs: He is tasked with building a wall of a certain width that is infinitely high! His client assured him that he does not need to worry about the building material, and that an infinite supply of various kinds of bricks has already been ordered for him. Of course, building a stable wall takes very careful planning, especially if it is supposed to be infinitely high. In particular, a wall is only stable if no two gaps between bricks in consecutive rows end up directly above each other, as shown in the figure below.\n\nBob knows from his long-time experience that if it is possible to build such a wall, then it can be done by alternating just two row configurations.\n\n**Figure:**\nOn the left, we see an unstable wall using the brick types of Sample Input 1. On the right, we see a stable wall using the same brick types. Note that even though only two rows of the wall are shown, it is possible to build an infinitely high wall by repeating these two row configurations.\n\nGiven the types of bricks available, is it possible to build a stable wall of width exactly $w$ and infinite height? If yes, how should Bob build it using only two alternating row configurations?\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $w$ $(1 \\leq n, w \\leq 3 \\cdot 10^5)$, the number of brick types and the width of the wall.\n- One line with $n$ integers $b$ ($1 \\leq b \\leq w$), the widths of the brick types.\n\nNote that Bob has an infinite supply of all brick types.\n\n## Output\n\nIf it is possible to build a wall, then output `possible`. Otherwise, output `impossible`.\n\nIf a wall can be built, provide two row configurations that can be used in an alternating fashion. For both rows, first output the number of bricks needed for that row, followed by the lengths of the bricks in the order you want to use them. Your solution is considered valid if alternating the two rows infinitely would result in a stable wall.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Input 1\n\n```\n4 12\n3 2 7 2\n```\n\n## Sample Output 1\n\n```\npossible\n5\n2 2 3 2 3\n3\n3 2 7\n```\n\n## Sample Input 2\n\n```\n3 11\n6 7 8\n```\n\n## Sample Output 2\n\n```\nimpossible\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2022_G", "prompt": "### Problem G: Parmigiana With Seafood\n\n**SWERC 2022-2023**\n\n#### Time Limit:\n2.0S\n\n#### Memory Limit:\n2048MB\n\nThe \"Parmigiana di melanzane\" is a typical Italian dish. Alessandro and Bianca have very different tastes when it comes to it: Alessandro loves to eat Parmigiana with seafood, but Bianca thinks it is an atrocity! To decide which ingredients to include in the dish they prepare, they play the following game.\n\nThere are $n$ possible ingredients, labeled from 1 to $n$. The higher the label, the closer the ingredient is to being seafood. The ingredients are connected by $n - 1$ edges, in such a way as to form a tree. Alessandro and Bianca take turns, with Alessandro going first. They alternately choose a terminal ingredient $a$, that is an ingredient currently connected to at most one other ingredient, and remove it from the tree. If the terminal ingredient was chosen by Alessandro, it goes in the recipe; if it was chosen by Bianca, it is discarded.\n\nThe taste of the Parmigiana is measured as the maximum label of an ingredient in the recipe. Alessandro wants to maximize the taste, while Bianca wants to minimize the taste. If both play optimally, what is the taste of the Parmigiana?\n\n#### Input\nThe first line contains an integer $n$ ($2 \\leq n \\leq 100000$) \u2014 the number of ingredients.\n\nEach of the following $n - 1$ lines contain two integers $u_i$ and $v_i$ ($1 \\leq u_i, v_i \\leq n$, $u_i \\neq v_i$) \u2014 the ingredients that the $i$-th edge connects.\n\nIt is guaranteed that the edges form a tree (i.e., any pair of ingredients is connected by the edges, possibly indirectly).\n\n#### Output\nPrint the value of the taste if both Alessandro and Bianca play optimally.\n\n#### Sample Inputs and Outputs\n\n**Sample Input 1**\n```\n4\n1 2\n1 3\n1 4\n```\n\n**Sample Output 1**\n```\n4\n```\n\n**Explanation of Sample 1**\nAlessandro can choose terminal ingredient 4 in the first turn. This ingredient is added to the recipe. Since 4 is the maximum label of an ingredient, the taste is 4 regardless of the choices that follow.\n\n**Sample Input 2**\n```\n5\n1 5\n5 3\n3 4\n4 2\n```\n\n**Sample Output 2**\n```\n3\n```\n\n**Explanation of Sample 2**\nBianca can make sure that neither ingredient 4 nor 5 are included in the recipe, in which case Alessandro can include 3. Thus, the taste is 3.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2022_A", "prompt": "# Problem A: Walking Boy\n## SWERC 2022-2023\n\n## Problem Statement\n\nOne of the SWERC judges has a dog named Boy. Besides being a good competitive programmer, Boy loves fresh air, so she wants to be walked at least twice a day. Walking Boy requires 120 consecutive minutes. Two walks cannot overlap, but one can start as soon as the previous one has finished.\n\nToday, the judge sent $n$ messages to the SWERC Discord server. The $i$-th message was sent $a_i$ minutes after midnight. You know that, when walking Boy, the judge does not send any messages, but he can send a message right before or right after a walk. Is it possible that the judge walked Boy at least twice today?\n\nNote that a day has 1440 minutes, and a walk is considered to happen today if it starts at a minute $s \\geq 0$ and ends right before a minute $e \\leq 1440$. In that case, it must hold that $e - s = 120$ and, for every $i = 1, 2, \\ldots, n$, either $a_i \\leq s$ or $a_i \\geq e$.\n\n## Input\n\nEach test contains multiple test cases. The first line contains an integer $t$ ($1 \\leq t \\leq 100$) - the number of test cases. The descriptions of the $t$ test cases follow.\n\nThe first line of each test case contains an integer $n$ ($1 \\leq n \\leq 100$) \u2014 the number of messages sent by the judge.\n\nThe second line of each test case contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($0 \\leq a_1 < a_2 < \\ldots < a_n < 1440$) - the times at which the messages have been sent (in minutes elapsed from midnight).\n\n## Output\n\nFor each test case, output one line containing `YES` if it is possible that Boy has been walked at least twice, and `NO` otherwise.\n\n## Sample\n\n### Sample Input 1\n\n```\n6\n14\n100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400\n12\n100 200 300 400 600 700 800 900 1100 1200 1300 1400\n13\n100 200 300 400 500 600 700 800 900 1100 1200 1300 1400\n13\n101 189 272 356 463 563 659 739 979 1071 1170 1274 1358\n1\n42\n5\n0 1 2 3 4\n```\n\n### Sample Output 1\n\n```\nNO\nYES\nNO\nYES\nYES\nYES\n```\n\n### Explanation of Sample 1\n\n- In the first test case, the judge has sent a message at each time multiple of 100 (excluding 0). It is impossible that he has walked Boy even once.\n- In the second test case, the times are the same as above, but 500 and 1000 are missing. The judge could have walked Boy, for instance, during the time intervals [440, 560] and [980, 1100].\n- In the third test case, the times are the same as in the first test case, but 1000 is missing. The judge could have walked Boy at most once.\n- In the fourth test case, Boy could have been walked during the time intervals [739, 859] and [859, 979].\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "nwerc2024_E", "prompt": "# Problem Statement\n\n**Create a new word from an existing word $s$ ($|s| \\leq 10^5$) by applying the following method up to $10^{18}$ times:**\n\n- Take every second letter of $s+s$, starting with the first letter.\n- For example, applying this method to the word \"etymology\" once would result in \"eyooytmlg\".\n\n**Eelco has recently started to gain interest in the field that studies the origin of words: etymology.** He especially likes how words can evolve in many different ways: pronunciation changes over time, words are borrowed from different languages, and the meaning of words can change based on culture. Eelco is eager to attend the Networking With Etymologists: Revolutionary Conference for the first time ever. To make a good first impression, he is going to present a completely new method to make new words from existing words.\n\n**To make a new word from an existing word $s$, Eelco proposes to take every second letter of $s+s$, starting with the first letter.** For example, applying this method to the word \"etymology\" would result in \"eyooytmlg\". Of course, to design even more words, this process can be repeated many times. Eelco would like to prepare a list of new words to present at the conference, so he writes a program that applies his method some predetermined number of times.\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $k$ ($1 \\leq n \\leq 10^5$, $1 \\leq k \\leq 10^{18}$), the length of the original word and the number of times to apply the method.\n- One line with a string $s$ of length $n$, only consisting of English lowercase letters (a-z), the original word.\n\n## Output\n\nOutput the resulting word after applying the method to the original word $k$ times.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n9 1\netymology\n```\n\n### Sample Output 1\n```\neyooytmlg\n```\n\n### Sample Input 2\n```\n4 1\nword\n```\n\n### Sample Output 2\n```\nwrwr\n```\n\n### Sample Input 3\n```\n5 1000000000000000000\ndelft\n```\n\n### Sample Output 3\n```\ndelft\n```\n\n### Sample Input 4\n```\n5 5\neceol\n```\n\n### Sample Output 4\n```\neelco\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2022_D", "prompt": "# Problem D: Crossing the Railways\n## SWERC 2022-2023\n\n## Problem Statement\n\nIsona is in a train station. This station has two platforms, and between them are $m$ parallel railways that can be viewed as infinite straight lines. Each railway is identified with an integer from 1 to $m$, with railway 1 being the closest to the first platform and railway $m$ being the farthest. There is a 1 meter distance between consecutive railways, as well as between each platform and its closest railway.\n\nIsona is standing on the inner border of the first platform, and she realizes that she forgot to validate her ticket! There is a validating machine on the second platform, exactly opposite her current position (thus, the distance between Isona and the validating machine is $m + 1$ meters). There are only $s$ seconds left to validate the ticket, and the bridge designated to cross the railways is too far from the validating machine. Therefore, Isona (who is very brave and a little bit careless) will cross the railways running in a straight line perpendicular to the railways themselves. Isona can only run forward (not backward) and she can stay still. When she runs at maximum speed, she needs $v$ seconds to traverse 1 meter. She can run at any speed less than or equal to her maximum speed.\n\nThere is only one problem: $n$ trains are programmed to transit through the railways. The $i$-th train will use the railway $r_i$. It will start crossing the straight line between Isona and the validating machine at $a_i$ seconds from now and it will end at $b_i$ seconds from now. Of course, Isona cannot cross a railway when a train is passing. Formally, for every $i = 1, 2, \\ldots, n$, Isona is not allowed to be on railway $r_i$ at any time $t$ with $a_i < t < b_i$ (but she is allowed to cross at times $a_i$ or $b_i$).\n\nIsona is a really good runner, but she gets tired every time she has to change her running speed. What is the minimum number of speed changes she has to perform to get to the validating machine on the other platform within $s$ seconds from now? Note that at the beginning Isona is not running. She can start to run anytime. The instant she starts to run (i.e., her speed becomes positive) is not counted as a speed change.\n\n## Input\n\nThe first line of the input contains four integers $n$, $m$, $s$, $u$ ($1 \\leq n \\leq 500$, $1 \\leq m \\leq 10$, $1 \\leq s, u \\leq 100$) \u2014 the number of trains, the number of railways, the maximum time in seconds Isona can spend crossing the railways, and the number of seconds she needs to traverse 1 meter at maximum speed.\n\nEach of the next $n$ lines contains three integers $a_i$, $b_i$, $r_i$ ($1 \\leq a_i < b_i \\leq 100$, $1 \\leq r_i \\leq m$) \u2014 the start and end times of the $i$-th train crossing the straight line between Isona and the validating machine, and the railway it will be using.\n\nIt is guaranteed that, for any two trains $i$ and $j$ that go through the same railway (i.e., $r_i = r_j$), there is at least 1 second between them (that is, either $a_j \\geq b_i + 1$ or $a_i \\geq b_j + 1$).\n\n## Output\n\nPrint the minimum number of speed changes Isona has to perform to get to the validating machine in time. If this is impossible, print -1.\n\n## Samples\n\n### Sample Input 1\n```\n4 3 5 1\n1 2 1\n3 4 1\n2 3 2\n3 4 3\n```\n\n### Sample Output 1\n```\n0\n```\n\n### Explanation of Sample 1\nIf Isona starts running at time $t = 0$ at maximum speed (1 m/s), she will cross each railway just when a train is about to traverse it, and she will arrive at the other platform at time 4 = $s - 1$ without changing speed.\n\n### Sample Input 2\n```\n3 3 12 2\n2 10 1\n1 6 2\n8 12 3\n```\n\n### Sample Output 2\n```\n2\n```\n\n### Explanation of Sample 2\nA possible solution with 2 speed changes is the following: for the first 2 seconds Isona goes at maximum speed (0.5 m/s), then she slows down to 0.25 m/s for 4 seconds until she reaches the second railway. At that point, she goes at maximum speed again until she reaches the other platform.\n\n### Sample Input 3\n```\n8 4 13 2\n1 4 1\n5 13 1\n1 5 2\n6 13 2\n1 9 3\n10 13 3\n1 10 4\n11 13 4\n```\n\n### Sample Output 3\n```\n2\n```\n\n### Explanation of Sample 3\nIsona can wait 2 seconds before starting running. She then runs for 5 seconds at maximum speed (0.5 m/s). After that, she waits for 1 second not running (or running at 0 m/s), and finally she runs again at maximum speed for the last 5 seconds. Overall, she changes speed twice.\n\n### Sample Input 4\n```\n1 1 2 2\n1 2 1\n```\n\n### Sample Output 4\n```\n-1\n```\n\n### Explanation of Sample 4\nIt is impossible for Isona to cross the railway within the given time constraints because the train is crossing the only railway for the entire duration of the available time.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2022_A", "prompt": "# Problem: Alternating Algorithm\n\nIn recent years, CPU manufacturers have found it increasingly difficult to keep up with Moore's law of doubling the number of transistors on integrated circuit chips every two years. To address this, manufacturers have instead started creating CPUs with an increasingly higher number of cores. In fact, you just purchased a CPU with a staggering $n$ number of cores, no less!\n\nIncidentally, you also have an array of $n+1$ integers, $a_0, a_1, \\ldots, a_n$, that you need to sort. To make good use of the large number of cores on your CPU, you have devised a parallel sorting algorithm in which there is a dedicated core for comparing each adjacent pair of integers. As long as the array is not sorted in non-decreasing order, the algorithm proceeds in rounds that alternate between:\n\n- **Odd rounds (starting with the first):** The first core compares $a_0$ and $a_1$, the third core compares $a_2$ and $a_3$, the fifth core compares $a_4$ and $a_5$, and so on. If a pair of compared elements are out of order, the corresponding core will swap their positions. If $n$ is even, $a_n$ will be left untouched.\n- **Even rounds:** The second core compares $a_1$ and $a_2$, the fourth core compares $a_3$ and $a_4$, the sixth core compares $a_5$ and $a_6$, and so on. If a pair of compared elements are out of order, the corresponding core will swap their positions. If $n$ is odd, $a_n$ will be left untouched, and $a_0$ will be left untouched no matter what the parity of $n$ is.\n\nNote that in both types of rounds some cores may be idle.\n\nBefore implementing this algorithm, you have decided to do some analysis. In particular, you noticed that the time complexity of the algorithm does not depend on the value of $n$, but rather it depends on the number of rounds that the algorithm runs. Given the initial contents of the array, determine the number of rounds that the parallel sorting algorithm runs before the array becomes sorted.\n\n## Input\nThe input consists of:\n- One line with an integer $n$ ($1 \\leq n \\leq 4 \\cdot 10^5$), the number of cores and the size of the array.\n- One line with $n+1$ integers $a_0, a_1, \\ldots, a_n$ ($0 \\leq a_i \\leq 10^9$ for each $i$), the initial contents of the array.\n\n## Output\nOutput the number of rounds that the parallel sorting algorithm runs before the array becomes sorted in non-decreasing order.\n\n## Sample Input/Output\n\n### Sample Input 1\n```\n3\n8 13 4 10\n```\n\n### Sample Output 1\n```\n3\n```\n\n### Sample Input 2\n```\n5\n13 12 14 10 14 12\n```\n\n### Sample Output 2\n```\n3\n```\n\n### Sample Input 3\n```\n2\n2 2 1\n```\n\n### Sample Output 3\n```\n3\n```\n\nIllustration of Sample Input 1, where the array is sorted after three rounds. (Note: This illustration is not included in the markdown output.)\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2024_B", "prompt": "# Problem Statement\n\nYou are given an undirected graph with $n$ vertices and $m$ edges. Each vertex $v$ has a number $a_v$ written on it. This number is either $0$ or $1$.\n\nA *walk* is a sequence $v_1 v_2 \\dots v_k$ of vertices in the graph such that any two consecutive vertices are connected by an edge. We call a binary sequence $s = s_1 s_2 \\dots s_k$ *walkable* if there is a walk $v_1 v_2 \\dots v_k$ in the graph that satisfies $a_{v_1} a_{v_2} \\dots a_{v_k} = s$.\n\nIn other words, a binary sequence is walkable if it is possible to obtain $s$ by walking in the graph and writing down the binary numbers in the order that they are visited. An example is visualized in the following figure.\n\nYour task is to find the length of a shortest binary sequence that is not walkable.\n\n## Input\nThe input consists of:\n- One line with two integers $n$ and $m$ ($1 \\leq n \\leq 3 \\cdot 10^5$, $0 \\leq m \\leq 3 \\cdot 10^5$), the number of vertices and the number of edges.\n- One line with $n$ integers $a_1, \\dots, a_n$ ($a_v \\in \\{0, 1\\}$ for each $v$), where $a_v$ is the number written on vertex $v$.\n- $m$ lines, each with two integers $u$ and $v$ ($1 \\leq u, v \\leq n$, $u \\neq v$), denoting that the vertices $u$ and $v$ are connected by an edge. It is guaranteed that every pair of vertices is connected by at most one edge.\n\n## Output\nIf every binary sequence is walkable, output \"infinity\". Otherwise, output the length of a shortest binary sequence that is not walkable.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n4 4\n0 0 1 1\n1 2\n1 3\n2 3\n3 4\n```\n\n### Sample Output 1\n```\n4\n```\n\n### Sample Input 2\n```\n6 7\n0 0 1 1 0 1\n1 2\n3 1\n1 4\n2 3\n4 2\n3 4\n5 6\n```\n\n### Sample Output 2\n```\ninfinity\n```\n\n### Sample Input 3\n```\n1 0\n0\n```\n\n### Sample Output 3\n```\n1\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2024_M", "prompt": "# Problem: M: Ook? Ook!\n\nWhen Arthur Evans excavated Knossos, along with the famous Linear A and Linear B tablets, he also found evidence of a much earlier language, the Ook language, whose only letters are O and K.\n\nAs he was deciphering this language, he telegraphed to London lists of Ook words that he was gathering. At the time, the Morse language was different from the one you know, and letters had Pseudo-Morse translations different from the ones they have today. Unfortunately, he was so excited by this discovery that he forgot to include pauses between letters when telegraphing.\n\nAs the operator in London, you have received this message from sir Arthur: `.-.-.-`, and through a side-channel, you have learnt this sequence can represent two different Ook words: OK and KO. You have also received the sequence `.-.-.-.-.-`, and have learnt it means OOK.\n\nYou need to ask sir Arthur to translate a few more Ook words for you into English. Can your program send them as Pseudo-Morse over the wire? You are as excited as sir Arthur, so you forget pauses in what you send as well.\n\n## Input\n\nThe input consists of a single line. This line contains a single Ook word $W$, which only contains letters `O` and `K`, followed by an end-of-line character.\n\n## Output\n\nThe output should contain a single string, the translation of $W$ in the pseudo-Morse language, without pauses.\n\n## Limits\n\n- $1 \\leq |W| \\leq 1\\,000$.\n\n## Sample Input/Output\n\n### Sample 1\n```\nOK\n```\n```\n.-.-.-\n```\n\n### Sample 2\n```\nKO\n```\n```\n.-.-.-\n```\n\n### Sample 3\n```\nOOK\n```\n```\n.-.-.-.-.-\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "nwerc2024_H", "prompt": "# Problem Statement\n\nFor security reasons, TU Delft is going to place locks with numeric keypads on the doors of a large number of rooms. Each room will have its own pass code. The task of setting up the server on which all codes will be stored is given to Harry and Sharon.\n\nHaving paid attention in cybersecurity class, they know that the codes should be passed through a **hash function**, preferably multiple times, before storing.\n\nSharon came up with the nifty idea of letting the room number be the number of times the code is passed through the hash function. That way, even if two rooms happen to have the same pass code, they will not (necessarily) end up with the same hash value. However, they find that for some combinations of room number and code, the hash value happens to be the same as the original code, presenting a security risk.\n\nNot to be outdone by Sharon, Harry came up with an idea of his own: to switch the roles, that is, let the code be the number of times the hash function is applied to the room number. In other words, if $c$ is the code and $r$ is the room number, the hash value will be $f^c(r) = \\underbrace{f(\\cdots f(}_{c~\\text{times}}r)\\cdots)$.\n\nAfter some thought, Sharon claimed that, regardless of what the function $f$ is, it would always still be the case for some room numbers and codes that the hash value is the same as the code; that is, that $f^c(r) = c$. In fact, Sharon thinks it would not be too difficult to find two such numbers, even without knowing the full details of $f$.\n\nThis dismissive statement made Harry angry, who believed that Sharon was just jealous of his idea. After a big argument that led nowhere, Harry decided to make Sharon prove her claim: he has written a program that, upon sending it a query, will return the hash value $f^c(r)$ for the $c$ and $r$ given in the query, using a secret hash function $f$ he has chosen. The hash function accepts any $r$ in $\\{1, \\dots, n\\}$, where $n$ is given, and returns a value in the same range. The value of $c$ should also be in the same range. The challenge for Sharon is to find $c$ and $r$ such that $f^c(r) = c$, using a limited number of queries.\n\nYou know that Sharon is right about her claim and decide to help her.\n\n## Interaction\n\nThis is an interactive problem. Your submission will be run against an interactor, which reads the standard output of your submission and writes to the standard input of your submission. This interaction needs to follow a specific protocol:\n\n1. The interactor first sends one line with an integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), indicating that the domain of the hidden function $f$ is $\\{1, \\dots, n\\}$.\n2. Then, your program should make at most 1000 queries to find the answer.\n - Each query is made by printing one line of the form `? $c$ $r$` ($1 \\leq c, r \\leq n$).\n - The interactor will respond with an integer $h$ ($1 \\leq h \\leq n$), the value of $f^c(r)$.\n3. When you have determined some values of $c$ and $r$ such that $f^c(r) = c$, print one line of the form `! $c$ $r$` ($1 \\leq c, r \\leq n$), after which the interaction will stop.\n - Printing the answer does not count as a query.\n4. If there are multiple valid solutions, you may output any one of them.\n5. The interactor is not adaptive: the hidden function $f$ is fixed up front, and does not depend on your queries.\n6. Make sure you flush the buffer after each write.\n7. Using more than 1000 queries will result in a wrong answer.\n\n## Sample Input and Output\n\n### Sample Input 1\n```\n6\n4 3 5 2 4 6\n```\n\n### Sample Output 1\n```\n! 4 1\n```\n\n### Sample Input 2\n```\n4\n2 4 2 2\n```\n\n### Sample Output 2\n```\n! 2 1\n```\n\nIn the first sample case, the value of $n$ is 6, and the hidden function is given by $f(1) = 4$, $f(2) = 3$, $f(3) = 5$, $f(4) = 2$, $f(5) = 4$, and $f(6) = 6$.\n\nIn the second sample case, the value of $n$ is 4, and the hidden function is given by $f(1) = 2$, $f(2) = 4$, $f(3) = 2$, and $f(4) = 2$.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2023_K", "prompt": "# Problem: Klompendans\n\nIn traditional Dutch clog dancing, you as the dancer need to follow a very specific sequence of movements. The dance takes place on a square grid of square tiles, and at the start of the dance you stand on the top left corner tile of the grid. You then alternate between two types of dance move, moving from tile to tile in the grid for as long as you want. Your first move may be of either kind, but after that you need to strictly alternate between the two kinds of moves.\n\nBoth moves are similar to knight moves in chess:\n- In the first type of move, you go from your current square to a square that is $a$ tiles away along one axis of the grid and $b$ tiles away along the other axis.\n- Similarly, in the second type of move, you need to move $c$ and $d$ tiles along the respective axes.\nAs you can freely swap the two axes and choose the movement direction along each axis, there can be up to 8 ways of performing a given type of move.\n\nStarting on the top left corner tile, how many different tiles could you reach while doing a clog dance? It is not allowed to step outside of the grid and you do not count tiles that you are simply stepping over while doing a move. Note that you need to count all tiles that can be reached during some performance of the dance, but not necessarily during the same one.\n\n## Input\nThe input consists of:\n- One line with an integer $n$ ($3 \\leq n \\leq 500$), the side length of the square.\n- One line with two integers $a$ and $b$ ($1 \\leq a, b < n$), describing the first dance move.\n- One line with two integers $c$ and $d$ ($1 \\leq c, d < n$), describing the second dance move.\n\n## Output\nOutput the number of tiles you can reach using these dance moves.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n3\n2 1\n2 2\n```\n\n### Sample Output 1\n```\n6\n```\n\n### Sample Input 2\n```\n8\n1 2\n1 2\n```\n\n### Sample Output 2\n```\n64\n```\n\n### Sample Input 3\n```\n4\n1 2\n2 3\n```\n\n### Sample Output 3\n```\n13\n```\n\n### Sample Input 4\n```\n5\n1 2\n2 3\n```\n\n### Sample Output 4\n```\n25\n```\n\n### Sample Input 5\n```\n10\n3 3\n4 4\n```\n\n### Sample Output 5\n```\n50\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2024_J", "prompt": "# Problem: J: Recovering the Tablet\n\nA long time ago, before our modern civilization arose and before any of you were born, was the year -1966 (3961 Before SWERC). During this dark period, there were no streaming services nor any programming contests. Thus, to entertain themselves, humans had rudimentary games that they played on clay tablets.\n\nThis year, a mysterious game was created: Kakurus. We know close to nothing about Kakurus (the Internet Archive had not yet been created), except for a few rules described on an artifact you have discovered:\n1. The game is played on an $M \\times N$ grid;\n2. Each cell is either black or white;\n3. White cells are originally empty, but you will have to put an integer from $1$ to $9$ (inclusive) inside each white cell;\n4. **Horizontal constraint**: A black cell can contain an integer corresponding to the sum of the consecutive white cells to its right (until the first black cell or the limit of the grid);\n5. **Vertical constraint**: A black cell can contain an integer corresponding to the sum of the consecutive white cells below it (until the first black cell or the limit of the grid).\n\nNote that the last two rules are independent from each other: a black cell can have $0$, $1$ or $2$ integers inside it. **Note also that no constraint is placed on repetitions of numbers.** Finally, since we want this problem to be interesting, every white cell is covered by exactly one vertical constraint and by exactly one horizontal constraint.\n\nAt the bottom of your artifact lies a grid of Kakurus. It is already filled, but not necessarily with a correct solution -- probably a deterioration due to the age of this antique artifact. Can you find a valid solution that is as close as possible to this proposed solution?\n\nIf the number you write on a white cell is $X$ and the value of the proposed solution for this cell is $T$, then the closeness score is $|X-T|$. The final closeness score of the grid is the sum of all closeness scores of the cells. Your objective is to find the minimum closeness score that can be achieved.\n\n## Input\n\nThe first line of the input consists of three integers, $M$, $N$ and $S$, respectively the number of lines and columns of this grid, and the number of sum constraints.\n\nThen, $M$ lines follow. The $i$th of these lines only contains digits from $0$ to $9$. The $j$th character equals $0$ if and only if the cell at line $i$ and column $j$ ($1 \\leq i \\leq M$, $1 \\leq j \\leq N$) is black, and otherwise is equal to the value of this cell (which is thus white) in the proposed solution.\n\nThen $S$ lines follow. Each line is of the form $c\\ i\\ j\\ s$ where $c$ is equal to either `H` or `V`, $1 \\leq i \\leq M$, $1 \\leq j \\leq N$ and $s$ is an integer between 1 and 135, inclusive. The sum of the consecutive white cells at the right of (when $c=$ `H`) or below (when $c=$ `V`) the cell at line $i$ and column $j$ must be equal to $s$ in your solution.\n\nIt is guaranteed that every white cell is covered by exactly one vertical and one horizontal constraint.\n\n## Output\n\nIf the grid has no solution, you must output `IMPOSSIBLE`.\nOtherwise, your output should consist of the minimum closeness score that can be achieved.\n\n## Limits\n\n- $1 \\leq M \\leq 16$;\n- $1 \\leq N \\leq 16$;\n- $0 \\leq S \\leq 2 \\times M \\times N$.\n\n## Sample Input 1\n\n```\n4 4 7\n0000\n0032\n0233\n0204\nH 3 1 9\nV 1 3 6\nH 2 2 5\nV 2 2 5\nV 1 4 9\nH 4 1 2\nH 4 3 4\n```\n\n## Sample Output 1\n\n```\n1\n```\n\n## Sample Input 2\n\n```\n3 4 5\n0000\n0012\n0345\nH 2 2 3\nH 3 1 12\nV 2 2 3\nV 1 3 5\nV 1 4 6\n```\n\n## Sample Output 2\n\n```\nIMPOSSIBLE\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2024_G", "prompt": "# Problem Statement\n\nA sliding puzzle consists of square tiles on a rectangular grid. Exactly one of the grid positions is empty, so that you can move the tile above, below, to its left, or to its right into the empty square and back.\n\nEach tile is labelled with a unique number, as shown in Figure 1. To solve a sliding puzzle, you need to find a sequence of moves that puts the tile numbers in ascending order, from left to right and top to bottom, such that the empty square ends up at the bottom right position in the grid, as shown in Figure 2. Such a sequence of moves does not exist for all sliding puzzles.\n\nWhile cleaning out your garage, you grapple with the garage goblins over a glowing box full of goodies. They offer a gamble: the box is yours if you can solve all their sliding puzzles. You accept to give it a go, only to find out that the garage goblins have glued some tiles in place!\n\nHowever, all sliding puzzles share the following properties:\n- The empty square is at the bottom right position.\n- Every glued tile is in its correct position.\n- For each tile that can move, there is a sequence of moves that leaves the empty square in its position instead.\n- From any glued tile, there is a path to the border of the sliding puzzle across glued tiles only, when stepping to the tile above, below, to the left, or to the right at each step. That is, no glued tiles are encircled by tiles that can move.\n\nDetermine whether it is possible to solve a given sliding puzzle.\n\n## Input\nThe input consists of:\n- One line with two integers $h$ and $w$ ($1 \\le h, w \\le 500$), the height and width of the sliding puzzle's grid.\n- $h$ lines with $w$ characters, each character being either `\\texttt{.}` or `\\texttt{\\#}`. The bottom right character, at the position of the empty square, is `\\texttt{.}`. Otherwise, `\\texttt{.}` denotes a tile that can move, and `\\texttt{\\#}` denotes a glued tile.\n- $h$ lines with $w$ integers $a_{i,j}$ ($1 \\le i \\le h$, $1 \\le j \\le w$, $0 \\le a_{i,j} \\le h \\cdot w - 1$). The bottom right integer is $a_{h,w} = 0$, representing the empty square. Otherwise, $a_{i,j}$ is the label on the tile at position $(i,j)$.\n\nThe set of all $a_{i,j}$ ($1 \\le i \\le h, 1 \\le j \\le w$) contains each of the numbers $0, 1, \\dots, h \\cdot w - 1$ once.\n\n## Output\nOutput `possible` if the sliding puzzle can be solved, or `impossible` if not.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n3 4\n....\n....\n....\n10 8 2 3\n6 7 5 9\n11 1 4 0\n```\n\n### Sample Output 1\n```\npossible\n```\n\n### Sample Input 2\n```\n2 4\n....\n....\n2 1 3 4\n5 6 7 0\n```\n\n### Sample Output 2\n```\nimpossible\n```\n\n### Sample Input 3\n```\n3 4\n..#.\n....\n#...\n5 1 3 4\n2 6 7 8\n9 10 11 0\n```\n\n### Sample Output 3\n```\npossible\n```\n\n### Sample Input 4\n```\n3 4\n..#.\n....\n#...\n7 1 3 4\n5 6 2 8\n9 10 11 0\n```\n\n### Sample Output 4\n```\nimpossible\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2024_D", "prompt": "# Problem: Temple Architecture\n\nYou are excavating what remains of a very old Indian temple. The architecture of the temple is very curious: you found a line of $N$ towers of different heights (no two towers have the same height), all spaced by one meter (the radius of each tower is supposed to be negligible).\n\nDuring the excavations, you find something which might explain this curious architecture: the tomb of the architect. You find the following epitaph on the tomb:\n\n> O thou temple-builder, \n> To achieve perfection, visit each tower; \n> For each, compute the distance to the closest tower that is taller; \n> Add every such distance. \n> If thou can follow this guidance, \n> Enlightened shalt thou be by this result, \n> And great in thy temple shall be the cult.\n\nThe closest taller tower can be on the left or on the right. For the tallest tower, this distance is undefined and should not be considered in the final sum.\n\nYou wonder how to compute this sum, this \"enlightenment score\" of the temple.\n\nYou are given a positive integer $N$ corresponding to the number of towers, and an array $H$ of $N$ distinct non-negative integers corresponding to the heights of the towers. $H_0$ is the height of the leftmost tower, $H_1$ is the height of the tower to the right of $H_0$, and so on. Finally, $H_{N-1}$ is the height of the rightmost tower. Observe that the distance between any two towers, in meters, is the absolute value of the difference of their respective indices in the array $H$.\n\nLet $p$ denote the index of the tallest tower in $H$ and define, for every $i \\neq p$,\n$$\nd(i) = \\min\\{ |i - j| \\text{ for every } j \\text{ such that } H_j > H_i \\}.\n$$\nNote that $d(p)$ is not defined. The \"enlightenment score\" of the temple is then given by\n$$\n\\sum_{i=0, i \\neq p}^{N-1} d(i).\n$$\n\n## Input\n\nThe first line contains the integer $N$.\nThe second line contains the list of elements $H_0, \\dots, H_{N-1}$ of the array $H$ of heights, separated by spaces.\n\n## Output\n\nThe output should contain one line with the enlightenment score of the temple.\n\n## Limits\n\n- $2 \\leq N \\leq 200,000$\n- $0 \\leq H_i \\leq 10^{18}$, for $i = 0, \\dots, N-1$\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n5\n7 3 2 100 1\n```\n\n### Sample Output 1\n```\n6\n```\n\n### Explanation for Sample 1\n- Distance of the 1st tower to the closest taller tower (4th tower): 3\n- Distance of the 2nd tower to the closest taller tower (1st tower): 1\n- Distance of the 3rd tower to the closest taller tower (2nd or 4th tower): 1\n- Distance of the 5th tower to the closest taller tower (4th tower): 1\nThe tallest tower (the 4th) is not considered. Hence, $3 + 1 + 1 + 1 = 6$.\n\n### Sample Input 2\n```\n8\n45 13 18 10 8 56 17 19\n```\n\n### Sample Output 2\n```\n13\n```\n\n### Explanation for Sample 2\n- Distance of the 1st tower to the closest taller tower (6th tower): 5\n- Distance of the 2nd tower to the closest taller tower (1st or 3rd tower): 1\n- Distance of the 3rd tower to the closest taller tower (1st tower): 2\n- Distance of the 4th tower to the closest taller tower (3rd tower): 1\n- Distance of the 5th tower to the closest taller tower (4th or 6th tower): 1\n- Distance of the 7th tower to the closest taller tower (6th or 8th tower): 1\n- Distance of the 8th tower to the closest taller tower (6th tower): 2\nThe tallest tower (the 6th) is not considered. Hence, $5 + 1 + 2 + 1 + 1 + 1 + 2 = 13$.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "nwerc2024_F", "prompt": "# Problem Statement\n\n## Bill's Champagne Fountain\n\nLast week, Bill filled a champagne fountain for the first time. Delighted by the champagne pouring from one glass into another, he decided that he wants to organize an even bigger champagne fountain for the next World Finals. He already ordered $n$ glass bowls with different capacities to stack on top of each other to form a huge glass fountain. However, he is still unsure how to pour the champagne into the fountain. One bottle will not be enough and just pouring from the top might not fill every bowl. Bill wants to try out different ways to fill the fountain, but wasting any champagne would be such a shame.\n\nThis is your time to shine! You are tasked with writing a program that simulates the process of pouring champagne into a given fountain. If a bowl in some level is already filled up, then the champagne spills over to the first level below it with larger capacity. If the next larger level is also filled, the champagne spills over even further until eventually seeping into the ground, wasting the good champagne. Additionally, Bill also wants to know at some times during the simulation process how much champagne currently is in a certain level.\n\n## Input\n\nThe input consists of:\n- One line with two integers $n$ and $q$ ($1 \\leq n, q \\leq 3 \\cdot 10^5$), the number of levels and the number of queries.\n- One line with $n$ distinct integers $c$ ($1 \\leq c \\leq 10^9$), the capacity of each level in litres. The levels are given in order from top to bottom.\n- $q$ lines, each describing a query. The first symbol $t$ ($t \\in \\{\\text{`\\texttt{+}'}, \\text{`\\texttt{?}'}\\}$) describes the type of the query. The format of the rest of the line depends on $t$:\n - $t = \\text{`\\texttt{+}'}$: Two integers $\\ell$ and $x$ follow ($1 \\leq \\ell \\leq n$, $1 \\leq x \\leq 10^9$), the level into which Bill wants to pour $x$ litres of champagne.\n - $t = \\text{`\\texttt{?}'}$: One integer $\\ell$ follows ($1 \\leq \\ell \\leq n$), the level for which Bill requests the current amount of champagne in litres.\n\nIt is guaranteed that there is at least one query of type `\\texttt{?}'.\n\n## Output\n\nFor each query of type `\\texttt{?}', output the amount of champagne in the requested level in litres.\n\n## Sample Input 1\n\n```\n4 4\n1 2 3 4\n+ 1 6\n? 4\n+ 1 6\n? 4\n```\n\n## Sample Output 1\n\n```\n0\n4\n```\n\n## Sample Input 2\n\n```\n4 8\n2 4 3 5\n+ 1 4\n? 2\n+ 2 3\n? 4\n+ 3 4\n? 4\n+ 2 10\n? 4\n```\n\n## Sample Output 2\n\n```\n2\n1\n2\n5\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2022_B", "prompt": "# Problem: Bottle Flip\n\nIt marks the year 2022 where the *bottle flip challenge* finally reached the last people on earth; the NWERC Jury. As you may know, the objective of the challenge is to flip a bottle of water $360^\\circ$ through the air and hope that it lands standing upright. Figure 1 demonstrates a successful bottle flip.\n\nAfter many failed attempts, we noticed that this task gets significantly easier if the bottle is filled with just the right amount of water. The simple reason for this is that the amount of water affects the centre of mass of our bottle as it is about to land. For the sake of completeness, we define the centre of mass as the unique point at which the whole mass of the bottle could be concentrated without changing the bottle's reaction to gravity, regardless of the orientation of the bottle. Note that we implicitly assume that the water will stay at the bottom of the bottle. This defines exactly what you would intuitively think of as centre of mass.\n\nA lower centre of mass makes it easier for the bottle to stay upright after it lands. Unfortunately, the optimal amount of water depends on the bottle, and we already wasted enough time on this challenge\\dots\n\nGiven that our bottle is a perfect cylinder of height $h$ and radius $r$, determine the optimal amount of water the bottle should contain so that our chances of landing a successful bottle flip are maximised. You can assume that both the water and the air contained in the bottle have uniform density, and that the weight of the bottle itself is negligible.\n\n## Input\nThe input consists of:\n- One line with four integers $h$, $r$, $d_a$, and $d_w$ ($1 \\leq h, r, d_a, d_w \\leq 1000$, $d_a < d_w$), where $h$ and $r$ are the height and radius of the bottle, and $d_a$ and $d_w$ are the densities of air and water, respectively.\n\n## Output\nOutput the height such that filling the bottle with water up to this height results in the lowest possible centre of mass while the bottle is standing upright. Your answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n22 4 1 4\n```\n\n## Sample Output 1\n```\n7.3333333333\n```\n\n## Sample Input 2\n```\n7 2 655 988\n```\n\n## Sample Output 2\n```\n3.1415941720\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "swerc2024_C", "prompt": "# Problem: Phryctoria\n\nLusius Quietus, one of the generals of Trajan, the Roman emperor, is sending signals to his army using signal towers, where the fires you lit can be seen from afar.\n\nHe wants to send the string $S$ describing military manoeuvres. However, sending long messages via fire signals is time-consuming, so Lusius decides to use a shorthand system. To abbreviate the message, Lusius can replace any substring of $S$ with the special character `*'. For example, if $S$ is ``swerc'', then some possible abbreviations are: ``swe*'', ``*sw*r*'', ``swerc'', ``*'', etc. Note that `*' can match the whole string or no character at all, so ``*sw*r*'' is indeed considered a valid abbreviation of ``swerc'' even though it's longer (Lusius is not always clever).\n\nHowever, there is a problem: the recipient might misinterpret Lusius's message. If the abbreviation he sends is also a valid abbreviation of the string $T$, which is a word used to signal retreat, it could lead to losing the war.\n\nHelp Lusius find the length of the shortest possible abbreviation of $S$ that cannot be interpreted as an abbreviation of $T$.\n\n## Input\n\nThe first line contains two integers $N$ and $M$, the lengths of the strings $S$ and $T$, respectively.\nThe second line contains the string $S$.\nThe third line contains the string $T$.\n\n## Output\n\nThe length of the shortest abbreviation of $S$.\n\n## Limits\n\n- $1 \\leq N \\leq 500$.\n- $1 \\leq M \\leq 500$.\n- $S \\neq T$.\n- $S$ and $T$ contain only lowercase English letters.\n\n## Sample Input\n\n```\n5 5\nswerc\nseerc\n```\n\n## Sample Output\n\n```\n3\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2022_J", "prompt": "# Problem Statement: Justice Served\n\nYou finally managed to produce the ultimate stroopwafel with just the right number of squares on it. After the hard work, you left the stroopwafel unattended for a few seconds to get yourself a hot drink. Full of anticipation for your delicious treat, you came back just to see that your stroopwafel was gone! Even though you were only away for a short time, someone used the opportunity to steal it.\n\nYou looked at the security recordings and saw a total of $n$ suspects that had been in the room where you left your stroopwafel, each entering and leaving the room exactly once. After seeing this, you already had a good idea who took it since your archrival Rob -- who has some background in robberies -- was among the suspects. But you wanted to give him the benefit of the doubt and decided to interrogate every suspect. Unsurprisingly, every suspect claimed their own innocence. However, some suspects also provided an alibi for other suspects. Specifically, a suspect $A$ provided an alibi for suspect $B$ if and only if $A$ was in the room for the entire duration $B$ was in the room.\n\nYou feel like a suspect is more convincing if they have an alibi provided by a suspect who is convincing themselves. Formally, a suspect without an alibi has *convincingness* $0$. Otherwise, their convincingness is $1$ more than the convincingness of the most convincing suspect who provides them with an alibi. Your task is to compute the convincingness of each suspect.\n\n## Input\n\nThe input consists of:\n- One line with a single integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), the number of suspects.\n- $n$ lines, each with two integers $a$ and $t$ ($1 \\leq a, t \\leq 10^9$), the time at which each suspect arrived and the duration they stayed.\n\nIt is guaranteed that no two suspects who arrived at the same moment stayed for the same duration.\n\n## Output\n\nOutput the convincingness of each suspect.\n\n## Sample Input 1\n\n```\n4\n2 8\n1 7\n4 5\n5 2\n```\n\n## Sample Output 1\n\n```\n0 0 1 2\n```\n\n## Sample Input 2\n\n```\n5\n2 4\n3 3\n2 2\n4 2\n4 1\n```\n\n## Sample Output 2\n\n```\n0 1 1 2 3\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2022_H", "prompt": "# High-quality Tree\n\nThe binary search tree is one of the most useful data structures in computer science. Many methods exist to keep them balanced, such as using tree rotations (like in AVL-trees) or randomness (like in treaps). One thing that these methods have in common is that they are all somewhat slow and complicated.\n\nBut this is all about to change! Rob the computer scientist has invented a new method to keep rooted binary trees balanced, that is much better than the current state-of-the-art. The main idea is to repeatedly perform an operation Rob calls a *robbery*. One robbery is to take a leaf from the tree, and remove it. By applying robberies at the right times, Rob is able to keep a tree balanced in $\\mathcal{O}(1)$ amortized time.\n\nSome people have criticized Rob's revolutionary discovery, saying that removing elements from the tree makes the algorithm incorrect. Rob does not agree that this is a big problem; if you plan to store $2 \\cdot 10^5$ numbers, you probably do not need all of them. But Rob accepts the criticism and decides to find a way to minimize the number of robberies.\n\nYou are given a rooted binary tree with $n$ vertices. The vertices are numbered from $1$ to $n$, and vertex $1$ is the root. Your task is to find the minimum number of robberies to make the tree *strongly balanced*, meaning that all of its subtrees are balanced. A rooted binary tree is called balanced if the depth of its left and right subtrees differ by at most one. Recall that a robbery is simply to take a leaf and remove it, and doing so may turn its parent vertex into a leaf. See the illustration below for an example.\n\n## Input\n\nThe input consists of:\n- One line with an integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), the number of vertices in the tree.\n- $n-1$ lines, each with two integers $u$ and $v$ ($1 \\leq u, v \\leq n$, $u \\neq v$), indicating an edge between vertices $u$ and $v$.\n\nIt is guaranteed that the given edges form a valid binary tree with vertex $1$ as the root. However, the edges can appear in any order and are not directed: $u$ can be the parent of $v$ or the other way around.\n\n## Output\n\nOutput the minimum number of leaves you need to remove to make the tree strongly balanced.\n\n## Sample Input 1\n```\n6\n1 2\n1 3\n3 4\n3 5\n5 6\n```\n\n## Sample Output 1\n```\n1\n```\n\n## Sample Input 2\n```\n12\n1 2\n2 3\n3 4\n3 5\n1 6\n6 7\n7 8\n7 9\n9 10\n6 11\n11 12\n```\n\n## Sample Output 2\n```\n3\n```\n\n### Illustration of Sample Input 2\nThe tree becomes strongly balanced after removing the three vertices marked in red ($4$, $5$, and $10$); the minimum number of vertices that need to be removed to make the tree strongly balanced.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2023_F", "prompt": "### Problem Statement: Programming-Trampoline-athlon!\n\n**Time Limit:** 1 second\n\nProgramming competitions are fun and exciting. Programming should be an Olympic sport! At least, this is what we believe. However, when we suggested this to some of our friends, they did not seem to share our excitement. So, we decided to suggest a combined sport that will be more interesting to watch: Programming-Trampoline-athlon! (We are still working on the name.)\n\nThe idea is as follows. This is a team sport, where each team comprises of 3 members. The team has at its disposal 1 hour, 1 computer, and 1 trampoline. At all times, there must be at most one team member using the computer and at least one team member jumping on the trampoline. At the beginning of the competition, the team is given 6 programming problems and 6 trampoline elements (exercises).\n\nThe team decides how to partition the trampoline elements between its members, such that each team member has to perform 2 of the given elements on the trampoline. The programming tasks are solved cooperatively by the team members, but no one member can spend more than 25 minutes on the computer in total. The scoring is comprised of two parts, which are added together:\n- The programming score ranges between 0 and 60. The team receives 10 points for every correctly solved problem.\n- The trampoline score ranges between 0 and 40. Each of the 6 trampoline elements receives a score from the judges that ranges between 0 and 10. The final trampoline execution score is determined by dropping the highest and lowest of the 6 scores, and then adding up the remaining 4 scores.\n\nBefore we pitch this new sport to the International Olympic Committee, we want everything to be ready in order to show them just how serious we are. Thus, each team should receive a medal when no more than two other teams obtained a strictly higher score. However, in order to cope with a recent shortage of medals, the jury was instructed to make sure that there would be no more than 1,000 teams deserving a medal. We ask you to write a program that determines the medallists, given the performance of the different teams.\n\n#### Input\nThe first line contains the number $N$ of competing teams. Then follow $N$ lines. Each of these lines describes a team and contains space-separated values $C$, $P$, $E_1$, $E_2$, $E_3$, $E_4$, $E_5$, $E_6$; where:\n- $C$ is a five-letter code used to identify the team.\n- $P$ is an integer specifying the number of problems the team solved.\n- $E_i$ is an integer specifying the execution score of trampoline element number $i$.\n\n#### Output\nThe output should contain $M$ lines, where $M$ is the number of medallists. Each line should represent a medallist team, by containing two space-separated values $C$ and $S$, where:\n- $C$ is the team code.\n- $S$ is the total score of the team.\n\nThe medallist teams should be listed in decreasing total score order. In case of ties, they should be listed by input order.\n\n#### Limits\n- $3 \\leq N \\leq 100,000$\n- $3 \\leq M \\leq 1,000$\n- $C$ consists of five uppercase English letters.\n- $0 \\leq P \\leq 6$\n- $0 \\leq E_i \\leq 10$ for all $1 \\leq i \\leq 6$\n- Different teams always have different team codes.\n\n### Sample Input 1\n```\n5\nEMAIL 3 5 6 7 8 9 10\nCRASH 2 7 1 8 2 8 1\nMOUSE 4 0 9 3 9 1 7\nSWERC 6 3 1 4 1 5 9\nPAINT 6 0 0 0 0 0 10\n```\n\n### Sample Output 1\n```\nSWERC 73\nEMAIL 60\nMOUSE 60\nPAINT 60\n```\n\n### Sample Input 2\n```\n4\nCRAZY 4 0 2 4 6 8 10\nJAZZY 2 9 9 9 9 9 9\nJUICY 3 2 9 10 9 10 1\nFUZZY 5 0 1 1 2 3 5\n```\n\n### Sample Output 2\n```\nCRAZY 60\nJUICY 60\nFUZZY 57\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2023_E", "prompt": "### Problem Statement\n\nParis is so crowded with tourists during the Olympic games! You want to escape the city and go on a hike on a linear trail path, going from left to right. Every kilometre on that trail, including at the start and end, is a milestone, on which is written the stone's altitude. The slope between two consecutive stones is constant, and no two stones have the same altitude.\n\nPlanning to come back with your friends, you try to identify the point of the hike at which you had the nicest view. The beauty of a point of view is defined as the distance (measured in kilometres) between your position and the leftmost position that you can see on your hike and that is at the same altitude as you are. If such a previous position fails to exist, it means that you can see the city and its smog, and the beauty of that view is zero.\n\nYou have listed the altitudes of the milestones. What is the maximal beauty on your hike?\n\n### Input\nThe input consists of two lines. The first line contains a single integer $N$, which is the number of milestones on the trail path. The second line contains $N$ space-separated integers $H_1, H_2, \\ldots, H_n$; each integer $H_k$ is the altitude (measured in metres) of the $k$-th milestone on the path.\n\n### Output\nThe output should contain a single line, consisting of a single number $S$: the best beauty score on your hike. This number is written either as an integer or as an irreducible fraction $N / D$ for which $D \\geq 2$; we recall that a fraction $N / D$ is irreducible when the greatest common divisor of $N$ and $D$ is 1.\n\n### Limits\n- $1 \\leq N \\leq 100000$;\n- $0 \\leq H_k \\leq 1000000$ for all $k \\leq N$;\n- the integers $H_k$ are pairwise distinct.\n\n### Sample Input 1\n```\n7\n0 5 3 1 4 8 2\n```\n\n### Sample Output 1\n```\n13/4\n```\n\n### Sample Input 2\n```\n5\n3 5 8 7 1\n```\n\n### Sample Output 2\n```\n0\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2023_K", "prompt": "### Problem: Team Selection\n\n**Time limit:** 6 seconds\n\nTwo team leaders get to assemble their teams by choosing team members among a set of players that are numbered from 1 to $N$. The leaders take turns, each picking the $k$th player among the remaining ones, according to their ideas of which one of the remaining players would be the best addition to their teams.\n\nGiven the choices of the two leaders (the first team leader starts first), please compute the list of players in each team.\n\n#### Input\nThe input consists of three lines:\n- The first line contains a single integer $N$.\n- The second line contains $N / 2$ space-separated integers $a_1, a_2, \\ldots, a_{N/2}$ representing the choices of the first team leader: during the $(2k - 1)$th turn, the first leader chose the $a_k$th remaining player.\n- The third line contains $N / 2$ space-separated integers $b_1, b_2, \\ldots, b_{N/2}$ representing the choices of the second team leader: during the $2k$th turn, the second leader chose the $b_k$th remaining player.\n\n#### Output\nThe output should contain two lines, each containing $N / 2$ space-separated integers:\n- The first line should contain the list $x_1, x_2, \\ldots, x_{N/2}$ of the players chosen to become members of the first team, in the order they were chosen: the player $x_k$ was chosen during the $(2k - 1)$th turn.\n- The second line should contain the list $y_1, y_2, \\ldots, y_{N/2}$ of the players chosen to become members of the second team, in the order they were chosen: the player $y_k$ was chosen during the $2k$th turn.\n\n#### Limits\n- $2 \\le N \\le 4000000$\n- $N$ is a multiple of 2\n- The choices of the team leaders are valid: at each step, they are between 1 and the number of remaining players (inclusive).\n\n#### Sample Input\n```\n4\n1 1\n2 1\n```\n\n#### Sample Output\n```\n1 2\n3 4\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2022_I", "prompt": "# Interview Question\n\n**Fizz Buzz** is a party game that is often used as a programming exercise in job interviews. In the game, there are two positive integers $a$ and $b$, and the game consists of counting up through the positive integers, replacing any number by `Fizz` if it is a multiple of $a$, by `Buzz` if it is a multiple of $b$, and by `FizzBuzz` if it is a multiple of both $a$ and $b$. The most common form of the game has $a=3$ and $b=5$, but other parameters are allowed.\n\nYour task here is to solve the reverse problem: given a transcript of part of the game (not necessarily starting at 1), find possible values of $a$ and $b$ that could have been used to generate it.\n\nFigure 1 shows some sample sequences for various values of $a$ and $b$.\n\n**Example sequences for Fizz Buzz:**\n\n- $a=3, b=5:$ `1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz`\n- $a=6, b=2:$ `1 Buzz 3 Buzz 5 FizzBuzz 7 Buzz 9 Buzz 11 FizzBuzz 13`\n- $a=4, b=4:$ `1 2 3 FizzBuzz 5 6 7 FizzBuzz 9 10 11 FizzBuzz 13 14`\n\n## Input\n\nThe input consists of:\n- One line with two integers $c$ and $d$ ($1 \\le c \\le d \\le 10^5$), indicating that your transcript starts at $c$ and ends at $d$.\n- One line with $d-c+1$ integers and strings, the contents of the transcript.\n\nIt is guaranteed that the transcript is valid for some integers $a$ and $b$ with $1 \\le a, b \\le 10^6$, according to the rules laid out above.\n\n## Output\n\nOutput two positive integers $a$ and $b$ ($1 \\le a, b \\le 10^6$) that are consistent with the given transcript.\n\nIf there are multiple valid solutions, you may output any one of them.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```\n7 11\n7 8 Fizz Buzz 11\n```\n\n### Sample Output 1\n```\n3 5\n```\n\n### Sample Input 2\n```\n49999 50002\n49999 FizzBuzz 50001 Fizz\n```\n\n### Sample Output 2\n```\n2 125\n```\n\n### Sample Input 3\n```\n8 11\nBuzz Buzz FizzBuzz Buzz\n```\n\n### Sample Output 3\n```\n10 1\n```\n\n### Sample Input 4\n```\n10 15\n10 11 12 13 14 15\n```\n\n### Sample Output 4\n```\n8 23\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "easy"} +{"id": "nwerc2022_G", "prompt": "# Problem: Going in Circles\n\nHercule Poirot, world-renowned detective, was having a lovely cup of tea in his compartment on the Disorient Express when the train conductor rushed in. \"We have lost track of the number of train carriages,\" exclaimed the conductor. You see, this was no ordinary train, and had no first or last train carriage. Instead, the train carriages were connected to form a large cycle, causing the conductor's confusion.\n\nHercule thought for a moment. \"That is most peculiar,\" he said. \"But I may be able to help you.\" He reached over and grabbed the lamp from the side table. \"You see, each train carriage has a light switch like this one. By moving between the carriages and toggling these switches, we can determine the number of train carriages.\"\n\nThe conductor was sceptical, but agreed to try it. \"We are in a hurry,\" he said, \"so please determine $n$, the number of carriages that the train consists of, in at most $3n + 500$ steps.\" Here a step counts as either moving to an adjacent carriage or toggling a light switch in the current carriage. \"The only thing I am certain of is that $n$ is at least $3$ and at most $5000$.\"\n\n## Interaction\n\nThis is an interactive problem. Your submission will be run against an interactor, which reads the standard output of your submission and writes to the standard input of your submission. This interaction needs to follow a specific protocol:\n\nThe interactor first sends an integer $s$ ($s \\in \\{0,1\\}$), the state of the light switch in Hercule's initial carriage.\n\nYour submission may then send at most $3n + 500$ steps for Hercule to carry out, each by printing one line of the form `? $a$`, where $a$ is one of the following:\n\n- `left`, to move to the adjacent train carriage in the clockwise direction,\n- `right`, to move to the adjacent train carriage in the counter-clockwise direction, or\n- `flip`, to toggle the light switch in the current train carriage.\n\nAfter every step, the interactor replies with an integer $s$ ($s \\in \\{0,1\\}$), the state of the light switch in the train carriage that Hercule is currently in, after he has carried out the requested step.\n\nWhen you have determined the number of train carriages $n$, print one line of the form `! $n$` ($3 \\leq n \\leq 5000$), after which the interaction will stop. Printing the answer does not count as a query.\n\nThe interactor is not adaptive; the initial state of the light switches is determined by the interactor before any interaction takes place. Make sure you flush the buffer after each write. Using more than $3n + 500$ queries will result in a wrong answer verdict.\n\nA testing tool is provided to help you develop your solution.\n\n## Sample Interaction\n\n### Example 1\n```\n1\n? left\n0\n? right\n1\n? flip\n0\n? left\n1\n? right\n0\n! 3\n```\n\n### Example 2\n```\n0\n? flip\n1\n? left\n1\n? left\n0\n? right\n1\n? right\n0\n! 4\n```\n\nNote: The actual number of train carriages in the test case is not known in advance, and the interactor only provides the state of the light switch in the current carriage after each step.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "swerc2022_L", "prompt": "# Problem L: Vittorio Plays with LEGO Bricks\n**SWERC 2022-2023**\n\n## Problem Statement\n\nVittorio is playing with his new LEGO Duplo bricks. All the bricks have the shape of a square cuboid with a $2 \\times 2$ square base and a height of $1$. They can be arranged in the 3D space to build structures, provided that the following rules are met:\n1. No two bricks can intersect, but they can touch on their faces.\n2. The corners of every brick must have integer coordinates (so bricks are axis-aligned) and the $z$ coordinates of all corners must be non-negative.\n3. The square bases of every brick must be parallel to the ground (i.e., the plane $z = 0$).\n4. The lower base of any brick that is not touching the ground must touch the upper base of some other brick in a region of positive area (when this happens, the two bricks stay attached to each other thanks to small studs).\n\nFor example, this is a valid structure:\n\nVittorio wants to build a structure that includes purple bricks in the following $n$ positions: $(a_i, 0, h)$, where $1 \\leq i \\leq n$ \u2014 these are the coordinates of the centers of their lower bases; note that all of these bricks have $y$ coordinate equal to $0$ and $z$ coordinate equal to $h$. Vittorio will use additional bricks of other colors to support the purple bricks. He is willing to place bricks only in positions where the center of the lower base has $y$ coordinate equal to $0$. What is the minimum number of additional bricks needed?\n\nIt can be shown that a valid construction always exists.\n\n## Input\nThe first line contains two integers $n$ and $h$ ($1 \\leq n \\leq 300$, $0 \\leq h \\leq 10^9$) \u2014 the number of purple bricks and their common $z$ coordinate.\nThe second line contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq 10^9$, $a_i < a_{i+1}$) \u2014 the $x$ coordinates of the purple bricks (centers of the bases), given in increasing order.\n\n## Output\nPrint the minimum number of additional bricks needed.\n\n## Samples\n\n### Sample Input 1\n```\n4 0\n2 7 11 13\n```\n\n### Sample Output 1\n```\n0\n```\n\n### Explanation of Sample 1\nAll the purple bricks lie on the ground, so no additional bricks are needed.\n\n### Sample Input 2\n```\n4 1\n2 7 11 13\n```\n\n### Sample Output 2\n```\n3\n```\n\n### Explanation of Sample 2\nVittorio will have to place supporting bricks under the purple bricks, and he can use a single brick to support both the third and the fourth purple bricks. For example, he can place additional bricks at positions $(3, 0, 0)$, $(7, 0, 0)$, and $(12, 0, 0)$. It can be shown that it is impossible to build a valid construction using less than 3 additional bricks.\n\n### Sample Input 3\n```\n4 100\n2 7 11 13\n```\n\n### Sample Output 3\n```\n107\n```\n\n### Sample Input 4\n```\n4 3\n2 5 8 11\n```\n\n### Sample Output 4\n```\n8\n```\n\n### Explanation of Sample 4\nA possible structure that minimizes the number of additional bricks is shown in the problem description.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2023_I", "prompt": "### Problem: Isolated Island\n\nOn a small island far, far away, a handful of old men live isolated from the rest of the world. The entire island is divided into plots of land by fences, and each old man owns a single plot of land bounded by fences on all sides. (The region outside all fences is the ocean.) Each of the inhabitants needs fish to survive, and the only place where they can fish is the ocean surrounding them. Since not every plot of land is connected to the ocean, some of the men might need to pass through the land of others before being able to fish. The men can cross a single fence at a time, but cannot go through fenceposts or locations where fences intersect.\n\nUnfortunately, the old men are greedy. They demand one fish each time a person wants to enter their land. Since they do not want to lose too much fish to the others, every old man chooses a route that minimizes the number of fish he has to pay to get to the ocean.\n\nOver the years, this has led to rivalry between the old men. Each man hates all other men who have to pay less than him to reach the ocean. Two men only *like* each other if they have to pay the same amount of fish to reach the ocean.\n\nThe natural question which now occurs is: are there some old men on this island who are neighbours (owning land on opposite sides of a single fence) and like each other? See the illustrations of the first three Sample Inputs for examples of islands with opposite answers to this question.\n\n#### Input\nThe input consists of:\n- One line with an integer $n$ ($3 \\le n \\le 1000$), the number of fences.\n- $n$ lines, each with four integers $x_1$, $y_1$, $x_2$, and $y_2$ ($\\left|x_1\\right|, \\left|y_1\\right|, \\left|x_2\\right|, \\left|y_2\\right| \\leq 10^6$, $(x_1,y_1) \\neq (x_2,y_2)$), indicating a straight fence between fenceposts at $(x_1,y_1)$ and $(x_2, y_2)$.\n\nNote that fences may intersect internally, and that three or more fences may intersect in the same location. It is guaranteed that any two fences intersect only in at most one point. Furthermore, after crossing a single fence, one always ends up in a different region. All regions together form a single island, where any region can be reached from any other region.\n\n#### Output\nIf there exists a pair of neighbours who like each other, then output \"yes\". Otherwise, output \"no\".\n\n#### Sample Inputs and Outputs\n\n**Sample Input 1**\n```\n6\n-3 -3 0 3\n-3 -3 0 0\n-3 -3 3 -3\n0 0 0 3\n0 0 3 -3\n0 3 3 -3\n```\n**Sample Output 1**\n```\nyes\n```\n\n**Sample Input 2**\n```\n6\n-6 -3 0 3\n0 3 6 -3\n6 -3 -6 -3\n-3 0 3 0\n3 0 0 -3\n0 -3 -3 0\n```\n**Sample Output 2**\n```\nno\n```\n\n**Sample Input 3**\n```\n8\n0 1 2 1\n2 2 0 0\n1 2 1 0\n1 0 2 1\n0 0 2 0\n1 2 2 2\n0 1 0 0\n2 2 2 0\n```\n**Sample Output 3**\n```\nyes\n```\n\n**Sample Input 4**\n```\n4\n0 0 1 0\n1 0 1 1\n1 1 0 1\n0 1 0 0\n```\n**Sample Output 4**\n```\nno\n```\n\n**Illustrations of the Samples**\n- In Sample Input 1, every man has direct access to the ocean, so they all like each other.\n- In Sample Input 2, there does not exist a pair of neighbours who like each other, because the man living in the middle needs to pay one fish, whereas all of his neighbours do not have to pay any fish to reach the ocean.\n- In Sample Input 3, there are six men, some of whom are friendly neighbours.\n- In Sample Input 4, there are no pairs of neighbours who like each other.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2024_C", "prompt": "# Problem Statement\n\nIn the town of Nattanham, all roads run either north to south, or east to west, and span the entire town. Furthermore, all roads are an equal distance apart. This makes navigating the town extremely easy.\n\nUnfortunately, the roads are quite poor and could do with a fresh layer of asphalt. However, there is not enough money to fix all the roads, so some sections of road need to be given priority.\n\nThe mayor has selected five locations in town that he considers to be of great importance: the city hall, the police station, the hospital, the fire department, and of course the mayor's house. Each of these locations is at an intersection.\n\nThe mayor wishes that, for each pair of these important locations, it becomes possible to get from one to the other along a shortest path that consists entirely of refurbished road. Within this restriction, the mayor would like to refurbish the smallest amount of road. The intersections do not count toward this amount.\n\nGiven are five locations in a city grid with square blocks, with coordinates up to $1000$. Refurbish a set of streets in the grid, such that:\n- for any two locations there exists a shortest path between them that only uses refurbished streets; and\n- the total length of the refurbished streets is minimized.\n\nOutput the minimum number of road segments that need to be refurbished.\n\n## Input\n\nThe input consists of:\n- Five lines, each with two integers $x$ and $y$ ($0 \\le x, y \\le 1000$), the grid coordinates of each of the five important locations.\n\nIt is guaranteed that the locations are distinct.\n\n## Output\n\nOutput the minimum number of road segments that need to be refurbished.\n\n### Sample Input 1\n```\n8 1\n3 4\n6 7\n10 4\n1 2\n```\n\n### Sample Output 1\n```\n22\n```\n\n### Sample Input 2\n```\n0 0\n0 10\n20 0\n20 10\n3 3\n```\n\n### Sample Output 2\n```\n70\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2024_M", "prompt": "# Problem Statement\n\nYou are given a convex polygon with $n$ vertices ($3 \\le n \\le 2 \\cdot 10^5$), with a mouse sitting at each vertex. A cat jumps to some point inside that polygon. For any location of the cat, one can count the number of *encirclements*: sets of three mice such that the cat is in the triangle spanned by the mice. Find the expected value for the number of encirclements when the location of the cat is uniformly random inside the polygon. The coordinates $x, y$ are up to $10^7$ in absolute value. The absolute or relative error of your answer must be at most $10^{-4}$.\n\n## Input\nThe input consists of:\n- One line with an integer $n$ ($3 \\leq n \\leq 2 \\cdot 10^5$), the number of mice.\n- $n$ lines, each with two integers $x$ and $y$ ($|x|, |y| \\leq 10^7$), the coordinates of a mouse.\n\nThe coordinates of the mice are given in counterclockwise order and form a strictly convex polygon with non-zero area. A strictly convex polygon is a convex polygon such that no three consecutive vertices are on a straight line.\n\n## Output\nOutput the expected number of encirclements after Medea lands inside the polygon.\n\nYour answer should have an absolute or relative error of at most $10^{-4}$.\n\n## Sample Inputs and Outputs\n\n### Sample Input 1\n```plaintext\n4\n0 0\n1 0\n1 1\n0 1\n```\n\n### Sample Output 1\n```plaintext\n2.0\n```\n\n### Sample Input 2\n```plaintext\n5\n0 0\n1 0\n2 1\n1 2\n0 2\n```\n\n### Sample Output 2\n```plaintext\n3.66666667\n```\n\n### Sample Input 3\n```plaintext\n3\n-3141592 -2718281\n-3141593 -2718281\n-3141592 -2718282\n```\n\n### Sample Output 3\n```plaintext\n1.0\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "nwerc2023_F", "prompt": "# Fixing Fractions\n\nMaths is hard. But it could be easier! And the internet has found some excellent ways to make it easier. Take a look at the following true equations:\nFollowing the patterns, we come to the conclusion that the following equation should also be true:\nHowever, this is actually wrong in boring old standard maths. Therefore, we define a new kind of funky maths where it is allowed to cancel out digits on the left side of the equality sign. This surely will make everyone's life easier. Except yours, since you have to evaluate if two given fractions are equal in our new funky maths.\n\n## Input\nThe input consists of:\n- One line with four integers $a$, $b$, $c$, and $d$ ($1 \\leq a, b, c, d < 10^{18}$), describing the two fractions $\\frac{a}{b}$ and $\\frac{c}{d}$.\n\n## Output\nIf there exist integers $a'$ and $b'$ obtained from $a$ and $b$ by cancelling out the same digits and with $\\frac{a'}{b'} = \\frac{c}{d}$ in standard mathematics, output \"possible\", followed by $a'$ and $b'$.\nOtherwise, output \"impossible\".\n\nIf there are multiple valid solutions, you may output any one of them.\n\nNote that neither $a'$ nor $b'$ is allowed to contain leading zeroes after cancelling digits.\n\n## Sample Input 1\n```\n163 326 1 2\n```\n\n## Sample Output 1\n```\npossible\n1 2\n```\n\n## Sample Input 2\n```\n871 1261 13 39\n```\n\n## Sample Output 2\n```\npossible\n87 261\n```\n\n## Sample Input 3\n```\n123 267 12339 23679\n```\n\n## Sample Output 3\n```\nimpossible\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2023_A", "prompt": "# Problem: Arranging Adapters\n\nIt is the day before the NWERC and you and your team are on the train towards Delft. The journey is long and boring but you came up with a good idea: \"Let's do some *train*ing.\"\n\n-- silence --\n\nYou take your laptop out and try to plug it in when you notice that the only socket is already in use. Your friends smirk and reply: \"No socket for you, no *train*ing for us.\" Their smirks quickly fade as you pull out a power strip, unplug the charger from the socket, and plug it back into the power strip. Now, there is enough space for your charger as well.\n\nHowever, as soon as more sockets are available, your friends suddenly take out more devices that need to be charged. You realize that you will not get them to train like this, so you decide to trick them into solving a problem instead.\n\nYour power strip comprises a row of $s$ sockets, and each socket is $3\\,\\text{cm}$ in diameter. Furthermore, as you examine the chargers, you notice that they all have integer lengths. The plug of each charger is always on one of the two ends, and each charger can only be used in two orientations. Chargers cannot overlap, but can touch, and can extend beyond the end of the power strip as long as they are plugged into a socket.\n\nNow you challenge them to charge as many devices as possible. This is visualized in the illustration below. Hoping that this allows them to avoid the *train*ing, your friends agree to write a program to solve this.\n\n## Input\nThe input consists of:\n- One line with two integers $n$ and $s$ ($1 \\leq n \\leq 2 \\cdot 10^5$, $1 \\leq s \\leq 10^9$), the number of chargers you have and the number of sockets on the power strip.\n- One line with $n$ integers $w$ ($3 \\leq w \\leq 10^9$), the width of each charger in centimetres.\n\nNote that you are allowed to rotate chargers by $180^\\circ$ before plugging them in.\n\n## Output\nOutput the maximum number of chargers you can plug into the power strip at the same time.\n\n## Sample Input 1\n```\n5 7\n7 4 4 5 8\n```\n\n## Sample Output 1\n```\n5\n```\n\n## Sample Input 2\n```\n8 9\n7 4 3 6 4 8 5 6\n```\n\n## Sample Output 2\n```\n6\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2024_K", "prompt": "# Problem Statement\n\n## Problem Title\n\nEvery week, Karlijn and her teammates join the competitive programming training at their university. Thinking and coding for such a long time is quite exhausting, and they need a ton of snacks to get through training. They have divided the chore of bringing snacks neatly: while the other two bring stroopwafels and salt sticks, Karlijn's duty is to provide kruidnoten.\n\nShe usually gets them on the way from home to university just before training. The bicycle network in her home town consists of intersections which are connected by cycleways of different lengths. The intersections are numbered from $1$ to $n$. Karlijn's house is at intersection $1$, and her university is at intersection $n$.\n\nThere are multiple stores that sell kruidnoten, but some of them are often out of stock. Karlijn wants to get to university as quickly as possible, so she has a habit of looking up online which stores still have kruidnoten before leaving her house. Using this information, she then takes the shortest path via some stocked store. An example is visualized in the figure below.\n\nNow, she wonders how much time she should usually plan for her way to training. From long-time experience, Karlijn knows for each store how likely it is that they have not sold out. In particular, she observed that the stock of kruidnoten is independent for each store. What is the expected length of a shortest path from Karlijn's house to university if she wants to visit some store that has kruidnoten in stock?\n\n## Input\nThe input consists of:\n- One line with three integers $n$, $m$, and $k$ ($2 \\leq n \\leq 2 \\cdot 10^5$, $1 \\leq m \\leq 2 \\cdot 10^5$, $1 \\leq k \\leq n$), the number of intersections, cycleways, and stores that may sell kruidnoten.\n- $m$ lines, each with three integers $i$, $j$, and $\\ell$ ($1 \\leq i, j \\leq n$, $i \\neq j$, $1 \\leq \\ell \\leq 10^6$), indicating that the intersections $i$ and $j$ are connected by a cycleway of length $\\ell$. It is guaranteed that every pair of intersections is connected by at most one cycleway. Further, it is possible to get from every intersection to every other intersection by bike.\n- $k$ lines, each with one integer $i$ ($1 \\leq i \\leq n$) and one floating-point number $p$ ($0 < p \\leq 1$ with at most four digits after the decimal point), indicating that there is a store located at intersection $i$, and that the probability that it still has kruidnoten is $p$. It is guaranteed that there is at most one kruidnoten store at each intersection.\n\n## Output\n\nIf the event that Karlijn cannot get any kruidnoten on her way has probability $> 0$, output \"impossible\". Otherwise, output the expected length of a shortest path from her home to university if she gets kruidnoten on the way. Your answer should have an absolute or relative error of at most $10^{-6}$.\n\n## Sample Input 1\n```\n5 5 3\n1 2 6\n3 1 4\n4 5 2\n1 4 1\n3 4 5\n2 1.0\n3 0.4\n5 0.1\n```\n\n## Sample Output 1\n```\n12.36\n```\n\n## Sample Input 2\n```\n6 5 2\n1 2 1\n1 3 1\n4 5 3\n5 6 1\n6 3 2\n1 0.6283\n4 0.3142\n```\n\n## Sample Output 2\n```\nimpossible\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": "nwerc2022_F", "prompt": "# Problem Statement\n\n## Problem Title: Faster Than Light\n\n* Determine whether it is possible to hit all rooms in a spaceship with a single, infinite-length beam.\n* The spaceship is represented by a set of $1 \\leq n \\leq 2 \\cdot 10^5$ axis-aligned non-intersecting rectangles ($0 \\leq x_1 < x_2 \\leq 10^9$ and $0 \\leq y_1 < y_2 \\leq 10^9$).\n\n![Illustration of Sample Input 1, which consists of five grey rooms. The hull beam in red hits all rooms and is the only valid solution in this case.](sample)\n\n## Input\n\nThe input consists of:\n* One line with an integer $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$), the number of rooms.\n* $n$ lines, each with four integers $x_1$, $y_1$, $x_2$, and $y_2$ ($0 \\leq x_1 < x_2 \\leq 10^9$ and $0 \\leq y_1 < y_2 \\leq 10^9$), describing the coordinates of two opposite corners ($x_1$,$y_1$) and ($x_2$,$y_2$) of a room.\n\nIt is guaranteed that no two rooms have a common interior point.\n\n## Output\n\nIf it is possible for the hull beam to pass through all rooms at once, output `possible`.\nOtherwise, output `impossible`.\n\n## Sample Input/Output\n\n### Sample Input 1\n```\n5\n1 3 3 4\n2 2 4 3\n4 1 5 3\n5 2 7 3\n6 3 8 4\n```\n\n### Sample Output 1\n```\npossible\n```\n\n### Sample Input 2\n```\n4\n1 1 2 2\n1 3 2 4\n3 1 4 2\n3 3 4 4\n```\n\n### Sample Output 2\n```\nimpossible\n```\n\n### Sample Input 3\n```\n3\n1 1 2 2\n1 3 2 4\n3 3 4 4\n```\n\n### Sample Output 3\n```\npossible\n```\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "hard"} +{"id": "swerc2022_F", "prompt": "# Problem F: Beppa and SwerChat\n## SWERC 2022-2023\n\n## Problem Description\n\nBeppa and her circle of geek friends keep up to date on a group chat in the instant messaging app SwerChat\u2122. The group has $n$ members, excluding Beppa. Each of those members has a unique ID between 1 and $n$. When a user opens a group chat, SwerChat\u2122 displays the list of other members of that group, sorted by decreasing times of last seen online (so the member who opened the chat most recently is the first in the list). However, the times of last seen are not displayed.\n\nToday, Beppa has been busy all day: she has only opened the group chat twice, once at 9:00 and once at 22:00. Both times, she wrote down the list of members in the order they appeared at that time. Now she wonders: what is the minimum number of other members that must have been online at least once between 9:00 and 22:00?\n\nBeppa is sure that no two members are ever online at the same time and no members are online when Beppa opens the group chat at 9:00 and 22:00.\n\n## Input\n\nEach test contains multiple test cases. The first line contains an integer $t$ ($1 \\leq t \\leq 10000$) \u2014 the number of test cases. The descriptions of the $t$ test cases follow.\n\nThe first line of each test case contains an integer $n$ ($1 \\leq n \\leq 10^5$) \u2014 the number of members of the group excluding Beppa.\n\nThe second line contains $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq n$) \u2014 the list of IDs of the members, sorted by decreasing times of last seen online at 9:00.\n\nThe third line contains $n$ integers $b_1, b_2, \\ldots, b_n$ ($1 \\leq b_i \\leq n$) \u2014 the list of IDs of the members, sorted by decreasing times of last seen online at 22:00.\n\nFor all $1 \\leq i < j \\leq n$, it is guaranteed that $a_i \\neq a_j$ and $b_i \\neq b_j$.\n\nIt is also guaranteed that the sum of the values of $n$ over all test cases does not exceed $10^5$.\n\n## Output\n\nFor each test case, print the minimum number of members that must have been online between 9:00 and 22:00.\n\n## Sample Input\n\n```\n4\n5\n1 4 2 5 3\n4 5 1 2 3\n6\n1 2 3 4 5 6\n1 2 3 4 5 6\n8\n8 2 4 7 1 6 5 3\n5 6 1 4 8 2 7 3\n1\n1\n1\n```\n\n## Sample Output\n\n```\n2\n0\n4\n0\n```\n\n## Explanation of Sample 1\n\n- In the first test case, members 4 and 5 must have been online between 9:00 and 22:00.\n- In the second test case, it is possible that nobody has been online between 9:00 and 22:00.\n### Format: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within delimiters as follows.\n```python\ndef main():\n\n \nif __name__ == \"__main__\":\n main()```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "icpc", "language": "python", "difficulty": "medium"} +{"id": 2423, "prompt": "### Problem Description\nThe annual \"Rock Jumping\" competition is about to begin!\n\nThis competition takes place in a straight river channel, where some giant rocks are distributed. The organizers have chosen two rocks as the starting point and the endpoint of the competition. Between the start and endpoint, there are $N$ rocks (excluding the starting and endpoint rocks). During the competition, participants will start at the starting point and jump to adjacent rocks step by step until they reach the endpoint.\n\nTo make the competition more challenging, the organizers plan to remove some of the rocks, trying to maximize the shortest jump distance during the competition. Due to budget constraints, the organizers can remove at most $M$ rocks lying between the starting and endpoint (the start and endpoint rocks cannot be removed).\n\n### Input Format\nThe first line of the input file contains three integers $L$, $N$, and $M$, representing the distance between the starting point and the endpoint, the number of rocks between the start and endpoint, and the maximum number of rocks that can be removed, respectively. \n\nThe next $N$ lines each contain an integer $D_i$ ($0 < D_i < L$), where the $i^{th}$ line indicates the distance of the $i^{th}$ rock from the starting point. These rocks are given in ascending order of distance from the starting point, and no two rocks share the same position.\n\n### Output Format\nThe output file contains a single integer, which is the maximum possible value of the shortest jump distance.\n\n### Example\n\n**Data Range and Hints** \nFor $20\\%$ of the data, $0 \\leq M \\leq N \\leq 10$. \nFor $50\\%$ of the data, $0 \\leq M \\leq N \\leq 100$. \nFor $100\\%$ of the data, $0 \\leq M \\leq N \\leq 50,000$, $1 \\leq L \\leq 1,000,000,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2131, "prompt": "### Problem Description\n\nTo celebrate the successful opening of NOI, the organizers have prepared a sushi banquet. Xiao G and Xiao W, as contestants of NOI, are also invited to the sushi banquet. \n\nAt the banquet, the organizers provide $n-1$ different types of sushi, numbered $1, 2, 3, \\ldots, n-1$. The deliciousness of the $i$-th type of sushi is $i+1$ (hence the deliciousness ranges from $2$ to $n$). \n\nNow, Xiao G and Xiao W would like to each choose some types of sushi to taste. They define a tasting plan as **disharmonious** if and only if: there exists a sushi with a deliciousness value $x$ among the types of sushi Xiao G tastes, and there exists a sushi with a deliciousness value $y$ among the types of sushi Xiao W tastes, such that $x$ and $y$ are not coprime. \n\nXiao G and Xiao W now want to count the total number of **harmonious** sushi tasting plans (modulo a given positive integer $p$). Note that it is possible for either person to not taste any sushi. \n\n---\n\n### Input Format\n\nThe first line of the input contains two positive integers $n$ and $p$, separated by a single space, indicating that there are $n$ types of sushi in total, and the total number of harmonious plans should be computed modulo $p$. \n\n---\n\n### Output Format\n\nOutput a single line containing one integer, representing the result of the harmonious plans modulo $p$. \n\n---\n\n### Sample\n\n---\n\n### Constraints and Hints\n\n$2 \\leq n \\leq 500, \\ 0 < p \\leq 1000000000$ \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2502, "prompt": "### Problem Description\nIn a directed graph $ G $, where the length of each edge is $ 1 $, you are given a starting point and an ending point. Your task is to find a path in the graph from the starting point to the ending point that satisfies the following conditions:\n\n1. Every vertex in the path must have outgoing edges pointing to vertices that are directly or indirectly connected to the ending point.\n2. Among paths that satisfy condition 1, the path must be the shortest.\n\nNote: The graph $ G $ may contain duplicate edges and self-loops. It is guaranteed that the ending point has no outgoing edges.\n\nOutput the length of the path that meets the above conditions.\n\n---\n\n### Input Format\nThe first line contains two integers $ n $ and $ m $, separated by a space, representing that the graph has $ n $ vertices and $ m $ edges.\n\nThe next $ m $ lines each contain two integers $ x $ and $ y $, separated by a space, indicating an edge going from vertex $ x $ to vertex $ y $.\n\nThe last line contains two integers $ s $ and $ t $, separated by a space, where $ s $ is the starting point and $ t $ is the ending point.\n\n---\n\n### Output Format\nOutput a single integer representing the length of the shortest path that satisfies the conditions described in the problem. If no such path exists, output $ -1 $.\n\n---\n\n### Example 1\n\n---\n\n### Example 2\n\n---\n\n### Constraints and Hints\n- For $ 30\\% $ of the cases: $ 0 < n \\le 10 $, $ 0 < m \\le 20 $. \n- For $ 60\\% $ of the cases: $ 0 < n \\le 100 $, $ 0 < m \\le 2000 $. \n- For $ 100\\% $ of the cases: $ 0 < n \\le 10000 $, $ 0 < m \\le 200000 $, $ 0 < x, y, s, t \\le n $, $ x,s \\ne t $.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2611, "prompt": "### Problem Description\n\nThe Chun Chun Kindergarten is hosting its annual \"Building Block Competition.\" This year's challenge is to construct a building with a width of $n$. The building can be considered as consisting of $n$ blocks, each with a width of $1$. The final height of the $i$-th block should be $h_i$.\n\nAt the beginning of the construction process, no blocks are present (it can be regarded as $n$ blocks with a height of $0$). During each operation, the children can select a continuous interval $[L, R]$, and increase the height of all blocks from the $L$-th block to the $R$-th block (inclusive) by $1$.\n\nLittle M is a clever child, and she quickly devised the optimal strategy to minimize the number of operations needed to construct the building. However, she is not a fan of executing her plans, so she asked you to implement the strategy and calculate the minimum number of operations required.\n\n### Input Format\n\nThe input contains two lines:\n\n1. The first line contains an integer $n$, representing the width of the building.\n2. The second line contains $n$ integers, where the $i$-th integer is $h_i$.\n\n### Output Format\n\nOutput only one line, the minimum number of operations required to construct the building.\n\n### Example\n\nOne feasible optimal strategy is to successively choose $[1, 5], [1, 3], [2, 3], [3, 3], [5, 5]$.\n\n### Constraints and Tips\n\n- For 30% of the data, $1 \\leq n \\leq 10$.\n- For 60% of the data, $1 \\leq n \\leq 1\\,000$.\n- For 100% of the data, $1 \\leq n \\leq 100\\,000$, $0 \\leq h_i \\leq 10\\,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2503, "prompt": "### Problem Description\nGiven a polynomial equation:\n\n$$a_0 + a_1x + a_2x^2 + \\cdots + a_nx^n = 0$$\n\nFind all integer solutions within the range $[1, m]$ where $n$ and $m$ are positive integers.\n\n### Input Format\nThe input consists of $n + 2$ lines. \n- The first line contains two integers $n$ and $m$, separated by a space. \n- The next $n + 1$ lines each contain one integer, representing the coefficients $a_0, a_1, a_2, \\ldots, a_n$ in order.\n\n### Output Format\n- On the first line, output the number of integer solutions to the equation within the interval $[1, m]$. \n- Then, each subsequent line should output one integer solution within $[1, m]$, listed in increasing order.\n\n### Example 1\n\n#### Example 2\n\n#### Example 3\n\n### Constraints and Hints\n- For $30\\%$ of the test cases: $0 < n \\leq 2$, $|a_i| \\leq 100$, $a_n \\neq 0$, $m < 100$. \n- For $50\\%$ of the test cases: $0 < n \\leq 100$, $|a_i| \\leq 10^{100}$, $a_n \\neq 0$, $m < 100$. \n- For $70\\%$ of the test cases: $0 < n \\leq 100$, $|a_i| \\leq 10^{10000}$, $a_n \\neq 0$, $m < 10^4$. \n- For $100\\%$ of the test cases: $0 < n \\leq 100$, $|a_i| \\leq 10^{10000}$, $a_n \\neq 0$, $m < 10^6$. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2499, "prompt": "### Problem Description\nAn undirected connected graph $G$ consists of $n$ nodes and $n - 1$ edges. The nodes are numbered from $1$ to $n$, and the weight of the node numbered $i$ is $W_i$. The length of each edge is $1$. The **distance** between two nodes $(u, v)$ on the graph is defined as the shortest path distance from node $u$ to node $v$. For a pair of nodes $(u, v)$ on graph $G$, if the distance between them is $2$, then they will generate a **joint weight** equal to $W_v \\times W_u$.\n\nWhat is the **maximum joint weight** among all possible ordered pairs in graph $G$? Additionally, what is the **sum of all joint weights**? \n\n### Input Format\nThe first line contains a single integer $n$. \n\nThe next $n - 1$ lines each contain $2$ positive integers $u, v$, separated by a space, indicating that there is an edge between node $u$ and node $v$. \n\nThe last line contains $n$ positive integers separated by a space, where the $i^{th}$ integer represents the weight $W_i$ of the node numbered $i$ in graph $G$. \n\n### Output Format\nOutput a single line containing 2 integers separated by a space: the maximum joint weight in graph $G$ and the sum of all joint weights. \n**Since the sum of all joint weights might be very large, the result should be taken modulo $10007$.**\n\n### Example\n\n**Input:**\n```\n4\n1 2\n2 3\n1 4\n2 4 3 1\n```**Output:**\n```\n8 17\n```\n\n### Constraints and Hints\n- For $30\\%$ of the data, $1 < n \\leq 100$.\n- For $60\\%$ of the data, $1 < n \\leq 2000$.\n- For $100\\%$ of the data, $1 < n \\leq 200000$, $0 < W_i \\leq 10000$.\n\nIt is guaranteed that at least one valid ordered pair exists in the graph that can generate a joint weight.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2665, "prompt": "### Problem Description\n\nWe know that a rooted tree can be traversed using Depth First Search (DFS) and Breadth First Search (BFS), yielding its DFS sequence and BFS sequence respectively. The DFS sequence of two different trees can be identical, and their BFS sequence can also be identical. For instance, the DFS sequence of the two trees below is `1 2 4 5 3` and their BFS sequence is `1 2 3 4 5`.\n\n![](https://i.loli.net/2018/06/10/5b1ce8c6521c4.png)\n\nGiven a DFS sequence and a BFS sequence, we want to know the average height of all possible rooted trees that satisfy these sequences. That is, if there are $K$ different rooted trees with the given DFS and BFS sequences, and their heights are $h_1, h_2, \\ldots, h_K$, please output:\n\n$$\n\\frac{h_1 + h_2 + \\ldots + h_K}{K}\n$$\n\n---\n\n### Input Format\n\n- The first line contains a positive integer $n$, representing the number of nodes in the tree.\n- The second line contains $n$ positive integers, which form a permutation of $1 \\ldots n$, representing the DFS sequence of the tree.\n- The third line contains $n$ positive integers, which form a permutation of $1 \\ldots n$, representing the BFS sequence of the tree.\n\nIt is guaranteed that there is at least one tree that satisfies the given DFS and BFS sequences.\n\n---\n\n### Output Format\n\nOutput a single real number, rounded to exactly three decimal places, representing the average height of the trees.\n\n---\n\n### Examples\n\n#### Example Input 1\n```plain\n5\n1 2 4 5 3\n1 2 3 4 5\n```#### Example Output 1\n```plain\n3.500\n```\n\n#### Example Input and Output 2\nRefer to the files `count.in` and `count.ans` in the additional attachment.\n\n---\n\n### Constraints and Notes\n\n- If the absolute difference between the output and the correct answer does not exceed $0.001$, the test point will be considered passed; otherwise, it will not be scored.\n- For $20\\%$ of the test cases, $n \\leq 10$.\n- For $40\\%$ of the test cases, $n \\leq 100$.\n- For $85\\%$ of the test cases, $n \\leq 2000$.\n- For $100\\%$ of the test cases, $2 \\leq n \\leq 200,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2424, "prompt": "### Problem Description\nThere are two strings $ A $ and $ B $ that only consist of lowercase English letters. The task is to extract $ k $ non-overlapping, non-empty substrings from string $ A $ and concatenate them in the order in which they appear in string $ A $ to form a new string. Determine how many ways it is possible for this new string to be equal to string $ B $.\n\n**Note**: Different positions of substring extraction are considered different solutions.\n\n### Input Format\nThe first line contains three positive integers $ n, m, k $, which represent the length of string $ A $, the length of string $ B $, and the value of $ k $ as mentioned in the problem description. Each pair of integers is separated by a single space. \nThe second line contains a string of length $ n $, representing string $ A $. \nThe third line contains a string of length $ m $, representing string $ B $. \n\n### Output Format\nOutput a single integer in one line, representing the number of solutions. Since the result could be very large, output the result modulo $ 1,000,000,007 $.\n\n### Sample Input and Output\n\n#### Sample 1:\n\n#### Sample 2: \n\n#### Sample 3: \n\n---\n\n### Constraints and Hints\nFor the $ 1^{st} $ dataset: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, k = 1 $; \nFor the $ 2^{nd} $ to $ 3^{rd} $ datasets: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, k = 2 $; \nFor the $ 4^{th} $ to $ 5^{th} $ datasets: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, k = m $; \nFor the $ 1^{st} $ to $ 7^{th} $ datasets: $ 1 \\leq n \\leq 500, 1 \\leq m \\leq 50, 1 \\leq k \\leq m $; \nFor the $ 1^{st} $ to $ 9^{th} $ datasets: $ 1 \\leq n \\leq 1000, 1 \\leq m \\leq 100, 1 \\leq k \\leq m $; \nFor all $ 10 $ datasets: $ 1 \\leq n \\leq 1000, 1 \\leq m \\leq 200, 1 \\leq k \\leq m $.\n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2415, "prompt": "### Problem Statement\n\nXiaoyuan and Xiaoxuan are good friends and classmates who always have endless topics to discuss. During one team-building activity, their classmates arranged themselves in a matrix of $m$ rows and $n$ columns. Xiaoyuan and Xiaoxuan were seated at the two ends of the diagonal of the matrix, making it impossible for them to converse directly. Fortunately, they could communicate by passing a note. The note must be passed through several classmates to reach the other person. Xiaoyuan is seated at the top-left corner of the matrix at coordinate $(1,1)$, while Xiaoxuan is seated at the bottom-right corner at coordinate $(m,n)$. The note passed from Xiaoyuan to Xiaoxuan can only be moved down or to the right, and the note passed from Xiaoxuan to Xiaoyuan can only be moved up or to the left.\n\nDuring the activity, Xiaoyuan wants to send a note to Xiaoxuan, and at the same time, Xiaoxuan wants to reply with a note to Xiaoyuan. Every classmate can help pass the notes, but they will only help once. In other words, if a classmate helps pass the note from Xiaoyuan to Xiaoxuan, they will not help pass the note back from Xiaoxuan to Xiaoyuan, and vice versa.\n\nAnother important detail to note is that every classmate has varying levels of willingness to help, expressed as their kindness level. The kindness levels (note: those of Xiaoyuan and Xiaoxuan are undefined and represented by $0$ in the input) are represented by natural numbers in the range $[0, 100]$, where larger numbers indicate higher kindness levels. Xiaoyuan and Xiaoxuan hope to find the classmates with the highest kindness levels to help pass the notes. Your task is to identify two paths (one for each note) such that the sum of kindness levels of the classmates involved in both paths is maximized.\n\n### Input Format\n\nThe first line contains two integers $m$ and $n$, separated by a space, indicating that the class has a matrix of $m$ rows and $n$ columns.\n\nThe next $m$ lines describe an $m \\times n$ matrix, where the integer in the $i$th row and $j$th column represents the kindness level of the student seated at $(i,j)$. The $n$ integers in each row are separated by a space.\n\n### Output Format\n\nOutput a single integer in one line, representing the maximum possible sum of kindness levels of students involved in the two paths for passing the notes back and forth.\n\n### Example\n\n#### Input:\n```\n4 4\n5 1 2 4\n8 3 6 7\n2 4 7 9\n6 7 4 9\n```#### Output:\n```\n67\n```\n\n### Constraints and Hints\n\n- For $30\\%$ of the data, $1 \\leq m,n \\leq 10$.\n- For $100\\%$ of the data, $1 \\leq m,n \\leq 50$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2420, "prompt": "### Problem Description\n\nA magic square is a fascinating $N \\times N$ matrix: it consists of the numbers $1, 2, 3, \\ldots, N \\times N$ and satisfies the property that the sum of the numbers in each row, each column, and both diagonals is the same.\n\nWhen $N$ is an odd number, a magic square can be constructed using the following method: \nFirst, write the number $1$ in the middle of the first row. \nThen, fill each successive number $K$ ($K = 2, 3, \\ldots, N \\times N$) as follows:\n\n1. If $(K - 1)$ is in the first row but not in the last column, place $K$ in the last row and in the column immediately to the right of the column containing $(K - 1)$; \n2. If $(K - 1)$ is in the last column but not in the first row, place $K$ in the first column and in the row immediately above the row containing $(K - 1)$; \n3. If $(K - 1)$ is in the last column of the first row, place $K$ directly below $(K - 1)$; \n4. If $(K - 1)$ is neither in the first row nor in the last column, and the position diagonally up and to the right of $(K - 1)$ has not been filled, then place $K$ in that position; otherwise, place $K$ directly below $(K - 1)$.\n\nGiven $N$, construct an $N \\times N$ magic square according to the method described above.\n\n---\n\n### Input Format\n\nThe input consists of a single line containing an integer, which is the size of the magic square.\n\n---\n\n### Output Format\n\nOutput $N$ lines, each containing $N$ integers, representing the magic square constructed using the method described above. Adjacent integers in the same row should be separated by a single space.\n\n---\n\n### Example\n\n```\nInput:\n3\n\nOutput:\n8 1 6\n3 5 7\n4 9 2\n```---\n\n### Constraints and Notes\n\nFor $100\\%$ of the test cases, $1 \\leq N \\leq 39$, and $N$ is an odd number.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2599, "prompt": "### Problem Description\n\nGiven a polynomial $(ax+by)^k$, find the coefficient of the term $x^ny^m$ after expanding the polynomial.\n\n### Input Format\n\nThe input contains one line with 5 integers: $a$, $b$, $k$, $n$, $m$. Each pair of consecutive integers is separated by a single space.\n\n### Output Format\n\nThe output contains one integer representing the desired coefficient. Since the coefficient can be very large, output it modulo $10,007$.\n\n### Example\n\n### Constraints and Hints\n\n- For $30\\%$ of the test cases, $k \\leq 10$. \n- For $50\\%$ of the test cases, $a = 1, b = 1$. \n- For $100\\%$ of the test cases, $0 \\leq k \\leq 1000$, $0 \\leq n, m \\leq k$, and $n + m = k$, $0 \\leq a, b \\leq 10^6$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2129, "prompt": "### Problem Description\n\nIn the process of implementing programmatic automatic analysis, it is often necessary to determine whether certain constraints can be satisfied simultaneously.\n\nConsider a simplified version of a constraint satisfaction problem: Suppose $x_1, x_2, x_3, \\ldots$ represent variables appearing in a program. You are given $n$ constraints of the form $x_i = x_j$ or $x_i \\neq x_j$. Your task is to decide whether it is possible to assign each variable an appropriate value such that all of the given constraints are satisfied simultaneously. \n\nFor example, consider the following constraints: $x_1 = x_2, \\ x_2 = x_3, \\ x_3 = x_4, \\ x_1 \\neq x_4$. These constraints are clearly contradictory and cannot all be satisfied at the same time. Therefore, this problem should be determined as unsatisfiable. \n\nNow, you are given several such constraint satisfaction problems; for each of them, you need to determine whether they are satisfiable.\n\n---\n\n### Input Format\n\nThe first line of the input file contains a positive integer $t$, representing the number of problems to be evaluated. Note that these problems are independent of each other. \n\nFor each problem: \n- The first line contains a positive integer $n$, representing the number of constraints for the problem. \n- The next $n$ lines each contain three integers $i, j, e$, describing a constraint. Integers are separated by a single space. If $e = 1$, the constraint is $x_i = x_j$; if $e = 0$, the constraint is $x_i \\neq x_j$.\n\n---\n\n### Output Format\n\nThe output file consists of $t$ lines. \n\nThe $k$-th line of the output should contain the string `YES` or `NO` (uppercase and without quotation marks): \n- Output `YES` if the $k$-th problem is satisfiable. \n- Output `NO` if the $k$-th problem is not satisfiable.\n\n---\n\n### Example\n\n#### Input:\n```\n2\n2\n1 2 1\n1 2 0\n2\n1 2 1\n2 1 1\n```#### Output:\n```\nNO\nYES\n```\n\n#### Explanation:\nIn the first problem, the constraints are $x_1 = x_2$ and $x_1 \\neq x_2$. These two constraints are contradictory, so they cannot be satisfied simultaneously. \nIn the second problem, the constraints are $x_1 = x_2$ and $x_2 = x_1$. These two constraints are equivalent and can be satisfied simultaneously.\n\n---\n\n### Constraints and Hints\n\n- For all test cases: $1 \\leq t \\leq 10$, $1 \\leq n \\leq 10^6$, $1 \\leq i, j \\leq 10^9$. \n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2445, "prompt": "### Problem Statement\n\nOn planet W, there are $n$ countries. To develop their economies, the countries have decided to construct bidirectional roads to ensure connectivity among them. However, the kings of these countries are very stingy and are only willing to build exactly $n - 1$ bidirectional roads.\n\nThe construction cost for each road is equal to the absolute difference between the number of countries at the two ends of the road multiplied by the road's length. For example, as shown in the figure below, the endpoints of the dashed road connect countries with $2$ and $4$ countries respectively. If the road has a length of $1$, its cost would be $1 \\times \\lvert 2 - 4 \\rvert = 2$. In the figure, the numbers inside the circles represent the country indices.\n\n![](https://i.loli.net/2018/06/11/5b1dfb1e69c02.png)\n\nDue to the vast number of countries, there are numerous ways to construct the roads, and calculating the construction costs for each plan manually is infeasible. Hence, the kings decided to seek help designing a program that, given a specific construction plan, computes the total construction cost for it. Your task is to design such a program.\n\n---\n\n### Input Format\n\nThe first line of the input contains a single integer $n$, which represents the number of countries on planet W, numbered from $1$ to $n$.\n\nThe next $n - 1$ lines each describe the construction of one road. The $i$-th line contains three integers $a_i$, $b_i$, and $c_i$, indicating that the $i$-th bidirectional road connects country $a_i$ and country $b_i$, and its length is $c_i$.\n\n---\n\n### Output Format\n\nOutput a single integer representing the total cost required to construct all roads.\n\n---\n\n### Example\n\n**Input**: \n```\n3\n1 2 1\n2 3 2\n```**Output**: \n```\n1\n```\n\n---\n\n### Constraints and Hints\n\nFor all data, it is guaranteed that $1 \\le a_i, b_i \\le n$ and $0 \\le c_i \\le 10^6$.\n\n| Test Case ID | $n=$ |\n| :-: | :-: |\n| 1 | $2$ |\n| 2 | $10$ |\n| 3 | $100$ |\n| 4 | $200$ |\n| 5 | $500$ |\n| 6 | $600$ |\n| 7 | $800$ |\n| 8 | $1000$ |\n| 9 | $10,000$ |\n| 10 | $20,000$ |\n| 11 | $50,000$ |\n| 12 | $60,000$ |\n| 13 | $80,000$ |\n| 14 | $100,000$ |\n| 15 | $600,000$ |\n| 16 | $700,000$ |\n| 17 | $800,000$ |\n| 18 | $900,000$ |\n| 19 | $1,000,000$ |\n| 20 | $1,000,000$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2609, "prompt": "### Problem Description\nHanhang has two boxes of matches, each containing $n$ matches, and each match has a height. The matches in each box can be arranged into a row, where the heights of matches in the same row are distinct. The distance between the two rows of matches is defined as: \n$$\\sum_{i=1}^{n} (a_i - b_i)^2$$ \nwhere $a_i$ represents the height of the $i$-th match in the first row, and $b_i$ represents the height of the $i$-th match in the second row.\n\nIn each row, adjacent matches can be swapped. Your task is to minimize the distance between the two rows by swapping the positions of matches. Then find the minimal number of swaps required to achieve this minimum distance. **If the number of swaps is too large, output the result modulo 99,999,997.**\n\n### Input Format\nThe input consists of three lines: \n- The first line contains an integer $n$, representing the number of matches in each box. \n- The second line contains $n$ integers separated by spaces, representing the heights of the matches in the first row. \n- The third line contains $n$ integers separated by spaces, representing the heights of the matches in the second row.\n\n### Output Format\nOutput a single integer representing the minimal number of swaps modulo 99,999,997 required to achieve the minimum distance.\n\n### Example 1\nFor the input: \n```\n2\n1 2\n2 1\n```\nThe minimum distance is $0$, and the minimal number of swaps is $1$. For example, swapping the first two matches in the first row or swapping the first two matches in the second row achieves the minimum distance.\n\n### Example 2\nFor the input: \n```\n3\n3 1 2\n3 2 1\n```\nThe minimum distance is $10$, and the minimal number of swaps is $2$. For example, swapping the middle two matches in the first row and swapping the last two matches in the second row achieves the minimum distance.\n\n### Constraints and Hints\n- For 10% of the test cases, $1 \\leq n \\leq 10$. \n- For 30% of the test cases, $1 \\leq n \\leq 100$. \n- For 60% of the test cases, $1 \\leq n \\leq 5,000$. \n- For 100% of the test cases, $1 \\leq n \\leq 100,000$, and $0 \\leq $ match height $ \\leq 2^{31} - 1$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2596, "prompt": "### Problem Description\n\nTo prepare for a unique award ceremony, the organizers are laying rectangular carpets in a rectangular area of the venue (considered as the first quadrant of a Cartesian coordinate plane).\n\nThere are $n$ carpets, numbered from $1$ to $n$. These carpets are laid out in sequence according to their number, parallel to the coordinate axes. A newly placed carpet will cover earlier ones that have already been laid.\n\nAfter all the carpets are placed, the organizers want to determine which carpet is at the top layer at a specific point on the ground.\n\nNote: Points located on the boundaries and the four corners of a rectangular carpet are also considered to be covered.\n\n### Input Format\n\nThe input consists of $n+2$ lines.\n\n- The first line contains a single integer $n$, which represents the total number of carpets.\n- The next $n$ lines describe the information of the carpets. The $(i+1)$-th line contains four positive integers: $a, b, g, k$, separated by a space. These integers describe the bottom-left corner $(a, b)$ of the carpet and its dimensions: $g$ is the length along the $x$-axis, and $k$ is the length along the $y$-axis.\n- The last line ($n+2$-th line) contains two positive integers $x$ and $y$, which represent the coordinates of the point $(x, y)$ on the ground that is to be queried.\n\n### Output Format\n\nThe output consists of a single line with one integer. The integer represents the carpet number of the topmost layer covering the queried point; if no carpet covers the point, output $-1$.\n\n### Example 1\n\nAs shown below, the solid line represents Carpet 1, the dashed line represents Carpet 2, and the double solid line represents Carpet 3. The point $(2, 2)$ is covered by Carpet 3, which is the topmost layer.\n\n![pic1.png](https://img.loj.ac.cn/2021/12/29/1b6a93302ed5e.png)\n\n### Example 2\n\nAs shown above, the solid line represents Carpet 1, the dashed line represents Carpet 2, and the double solid line represents Carpet 3. The point $(4, 5)$ is not covered by any carpet, so the output is `-1`.\n\n### Constraints and Hints\n\n- For $30\\%$ of the data, $n \\leq 2$;\n- For $50\\%$ of the data, $a, b, g, k \\leq 100$;\n- For $100\\%$ of the data: $0 \\leq n \\leq 10^4$, and $0 \\leq a, b, g, k \\leq 10^5$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2594, "prompt": "### Problem Description\nIn city S, there are currently two prisons, imprisoning a total of $N$ criminals numbered $1$ to $N$. Relationships among these criminals are naturally very discordant. Many of them bear grudges against each other, and conflicts may erupt at any time if the conditions are favorable. We use the \"resentment value\" (a positive integer) to represent the hatred level between any two criminals; the higher the resentment value $c$, the greater the grudge between the two criminals. If two criminals with resentment value $c$ are detained in the same prison, they will inevitably clash, causing a conflict with an impact level of $c$.\n\nAt the end of each year, the police department compiles a list of all the conflicts within the prison during the year, ordered from highest to lowest impact level, and submits it to Z, the mayor of city S. Busy with government affairs, Mayor Z only reviews the impact level of the first event on the list. If the impact is particularly high, he may consider replacing the police chief.\n\nAfter studying the relationships among these $N$ criminals in detail, the police chief feels enormous pressure. He plans to reallocate the criminals between the two prisons to minimize the impact level of the largest conflict Mayor Z sees, thus safeguarding his position. Assuming that if two criminals in the same prison harbor resentment towards each other, conflicts will occur at some point during the year. How should the criminals be allocated to ensure Mayor Z sees the smallest conflict impact level? What is this minimum value?\n\n---\n\n### Input Format\nEach line of the input separates two numbers by a space.\n\n- The first line contains two positive integers $N$ and $M$, representing the number of criminals and the number of pairs of criminals with resentment, respectively.\n- The next $M$ lines each contain three positive integers $a_j, b_j, c_j$, indicating that criminal $a_j$ and criminal $b_j$ harbor resentment with a resentment value of $c_j$. The data guarantees that $1 \\leq a_j < b_j \\leq N$, $0 < c_j \\leq 1,000,000,000$, and each pair of criminals appears only once.\n\n---\n\n### Output Format\nOutput consists of $1$ line, representing the impact level of the conflict event seen by the mayor.\n\nIf no conflicts occur within the prisons during the year, output $0$.\n\n---\n\n### Example\nThe resentment values between criminals are shown in the left diagram below. The allocation of criminals is shown in the right diagram. The conflict event with the highest impact level seen by the mayor is $3512$ (triggered by criminals $2$ and $3$). Any other allocation would not yield a better result.\n\n![298.png.jpg](https://i.loli.net/2018/05/22/5b03db0916ac8.jpg)\n\n---\n\n### Data Range and Hints\n- For $30\\%$ of the data, $N \\leq 15$.\n- For $70\\%$ of the data, $N \\leq 2,000$, $M \\leq 50,000$.\n- For $100\\%$ of the data, $N \\leq 20,000$, $M \\leq 100,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2307, "prompt": "### Problem Description\n\"Clone Technique!\" \u2014 Little $P$\n\nThere are $n$ clones of Little $P$ scattered across a plane. The area occupied by a group of clones is defined as the smallest convex polygon that encloses these clones. Little $P$ is limited in ability, and at every moment, some clones will disappear. However, before the next moment, Little $P$ performs:\n\n\"Clone Technique!\"\n\nto make the disappeared clones reappear at their original positions. Little $P$ wants to know the area occupied by the remaining clones each moment after some clones disappear.\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, representing the initial number of clones and the number of moments. \nThe next $n$ lines each contain two integers $x_i$, $y_i$, describing the position of the $i$-th clone. \nThe next $m$ lines each contain the first integer $k$, representing the number of clones that disappear at this moment, followed by $k$ non-negative integers $c_1$, $c_2$, ..., $c_k$, which are used to generate the indices of the disappearing clones. \n\nThe indices of the disappearing clones $p_1$, $p_2$, ..., $p_k$ are calculated as follows:\nLet the twice of the area occupied by the clones in the previous moment be $S$. Then the indices of the disappearing clones are calculated as:\n\n$$\np_i = [(S + c_i) \\bmod n] + 1\n$$\n\nSpecially, at the first moment, we consider $S = -1$, i.e., the indices of the disappearing clones are calculated as:\n\n$$\np_i = [(-1 + c_i) \\bmod n] + 1\n$$\n\n---\n\n### Output Format\nFor each moment, output $m$ lines, each containing a single integer representing twice the area occupied by the remaining clones.\n\n---\n\n### Example\nAs shown in the diagram below: \nThe left image represents the positions of the $6$ clones and the area they occupy. \nThe middle image represents the situation at the first moment, where the indices of the disappearing clones are $1, 3, 6$, and the remaining $3$ clones occupy the region marked by the solid lines within the area, yielding twice the area as $3$.\n\nThe right image represents the situation at the second moment, where the indices of the disappearing clones are calculated as: \n\n$$\n[(0 + 3) \\bmod 6] + 1 = 4\n$$\n\n$$\n[(1 + 3) \\bmod 6] + 1 = 5\n$$\n\nThe remaining $4$ clones occupy the region marked by the solid lines within the area.\n\n![TIM\u56fe\u724720170721203208.png](https://i.loli.net/2017/07/21/5971f489dcfb9.png)\n\n---\n\n### Data Constraints and Hints\nFor all data, it is guaranteed:\n\n- $|x_i| ,|y_i| \\leq 10^8$\n- No two clones have the exact same coordinates.\n- $k \\leq 100$\n- The sum of all $k$ across all moments does not exceed $2 \\times 10^6$.\n- $0 \\leq c_i \\leq 2^{31} - 1$\n- Initially, the area occupied by all clones is greater than $0$.\n- Define the **vertex set** of the area occupied by all $n$ clones as $S$, where $S \\geq 3$. At any moment, there are at least two clones from $S$ that have not disappeared.\n\nDue to the 64-bit operating system's pointer size of 8 bytes, the LOJ platform increases the memory limit to $768 \\mathrm{MB}$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2352, "prompt": "### Problem Description\nIn the study of social networks, graph theory concepts are often used to analyze social phenomena. Consider the following problem: \nIn a social circle with $n$ individuals, there are varying degrees of relationships between people. This relationship network can be represented as an undirected graph with $n$ nodes. If two different individuals know each other, there is an undirected edge between their corresponding nodes, assigned a positive weight $c$, where smaller values of $c$ indicate closer relationships. The shortest path between two nodes $s$ and $t$ is used to measure the closeness of the relationship between individuals $s$ and $t$. It is noteworthy that other nodes on the shortest path provide some form of convenience for the connection between $s$ and $t$, making these nodes somewhat important in their interaction. The importance degree of a node in the social network can be measured by counting the number of shortest paths passing through that node. \n\nConsidering that there might be multiple shortest paths between two nodes $A$ and $B$, we modify the definition of importance degree as follows: \nLet $C_{s,t}$ be the total number of different shortest paths from $s$ to $t$, and $C_{s,t}(v)$ be the number of those shortest paths that pass through a node $v$. The importance degree of node $v$ in the social network is then defined as:\n\n$$ I(v)=\\sum_{s \\ne v,t\\ne v} \\frac{C_{s,t}(v)}{C_{s,t}} $$\n\nTo ensure that $I(v)$ and $C_{s,t}(v)$ are well-defined, we assume that the social network is always represented by a connected undirected graph, meaning every pair of nodes has a finite shortest path in between. Given such a weighted undirected graph, your task is to calculate the importance degree for each node.\n\n### Input Format\nThe first line of input contains two integers $n$ and $m$, representing the number of nodes and edges in the social network. \nThe graph has nodes numbered from $1$ to $n$. \nThe following $m$ lines each describe an undirected edge with three integers $a$, $b$, and $c$, indicating there is an edge connecting node $a$ and node $b$ with a weight of $c$. \nNote that there is at most one edge between any two nodes, and the graph does not contain self-loops (i.e., no edge connects a node to itself).\n\n### Output Format\nThe output consists of $n$ lines, each containing a real number rounded to three decimal places. The $i$-th line contains the importance degree of node $i$ in the social network.\n\n### Sample\nThe social network is illustrated below.\n\n![dd(5).png](https://i.loli.net/2018/02/12/5a81453871c94.png)\n\nFor node $1$, only the shortest paths from node $2$ to node $4$ and from node $4$ to node $2$ pass through node $1$. There are $2$ shortest paths between node $2$ and node $4$. Hence, the importance degree of node $1$ is calculated as $\\frac{1}{2} + \\frac{1}{2} = 1$. Due to the symmetry of the graph, the importance degrees of the other three nodes are also $1$.\n\n### Constraints and Notes\n- For $50\\%$ of the test cases: $n \\leq 10 , m \\leq 45$. \n- For $100\\%$ of the test cases: $n \\leq 100 , m \\leq 4500$, and the weight $c$ of any edge is a positive integer such that $1 \\leqslant c \\leqslant 1000$. \n- It is guaranteed that the given undirected graph is connected, and that the number of shortest paths between any two nodes does not exceed $10^{10}$. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2605, "prompt": "### Problem Description\nFind the smallest positive integer solution $x_0$ to the congruence equation $ax \\equiv 1 \\pmod{b}$.\n\n### Input Format\nThe input consists of a single line containing two positive integers $a$ and $b$, separated by a space.\n\n### Output Format\nThe output consists of a single line containing the smallest positive integer solution $x_0$. It is guaranteed that a solution always exists for the given input.\n\n### Example\n\n### Data Range and Hints\n- For 40% of the test cases, $2 \\leq b \\leq 1\\,000$;\n\n- For 60% of the test cases, $2 \\leq b \\leq 50\\,000\\,000$;\n\n- For 100% of the test cases, $2 \\leq a, b \\leq 2\\,000\\,000\\,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2600, "prompt": "### Problem Description\n\nT is a quality inspector responsible for assessing the quality of a batch of minerals. This batch contains $n$ mineral stones numbered sequentially from $1$ to $n$. Each stone has its own weight $w_i$ and value $v_i$. The mineral assessment process includes the following steps:\n\n1. $m$ intervals $[L_i, R_i]$ are given;\n2. Choose a parameter $W$;\n3. For an interval $[L_i, R_i]$, calculate the inspection value $Y_i$ for the mineral stones in this interval:\n\n$$Y_i=\\sum_j 1 \\cdot \\sum_j v_j, \\quad j \\in [L_i, R_i], w_j \\geq W$$\n\nwhere $j$ is the index of the stones.\n\nThe inspection result $Y$ for the entire batch of minerals is the sum of the inspection values across all intervals, which is:\n\n$$Y=\\sum_{i=1}^m Y_i$$\n\nIf the inspection result deviates too much from the given standard value $S$, another batch of minerals will need to be inspected.\n\nT wants to avoid spending time inspecting another batch of minerals. Therefore, he wants to adjust the value of parameter $W$ such that the inspection result gets as close to the standard value $S$ as possible, i.e., minimize $|S-Y|$. Please help T find this minimum value.\n\n---\n\n### Input Format\n\nThe first line contains three integers $n$, $m$, and $S$, which represent the number of mineral stones, the number of intervals, and the standard value, respectively.\n\nThe next $n$ lines each contain $2$ integers separated by a space: the $i+1$-th line represents the weight $w_i$ and value $v_i$ of the $i$th mineral stone.\n\nThe following $m$ lines each contain $2$ integers separated by a space: the $i+n+1$-th line represents the two endpoints $L_i$ and $R_i$ of the interval $[L_i, R_i]$.\n\n**Note**: Different intervals may overlap or intersect with one another.\n\n---\n\n### Output Format\n\nThe output contains only one line: a single integer representing the minimum value of $|S-Y|$.\n\n---\n\n### Example\n\nWhen $W$ is set to $4$, the inspection values for the three intervals are $20$, $5$, and $0$, respectively. The inspection result for this batch of minerals is $25$. In this case, the minimum deviation from the standard value $S$ is $10$.\n\n---\n\n### Constraints and Hints\n\n- For $10\\%$ of the test cases, $n, m \\leq 10$; \n- For $30\\%$ of the test cases, $n, m \\leq 500$; \n- For $50\\%$ of the test cases, $n, m \\leq 5,000$; \n- For $70\\%$ of the test cases, $n, m \\leq 10,000$; \n- For $100\\%$ of the test cases, $1 \\leq n, m \\leq 200,000$, $0 < w_i, v_i \\leq 10^6$, $0 < S \\leq 10^{12}$, $1 \\leq L_i \\leq R_i \\leq n$. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2353, "prompt": "### Problem Description \nXiao $Y$ recently started working at a voucher trading exchange. This exchange only trades two types of vouchers: $A$ commemorative vouchers (hereafter referred to as $A$ vouchers) and $B$ commemorative vouchers (hereafter referred to as $B$ vouchers). Each customer who owns vouchers has their own account. The number of vouchers can be a real number. \n\nWith daily market fluctuations, the two types of vouchers have their respective values, i.e., the amount in RMB that can be exchanged per unit of voucher on a given day. We record the value of $A$ and $B$ vouchers on the $K$th day as $A_K$ and $B_K$ (RMB/unit voucher). To facilitate customer transactions, the voucher trading exchange provides a very convenient trading method called proportional trading. Proportional trading has two aspects: \n- Selling vouchers: Customers provide a real number $\\text{OP}$ within the range $[0,100]$, representing a selling percentage. This percentage means that $\\text{OP}\\%$ of their $A$ and $\\text{OP}\\%$ of their $B$ vouchers will be sold for RMB at the current value. \n- Buying vouchers: Customers pay $\\text{IP}$ RMB, and the exchange will provide vouchers with a total value of $\\text{IP}$ RMB. Moreover, the proportion of $A$ and $B$ vouchers given to the customer on the $K$th day must be exactly $\\text{Rate}_K$. \n\nFor example, consider the following changes in $A_K$, $B_K$, and $\\text{Rate}_K$ over the next 3 days: \n\n![dd(1).png](https://i.loli.net/2018/02/12/5a8146be1354d.png) \n\nAssume that on the first day, the customer has $100$ RMB but no vouchers. The customer can perform the following operations: \n\n![dd(2).png](https://i.loli.net/2018/02/12/5a8146be23a4c.png) \n\nNote that multiple operations can be performed on the same day. Xiao $Y$, being an economically savvy employee, has measured market trends over a long period and determined the values of $A$ and $B$ vouchers as well as $\\text{Rate}$ over the next $N$ days. He hopes to calculate how much money he can maximize after $N$ days if he starts with $S$ RMB initially. \n\n---\n\n### Input Format \nThe first line contains two positive integers, $N$ and $S$, representing the number of days Xiao $Y$ can forecast and the initial amount of money. \nThe next $N$ lines each contain three real numbers, $A_K$, $B_K$, and $\\text{Rate}_K$, as described in the problem statement. \n\n---\n\n### Output Format \nOutput one real number, $\\text{MaxProfit}$, representing the maximum amount of money that can be obtained at the end of the $N$th day. The answer is considered correct if the absolute error between it and the standard answer is no greater than $10^{-3}$. \n\n---\n\n### Example \n![dd(3).png](https://i.loli.net/2018/02/12/5a8146be2d7a6.png) \n\n---\n\n### Constraints and Tips \n#### Constraints \n- For $40\\%$ of the test cases, $N \\leq 10$. \n- For $60\\%$ of the test cases, $N \\leq 1000$. \n- For $100\\%$ of the test cases: \n - $1 \\leq N \\leq 10^5$ \n - $0 < A_K \\leq 10$ \n - $0 < B_K \\leq 10$ \n - $0 < \\text{Rate}_K \\leq 100$ \n - $\\text{MaxProfit} \\leq 10^9$. \n\n#### Tips \n- The input file may be very large; please use a fast input method. \n- There is always an optimal buy-sell strategy that satisfies: spend all available RMB in each buy operation; sell all vouchers in each sell operation. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2446, "prompt": "### Problem Description\nNOI2011 has begun at Jilin University! To welcome the most outstanding informatics contestants from all over the country, Jilin University decided to host two grand carnival events for the NOI. These events will be held in two different locations. Each carnival may include many activities, but each activity can only be held at one carnival.\n\nNow, the organizer Xiao An has received applications for hosting a total of $n$ activities, where the starting time of the $i$-th activity is $S_i$, and its duration is $T_i$. These activities can be arranged in either of the carnival venues or can be left unarranged.\n\nAfter extensive investigation, Xiao An discovered that if, at a certain time, two carnival venues have simultaneous ongoing activities (excluding the start and end moments of activities), some contestants might feel conflicted about which venue to attend, which would make them unhappy. To avoid such unpleasant scenarios, Xiao An requires that no two activities occur simultaneously at both venues (activities within the same venue can overlap freely).\n\nFurthermore, if one carnival venue has too few activities, its appeal will diminish, leading to a dull atmosphere. Thus, Xiao An wishes to arrange the activities in a reasonable manner so that the maximum number of activities in the carnival with the fewer activities is as large as possible.\n\nIn addition, some activities are especially meaningful and must be held. Xiao An wants to know, given that the $i$-th activity must be held (it can be arranged at either of the two carnival venues), what the maximum number of activities is in the carnival with fewer activities.\n\n---\n\n### Input Format\nThe first line of the input contains an integer $n$, representing the number of activities applied for.\n\nThe next $n$ lines describe all activities, where the $i$-th line contains two integers $S_i$ and $T_i$, denoting that the $i$-th activity starts at time $S_i$ and lasts for $T_i$ units of time.\n\n---\n\n### Output Format\nThe first line of the output contains a single integer, denoting the maximum number of activities in the carnival with fewer activities under optimal arrangements without any restrictions.\n\nThe next $n$ lines each contain one integer, with the $i$-th line representing the maximum number of activities in the carnival with fewer activities under the condition that the $i$-th activity must be arranged (it can be held in either of the two carnivals).\n\n---\n\n### Example\nWithout any restrictions, an optimal arrangement can place activities $1$ and $4$ in one carnival, and activities $3$ and $5$ in the other carnival, while activity $2$ is left unarranged.\n\n---\n\n### Data Constraints and Notes\nFor $10\\%$ of the test cases, $n \\le 10$. \nFor $30\\%$ of the test cases, $n \\le 40$. \nFor all test cases, $1 \\le n \\le 200, 0 \\le S_i \\le 10^9$, $1 \\le T_i \\le 10^9$. \n\nFor a single test case:\n* If the output format is incorrect (e.g., fewer than $n+1$ lines are output), the score is $0$.\n* If the first line in the output file is incorrect and at least one of the subsequent $n$ lines is incorrect, the score is $0$.\n* If the first line in the output file is correct, but at least one of the subsequent $n$ lines is incorrect, the score is $4$.\n* If the first line in the output file is incorrect, but all of the subsequent $n$ lines are correct, the score is $6$.\n* If all $n+1$ lines in the output file are correct, the score is $10$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2318, "prompt": "### Problem Description\n\nXiaoming, who is participating in an archaeological excavation, has obtained a treasure map. This treasure map marks $n$ treasure houses buried deep underground, as well as $m$ roads that can potentially be developed between the treasure houses, and their respective lengths.\n\nXiaoming is determined to personally excavate the treasures from all of the treasure houses. However, each treasure house is located far beneath the ground, meaning that building an access road from the surface to a specific treasure house is very challenging. In contrast, developing roads between treasure houses is relatively easier.\n\nXiaoming\u2019s determination impressed the sponsors of the archaeological excavation. The sponsors have decided to sponsor the development of a single road from the surface to one particular treasure house for free. Xiaoming can decide which treasure house this free road will lead to.\n\nWith this sponsorship, Xiaoming must also determine how to develop the roads between the treasure houses. Any road that has been developed can be used freely without incurring additional costs. Excavating a new road allows Xiaoming and the archaeological team to excavate treasures from all treasure houses that can be reached through that newly developed road. Furthermore, Xiaoming does not wish to develop unnecessary roads, meaning that a road between two treasure houses that have both already been excavated does not need to be developed.\n\nThe cost of developing a new road is calculated as follows:\n\n$$\n\\text{Cost} = \\text{Length of the road} \\times \\text{Number of treasure houses passed from the surface-connected treasure house to the starting treasure house of the new road (inclusive)}.\n$$\n\nWrite a program to help Xiaoming determine which treasure house should be connected to the surface by the sponsor and which roads to develop between treasure houses, so that the total cost of the project is minimized. Output the minimum total cost.\n\n---\n\n### Input Format\n\nThe first line contains two space-separated positive integers, $n$ and $m$, representing the number of treasure houses and the number of potential roads, respectively.\n\nThe next $m$ lines each contain three space-separated positive integers, specifying the two treasure houses connected by a road (numbered $1$ to $n$) and the length $v$ of the road.\n\n---\n\n### Output Format\n\nOutput a single positive integer representing the minimum total cost.\n\n---\n\n### Sample 1\n![treasure1.png](https://img.loj.ac.cn/2021/12/29/7de6a14844bf1.png)\n\n---\n\n### Sample 2\n![treasure2.png](https://img.loj.ac.cn/2021/12/29/984854de117a3.png)\n\n---\n\n### Constraints and Notes\n\n- For $20\\%$ of the test cases:\n - The input forms a tree.\n - $1 \\leq n \\leq 8$, $v \\leq 5000$ and all $v$ are equal.\n \n- For $40\\%$ of the test cases:\n - $1 \\leq n \\leq 8$, $0 \\leq m \\leq 1000$, $v \\leq 5000$ and all $v$ are equal.\n \n- For $70\\%$ of the test cases:\n - $1 \\leq n \\leq 8$, $0 \\leq m \\leq 1000$, $v \\leq 5000$.\n \n- For $100\\%$ of the test cases:\n - $1 \\leq n \\leq 12$, $0 \\leq m \\leq 1000$, $v \\leq 500000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2591, "prompt": "### Problem Description\n\nXiaocheng and Xiaohua are both students who love mathematics. Recently, they have coincidentally become fascinated with Sudoku games. Being competitive, they want to use Sudoku as a way to challenge each other. However, ordinary Sudoku is too simple for them. Therefore, they sought advice from Dr. Z, who came up with his newly invented \"Target-shaped Sudoku\" as the challenge for these two children.\n\nThe grid of Target-shaped Sudoku is the same as that of normal Sudoku. It consists of a $9 \\times 9$ grid containing $9$ smaller $3 \\times 3$ subgrids (separated by bold black lines). In this large $9 \\times 9$ grid, some of the numbers are already given. Using logical reasoning and the given numbers, players need to fill in the other blank cells with numbers from $1$ to $9$. Each number cannot appear more than once in any $3 \\times 3$ subgrid, row, or column.\n\nHowever, there is one difference between Target-shaped Sudoku and normal Sudoku: each cell has a score, and the closer the cell is to the center of the grid, the higher its score (as shown in the diagram below).\n\n![28.png](https://i.loli.net/2018/05/22/5b03d2988a44a.png)\n\nThe detailed score distribution for the cells is as follows: the innermost cell (yellow region) is worth $10$ points. The ring outside the yellow region (red) has cells each worth $9$ points. The outer ring (blue) has cells worth $8$ points each. Another ring outside (brown) has cells worth $7$ points each. Finally, the outermost ring (white) has cells worth $6$ points each, as illustrated in the diagram.\n\nThe competition requires every participant to complete a given Sudoku puzzle (each Sudoku may have multiple valid solutions) and try to achieve the highest possible total score. The total score is calculated as the product of the score of a cell and the number filled in that cell, summed over all cells.\n\nAs shown in the example below, the total score for the Target-shaped Sudoku game filled in is $2829$. According to the game\u2019s rules, the winner is determined by the highest total score.\n\n![29.png](https://i.loli.net/2018/05/22/5b03d2989aa46.png)\n\nAnxious to win, Xiaocheng turns to you, a skilled programmer, for help. He asks you to determine the maximum score that can be achieved for a given Target-shaped Sudoku puzzle.\n\n---\n\n### Input Format\n\nThe input consists of $9$ lines, each containing $9$ integers (each integer in the range $0$\u2013$9$), representing a partially filled Sudoku grid. Blank cells are denoted by $0$. Each pair of numbers within the same line is separated by a single space.\n\n---\n\n### Output Format\n\nOutput a single line.\n\nThe output should be the highest possible score for the given Target-shaped Sudoku puzzle. If the Sudoku puzzle has no solution, output the integer $-1$.\n\n---\n\n### Sample Input 1\n\n```\n\n```### Sample Output 1\n\n```\n\n```\n\n---\n\n### Sample Input 2\n\n```\n\n```\n\n### Sample Output 2\n\n```\n\n```\n\n---\n\n### Constraints and Hints\n\n- For $40\\%$ of the test cases, the number of non-zero numbers in the Sudoku grid is no less than $30$.\n- For $80\\%$ of the test cases, the number of non-zero numbers in the Sudoku grid is no less than $26$.\n- For $100\\%$ of the test cases, the number of non-zero numbers in the Sudoku grid is no less than $24$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2443, "prompt": "### Problem Description\nThe new Intelligent Vehicle Competition has started at JL University! The competition track can be viewed as being composed of $n$ rectangular regions joined together (as shown in the diagram below). Each rectangle has edges parallel to the coordinate axes, and the $i$-th rectangle's bottom-left and top-right corner coordinates are $(x_{i,1}, y_{i,1})$ and $(x_{i,2}, y_{i,2})$, respectively.\n\nIt is guaranteed that $x_{i,1} < x_{i,2} = x_{i+1,1}$, and $y_{i,1} < y_{i,2}$. Two adjacent rectangles will always overlap along an edge (as shown by the dotted lines in the diagram), allowing the intelligent vehicle to traverse between rectangles through this shared area.\n\n![](https://i.loli.net/2018/06/10/5b1d382b37cb5.png)\n\nThe participants are required to design an algorithm for their intelligent vehicle such that it can travel from a given starting point $S$ to a given endpoint $T$ in the shortest possible time, without leaving the track. Assume that the vehicle moves at a constant speed $v$ and turning does not consume any time. Can you calculate the shortest time needed for the vehicle to complete the race?\n\n### Input Format\nThe first line contains a positive integer $n$, indicating the number of rectangles that make up the track.\n\nThe next $n$ lines describe the rectangles. The $i$-th line contains $4$ integers: $x_{i,1}, y_{i,1}, x_{i,2}, y_{i,2}$, which represent the bottom-left and top-right corner coordinates of the $i$-th rectangle as $(x_{i,1}, y_{i,1})$ and $(x_{i,2}, y_{i,2})$.\n\nThe next line contains two integers $x_S$ and $y_S$, indicating the coordinates of the starting point.\n\nThe next line contains two integers $x_T$ and $y_T$, indicating the coordinates of the endpoint.\n\nThe final line contains a real number $v$ ($1 \\leq v \\leq 10$), representing the speed of the intelligent vehicle.\n\n### Output Format\nOutput a single real number, accurate to at least six decimal places, representing the minimum time required for the intelligent vehicle to complete the race.\n\nFor each test case, if the absolute difference between your output and the reference solution is no greater than $10^{-6}$, you will receive full points for that test case; otherwise, you will receive zero points.\n\n### Example\n\n#### Input\n```\n2\n0 0 2 3\n2 1 5 4\n1 2\n4 3\n5\n```#### Output\n```\n0.728738\n```\n\n### Constraints and Hints\n- For $10\\%$ of the cases, $n \\leq 1$.\n- For $30\\%$ of the cases, $n \\leq 5$.\n- For $60\\%$ of the cases, $n \\leq 200$.\n- For $100\\%$ of the cases, $n \\leq 2000$.\n\nAll coordinates are integers, and their absolute values do not exceed $40000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2593, "prompt": "### Problem Description\nOn his birthday, Xiao Ming received a Turtle Board Game as a gift from his dad.\n\nThe turtle game board consists of a row of $N$ cells, each containing a score (non-negative integer). The first cell on the board is the unique starting point, and the $N$th cell is the endpoint. The game requires the player to control a turtle piece that starts at the first cell and moves all the way to the last cell.\n\nThe game features $M$ crawling cards, divided into $4$ different types (not all $4$ types of cards need to be present among the $M$ cards, as shown in the examples). Each type of card is marked with one of the numbers $1$, $2$, $3$, or $4$, indicating that the turtle piece will crawl forward by the corresponding number of cells when using that card. In the game, the player must select one unused crawling card from all available crawling cards each time, controlling the turtle piece to move forward by the number of cells indicated on the card. Each card can only be used once.\n\nThe turtle piece automatically obtains the score of the starting cell and, in subsequent crawling, gains the score of each cell it reaches. The player's final score is the total score collected by the turtle piece as it moves from the start to the endpoint.\n\nClearly, different sequences of using the crawling cards will result in different final scores. Xiao Ming wants to find a sequence of card usage that maximizes his final score.\n\nNow, given the scores of all cells on the board and all the crawling cards, can you help Xiao Ming calculate the maximum score he can achieve?\n\n---\n\n### Input Format\nEach line in the input file separates two numbers with a single space.\n\n- The first line contains $2$ positive integers $N$ and $M$, representing the number of cells on the board and the number of crawling cards, respectively.\n- The second line contains $N$ non-negative integers, $a_1, a_2, \\cdots\\cdots, a_N$, where $a_i$ represents the score in the $i$th cell on the board.\n- The third line contains $M$ integers, $b_1, b_2, \\cdots\\cdots, b_M$, representing the numbers on the $M$ crawling cards.\n\nThe input guarantees that exactly all $M$ crawling cards are used and the turtle piece arrives at the endpoint, i.e., $N \u2212 1 = \\sum\\limits_{i=1}^M{b_i}$.\n\n---\n\n### Output Format\nThe output consists of exactly $1$ line, containing $1$ integer, which represents the maximum score Xiao Ming can achieve.\n\n---\n\n### Example 1\nXiao Ming uses the crawling cards in the order $1, 1, 3, 1, 2$ and achieves a score of $6+10+14+8+18+17=73$.\n\nNote that since the starting point is $1$, Xiao Ming automatically gains the score of the first cell, $6$.\n\n---\n\n### Example 2\n\n---\n\n### Constraints and Notes\n- For $30\\%$ of cases: $N \\leq 30$, $M \\leq 12$;\n- For $50\\%$ of cases: $N \\leq 120$, $M \\leq 50$, and no more than $20$ cards for each of the $4$ types;\n- For $100\\%$ of cases: $1 \\leq N \\leq 350$, $1 \\leq M \\leq 120$, and no more than $40$ cards for each of the $4$ types; $0 \\leq a_i \\leq 100$, $1 \\leq i \\leq N$; $1 \\leq b_i \\leq 4$, $1 \\leq i \\leq M$.\n\nThe input guarantees $N \u2212 1 = \\sum\\limits_{i=1}^M{b_i}$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2951, "prompt": "### Problem Statement\n\nIn the land of netizens, there are $n$ different denominations of currency, where the denomination of the $i$-th type of currency is $a[i]$. You may assume that there is an infinite number of each type of currency. To simplify notation, the currency system with $n$ types and denomination array $a[1 \\dots n]$ is written as $(n,a)$.\n\nIn a complete currency system, every non-negative integer amount $x$ should be representable. That is, for every non-negative integer $x$, there exist $n$ non-negative integers $t[i]$ such that the sum of $a[i] \\times t[i]$ equals $x$. However, in the land of netizens, the currency system may be incomplete, meaning there might be some amounts $x$ that cannot be represented in that system. For example, in the currency system $n = 3$, $a = [2, 5, 9]$, amounts $1, 3$ cannot be represented.\n\nTwo currency systems $(n,a)$ and $(m,b)$ are considered equivalent if and only if, for any non-negative integer $x$, it is either representable in both currency systems or unrepresentable in both.\n\nThe netizens want to simplify their currency system. They are looking for a currency system $(m,b)$ that is equivalent to the original currency system $(n,a)$, with $m$ being as small as possible. Your task is to assist them in finding the smallest $m$.\n\n---\n\n### Input Format\n\nThe input file name is `money.in`. \nThe first line of the input contains an integer $T$, representing the number of test cases. \nFor each test case, the first line contains a positive integer $n$. \nThe following line contains $n$ positive integers $a[i]$, separated by spaces.\n\n---\n\n### Output Format\n\nThe output file name is `money.out`. \nThe output file contains $T$ lines. For each test case, output one line with a single positive integer, representing the smallest $m$ among all currency systems $(m,b)$ that are equivalent to $(n,a)$.\n\n---\n\n### Example\n\n#### Input:\n```\n2\n3\n2 5 9\n5\n1 2 3 4 5\n```#### Output:\n```\n2\n5\n```\n\n#### Explanation:\n\nFor the first test case, the currency system $(2, [3,10])$ is equivalent to the given currency system $(n,a)$. It can be verified that there does not exist $m < 2$ that results in an equivalent currency system. Thus, the answer is $2$.\n\nFor the second test case, it can be verified that there does not exist $m < n$ resulting in an equivalent currency system. Thus, the answer is $5$.\n\n---\n\n### Constraints & Notes\n\n| Test Point ID | $n$ | $a[i]$ |\n| :-----------: | :-------: | :-----------------: |\n| $1\\sim 3$ | $=2$ | $\\leq 10^3$ |\n| $4\\sim 6$ | $=3$ | $\\leq 10^3$ |\n| $7,\\ 8$ | $=4$ | $\\leq 10^3$ |\n| $9,\\ 10$ | $=5$ | $\\leq 10^3$ |\n| $11\\sim 13$ | $\\leq 13$ | $\\leq 16$ |\n| $14\\sim 16$ | $\\leq 25$ | $\\leq 40$ |\n| $17\\sim 20$ | $\\leq 100$| $\\leq 2.5 \\times 10^4$ |\n\nFor all test cases, $1 \\leq T \\leq 20$, $n,a[i] \\geq 1$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2249, "prompt": "### Problem Description\nThis summer, NOI celebrates its 30th anniversary in SZ City. OIers from $n$ cities across the country will depart and travel to SZ City to participate in this grand event.\n\nThe cities across the country form a rooted tree with SZ City as the root. Each city is connected to its parent via a road. For convenience, we number the $n$ cities with integers from $1$ to $n$, where SZ City is numbered as $1$. For any city $v$ other than SZ City, its parent city $f_v$ and the length of the road connecting to its parent city $s_v$ are given.\n\nTo travel from city $v$ to SZ City, an OIer can follow these steps: choose an ancestor city $a$, pay the ticket price, and use public transport to reach $a$. Then choose an ancestor city $b$ of $a$, pay the ticket price again, and travel to $b$. Repeat this process until reaching SZ City.\n\nFor any city $v$, there is a distance limit $l_v$ for the transportation method. For an ancestor $a$ of city $v$, if the total distance of all roads between $v$ and $a$ exceeds $l_v$, then the OIer cannot reach $a$ in a single trip. Otherwise, $v$ can reach $a$ in one ticket purchase. Additionally, for each city $v$, two non-negative integers $p_v$ and $q_v$ are given as ticket price parameters. If the total distance between city $v$ and city $a$ is $d$, the ticket price for traveling from $v$ to $a$ is calculated as $dp_v+q_v$.\n\nOIers in every city want to minimize their total ticket expenses when they travel to SZ City. Your task is to determine the minimum total ticket cost for the OIers in each city.\n\n---\n\n### Input Format\nThe first line contains two non-negative integers $n$ and $t$, representing the number of cities and the type of data (the meaning of $t$ will be explained later). \nThe second to $n$th lines of the input describe cities other than SZ City. Line $v$ contains five non-negative integers $f_v, s_v, p_v, q_v, l_v$, which represent the parent city of city $v$, the length of the road to the parent city, the two ticket price parameters, and the transportation distance limit, respectively.\n\n**Note**: The input does not contain SZ City numbered $1$. Lines $2$ to $n$ describe cities $2$ to $n$.\n\n---\n\n### Output Format\nThe output should contain $n-1$ lines, each with a single integer. Line $v$ corresponds to the minimum ticket cost required for traveling from city $v+1$ to SZ City.\n\nSimilarly, **note**: The output does not contain SZ City numbered $1$.\n\n---\n\n### Example\n\n---\n\n### Constraints and Notes\nFor all data:\n- $n \\leq 2 \\times 10^5$ \n- $0 \\leq p_v \\leq 10^6$ \n- $0 \\leq q_v \\leq 10^{12}$ \n- $1 \\leq f_v < v$ \n- $0 < s_v \\leq l_v \\leq 2 \\times 10^{11}$ \n- The total road distance from any city to SZ City does not exceed $2 \\times 10^{11}$.\n\nThe input parameter $t$ represents the type of data: \n- When $t = 0$ or $2$, for all cities $v$, $f_v = v-1$, which means all cities form a chain leading to SZ City. \n- When $t = 0$ or $1$, for all cities $v$, $l_v = 2 \\times 10^{11}$, meaning there is no distance restriction, and every city can reach all its ancestors. \n- When $t = 3$, the data has no special properties.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2361, "prompt": "### Problem Description\n\nThe combination number represents the number of ways to choose $ m $ items from $ n $ items. For example, selecting two items from the set $ (1, 2, 3) $ can yield three choices: $ (1, 2) $, $ (1, 3) $, $ (2, 3) $.\n\nAccording to the definition of combination numbers, the general formula for calculating combinations can be expressed as:\n\n$$ C_n ^ m = \\frac{n!}{m!(n - m)!} $$\n\nwhere $ n! = 1 \\times 2 \\times \\cdots \\times n $.\n\nXiaocong wants to find out, given $ n $, $ m $, and $ k $, how many pairs of $ (i, j) $ for all $ 0 \\leq i \\leq n $ and $ 0 \\leq j \\leq \\min(i, m) $ satisfy that $ C_i ^ j $ is a multiple of $ k $.\n\n### Input Format\n\nThe first line contains two integers $ t $ and $ k $, where $ t $ represents the number of test datasets for this test case, and $ k $ represents the significance as described in the \"Problem Description.\"\n\nThe next $ t $ lines each contain two integers $ n $ and $ m $, where $ n $ and $ m $ are described in the \"Problem Description.\"\n\n### Output Format\n\nFor $ t $ lines, each line contains one integer representing the count of pairs $ (i, j) $ for all $ 0 \\leq i \\leq n $ and $ 0 \\leq j \\leq \\min(i, m) $ that satisfy $ C_i ^ j $ being a multiple of $ k $.\n\n### Sample 1\n\n### Sample 2\n\n### Constraints and Hints\n\n$ 3 \\leq n, m \\leq 2000, 2 \\leq k \\leq 21, 1 \\leq t \\leq 10000 $\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2245, "prompt": "### Problem Description\n\nTo inherit the true essence of calligraphy, Little E is determined to visit a hermit who resides deep in the magical forest.\n\nThe magical forest can be visualized as an undirected graph containing $N$ nodes and $M$ edges, where nodes are numbered $1, \\ldots, N$, and edges are numbered $1, \\ldots, M$. Initially, Little E starts at node $1$, while the hermit resides at node $N$. Little E must traverse the magical forest to reach the hermit.\n\nThe magical forest is inhabited by monsters. Whenever someone passes through an edge, the monsters on the edge attack them. Fortunately, two types of guardian spirits, type $A$ and type $B$, live at node $1$. Little E can harness their power to achieve her goal.\n\nAs long as Little E carries enough guardian spirits, the monsters will not launch an attack. Specifically, every edge $E_i$ in the undirected graph has two weights: $A_i$ and $B_i$. If Little E carries at least $A_i$ type $A$ guardian spirits and at least $B_i$ type $B$ guardian spirits, the monsters on this edge will not attack anyone passing through the edge. Only if no monster attacks Little E on any edge during her journey through the magical forest can she successfully reach the hermit.\n\nSince carrying guardian spirits is a cumbersome task, Little E wants to know the minimum total number of guardian spirits she needs to carry to successfully visit the hermit. The total number of guardian spirits is the sum of the number of type $A$ guardian spirits and type $B$ guardian spirits.\n\n---\n\n### Input Format\n\nThe first line contains two integers, $N$ and $M$, representing the undirected graph with $N$ nodes and $M$ edges. \n\nThe next $M$ lines, each containing four positive integers $X_i, Y_i, A_i, B_i$, describe the $i$-th undirected edge. Here $X_i$ and $Y_i$ are the labels of the two endpoints of the edge, and $A_i$ and $B_i$ are as described above. \n\n**Note**: The input data may contain duplicated edges and self-loops.\n\n---\n\n### Output Format\n\nOutput a single integer on one line: \nIf Little E can successfully visit the hermit, output the minimum total number of guardian spirits she needs to carry. \nIf it is impossible for Little E to visit the hermit, output ``-1`` (without quotes).\n\n---\n\n### Example 1\n\nIf Little E follows the path $1 \\rightarrow 2 \\rightarrow 4$, she needs to carry $19 + 15 = 34$ guardian spirits. \nIf Little E takes the path $1 \\rightarrow 3 \\rightarrow 4$, she needs to carry $17 + 17 = 34$ guardian spirits. \nIf Little E follows the path $1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4$, she needs to carry $19 + 17 = 36$ guardian spirits. \nIf Little E takes the path $1 \\rightarrow 3 \\rightarrow 2 \\rightarrow 4$, she needs to carry $17 + 15 = 32$ guardian spirits. \nTherefore, the minimum number of guardian spirits Little E needs to carry is $32$. \n\n#### Input:\n```\n4 5\n1 2 19 15\n1 3 17 17\n2 3 19 17\n2 4 15 15\n3 4 17 15\n```#### Output:\n```\n32\n```\n\n---\n\n### Example 2\n\nLittle E cannot travel from node $1$ to node $3$, so the output is ``-1``.\n\n#### Input:\n```\n3 2\n1 2 1 1\n2 2 2 2\n```\n\n#### Output:\n```\n-1\n```\n\n---\n\n### Constraints and Hints\n\n- For all datasets, $2 \\leq N \\leq 50000$, $0 \\leq M \\leq 100000$, $1 \\leq A_i, B_i \\leq 50000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2444, "prompt": "### Problem Description\nAli loves collecting all kinds of quirky and strange items, and recently he found an old-fashioned typewriter. This typewriter has only $28$ keys, printed with $26$ lowercase English letters and the letters ```B``` and ```P```. After studying the typewriter, Ali discovered how it works: \n- When a lowercase letter is input, the typewriter adds this letter to a groove (the groove must contain at least one letter before pressing ```P```). \n- When the ```B``` key is pressed, the last letter in the groove disappears. \n- When the ```P``` key is pressed, the typewriter prints all the letters in the groove onto the paper and starts a new line, but the letters in the groove remain unchanged (it is guaranteed that the groove contains at least one letter). \n\nFor example, if Ali inputs ```aPaPBbP```, the characters printed on the paper are as follows: \n```plain\na \naa \nab\n``` \n\nWe number the strings printed on the paper sequentially from $1$ to $n$. The typewriter has a very interesting feature: it hides a numeric keypad. When two numbers $(x, y)$ are input on the keypad (where $1 \\leq x, y \\leq n$), the typewriter displays the number of times the $x$-th printed string occurs within the $y$-th printed string.\n\nAli was excited when he discovered this feature, so he wants to write a program that can replicate it. Can you help him?\n\n### Input Format\nThe first line contains a string that represents the sequence of characters Ali inputs. \nThe second line contains an integer $m$, which represents the number of queries. \nThe next $m$ lines describe the queries input through the numeric keypad. Each line contains two integers $x$ and $y$, representing the $i$-th query $(x, y)$.\n\n### Output Format\nOutput $m$ lines, where the $i$-th line contains an integer representing the answer to the $i$-th query.\n\n### Example\n\n#### Input\n```plain\naPaPBbP\n2\n1 2\n1 3\n```#### Output\n```plain\n1\n1\n```\n\n### Constraints and Hints\nThe range and characteristics of all test data are as follows:\n\n| Test Case ID | Scale of $n$ | Scale of $m$ | String Length | Total Input Length (Number of characters in the first input line) | \n| :----------: | :---------------: | :---------------: | :----------------------------------: | :--------------------------------------------------------------: | \n| 1 | $ 1 \\leq n \\leq 100$ | $ 1 \\leq m \\leq 1000$ | - | $\\leq 100$ | \n| 2 | $ 1 \\leq n \\leq 100$ | $ 1 \\leq m \\leq 1000$ | - | $\\leq 100$ | \n| 3 | $ 1 \\leq n \\leq 1000$ | $ 1 \\leq m \\leq 10^4$ | Maximum individual length $\\leq 1000$, total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 4 | $ 1 \\leq n \\leq 1000$ | $ 1 \\leq m \\leq 10^4$ | Maximum individual length $\\leq 1000$, total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 5 | $ 1 \\leq n \\leq 10^4$ | $ 1 \\leq m \\leq 10^5$ | Total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 6 | $ 1 \\leq n \\leq 10^4$ | $ 1 \\leq m \\leq 10^5$ | Total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 7 | $ 1 \\leq n \\leq 10^4$ | $ 1 \\leq m \\leq 10^5$ | Total length $\\leq 10^5$ | $\\leq 10^5$ | \n| 8 | $ 1 \\leq n \\leq 10^5$ | $ 1 \\leq m \\leq 10^5$ | - | $\\leq 10^5$ | \n| 9 | $ 1 \\leq n \\leq 10^5$ | $ 1 \\leq m \\leq 10^5$ | - | $\\leq 10^5$ | \n| 10 | $ 1 \\leq n \\leq 10^5$ | $ 1 \\leq m \\leq 10^5$ | - | $\\leq 10^5$ | \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2955, "prompt": "### Problem Description\nThere are $n$ cities in Country Z, connected by $n-1$ bidirectional roads. Each bidirectional road connects two cities, ensuring that any two cities are reachable through one or more roads.\n\nThe Minister of Defense, Little Z, needs to station the army in these cities, subject to the following requirements:\n- A city can be stationed with an army or left unstated.\n- For any two cities directly connected by roads, at least one of them must be stationed with the army.\n- Stationing the army in a city incurs a cost. The cost of stationing in city $i$ is $p_i$.\n\nLittle Z quickly comes up with a plan to minimize the total cost of stationing the army. However, the king has proposed $m$ specific requirements, each specifying whether certain cities should or should not have armies stationed. Little Z needs to respond to each requirement. Specifically, for the $j$th requirement, if it is possible to satisfy the above stationing conditions under this requirement (without considering any other requirements), the minimum cost of the stationing plan subject to this requirement must be provided. If the $j$th requirement cannot be fulfilled, output $-1$. Please help Little Z solve this problem.\n\n### Input Format\nThe input file is named `defense.in`. \nThe first line contains two positive integers $n, m$ and a string $\\text{type}$, representing the number of cities, the number of requirements, and the data type. $\\text{type}$ is a string formed by an uppercase letter `A`, `B`, or `C` followed by a digit $1$, $2$, or $3$. It can help in partial scoring. You may not need to use this parameter. The exact meaning of this parameter is described in the \"Data Range and Hints\" section. \nThe second line contains $n$ integers $p_i$, representing the cost of stationing an army in city $i$. \nThe next $n-1$ lines each contain two positive integers $u, v$, representing a bidirectional road between cities $u$ and $v$. \nThe following $m$ lines each contain four integers $a, x, b, y$ ($a \\neq b$), representing the $j$th requirement. In the $j$th requirement, city $a$ must have $x$ armies stationed, and city $b$ must have $y$ armies stationed. The values of $x$ and $y$ can only be $0$ or $1$: if $x = 0$, city $a$ cannot have an army stationed; if $x = 1$, city $a$ must have an army stationed. Similarly, if $y = 0$, city $b$ cannot have an army stationed; if $y = 1$, city $b$ must have an army stationed.\n\nIn the input file, adjacent data elements in each line are separated by a single space.\n\n### Output Format\nThe output file is named `defense.out`. \nOutput $m$ lines, each containing one integer. The $j$th line represents the minimum cost of stationing the army while satisfying the king's $j$th requirement. If the king's $j$th requirement cannot be satisfied, output $-1$.\n\n### Example\nFor the first requirement, the minimum cost is incurred when armies are stationed in cities $4$ and $5$.\n\nFor the second requirement, the minimum cost is incurred when armies are stationed in cities $1$, $2$, and $3$.\n\nThe third requirement cannot be satisfied because neither city $1$ nor city $5$ has an army stationed, violating the condition that at least one of the two directly connected cities must have an army stationed.\n\n#### Data Range and Hints\nFor all data, $n = m \\leq 10^5$ and $1 \\leq p_i \\leq 10^5$.\n\n\n\n| Test Point Number | $\\text{type}$ | $n=$ |\n|:-:|:-:|:-:|\n| $1,2$ | A3 | $10$ |\n| $3,4$ | C3 | $10$ |\n| $5,6$ | A3 | $100$ |\n| $7$ | C3 | $100$ |\n| $8,9$ | A3 | $2\\times 10^3$ |\n| $10,11$ | C3 | $2\\times 10^3$ |\n| $12,13$ | A1 | $10^5$ |\n| $14\\sim 16$ | A2 | $10^5$ |\n| $17$ | A3 | $10^5$ |\n| $18,19$ | B1 | $10^5$ |\n| $20,21$ | C1 | $10^5$ |\n| $22$ | C2 | $10^5$ |\n| $23\\sim 25$ | C3 | $10^5$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3007, "prompt": "### Problem Description\n\nThere are $n$ students waiting to take a shuttle bus from RDFZ (The High School Affiliated to Renmin University of China) to Renmin University. The $i$-th student arrives at the bus stop at time $t_i$ (in minutes). There is only one shuttle bus operating, but the bus has an unlimited capacity. The shuttle bus travels from RDFZ to Renmin University and returns to RDFZ to pick up more students, which takes a total of $m$ minutes per round trip (the boarding and alighting times are negligible). The shuttle bus must transport all the students to Renmin University.\n\nKai Kai is curious\u2014if he can schedule the shuttle bus departure times freely, what is the minimum total waiting time for all the students?\n\nNote: The shuttle bus can depart immediately after returning to RDFZ.\n\n### Input Format\n\nThe input file is named `bus.in`.\n\nThe first line contains two positive integers, $n$ and $m$, separated by a space, representing the number of students and the time it takes for a shuttle bus round trip, respectively. \nThe second line contains $n$ non-negative integers, separated by spaces. The $i$-th integer $t_i$ represents the arrival time of the $i$-th student at the bus stop.\n\n### Output Format\n\nThe output file is named `bus.out`.\n\nOutput a single integer on one line, representing the minimum total waiting time for all students (in minutes).\n\n### Example 1\n\n#### Input\n```\n5 1\n3 4 4 3 5\n```#### Output\n```\n0\n```\n\n#### Explanation\n\n- Students 1 and 4 arrive at minute 3, wait 0 minutes, and board the shuttle bus at minute 3. The shuttle bus returns at minute 4.\n- Students 2 and 3 arrive at minute 4, wait 0 minutes, and board the shuttle bus at minute 4. The shuttle bus returns at minute 5.\n- Student 5 arrives at minute 5, waits 0 minutes, and boards the shuttle bus at minute 5.\n\nThus, all students are transported to Renmin University, achieving a total waiting time of $0$.\n\n---\n\n### Example 2\n\n#### Input\n```\n5 5\n11 13 1 5 5\n```\n\n#### Output\n```\n4\n```\n\n#### Explanation\n\n- Student 3 arrives at minute 1, waits 0 minutes, and boards the shuttle bus at minute 1. The shuttle bus returns at minute 6.\n- Students 4 and 5 arrive at minute 5, wait 1 minute, and board the shuttle bus at minute 6. The shuttle bus returns at minute 11.\n- Student 1 arrives at minute 11, waits 2 minutes; Student 2 arrives at minute 13, and waits 0 minutes. Both board the shuttle bus at minute 13.\n\nThus, all students are transported to Renmin University, achieving a total waiting time of $4$. \nIt can be proven that no arrangement yields a total waiting time smaller than $4$.\n\n---\n\n### See attached files for `bus3.in` and `bus3.ans`.\n\n---\n\n### Constraints and Hints\n\n- For $10\\%$ of the test cases, $n \\leq 10$, $m = 1$, $0 \\leq t_i \\leq 100$. \n- For $30\\%$ of the test cases, $n \\leq 20$, $m \\leq 2$, $0 \\leq t_i \\leq 100$. \n- For $50\\%$ of the test cases, $n \\leq 500$, $m \\leq 100$, $0 \\leq t_i \\leq 10^4$. \n- For an additional $20\\%$ of the test cases, $n \\leq 500$, $m \\leq 10$, $0 \\leq t_i \\leq 4 \\times 10^6$. \n- For $100\\%$ of the test cases, $n \\leq 500$, $m \\leq 100$, $0 \\leq t_i \\leq 4 \\times 10^6$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2953, "prompt": "### Problem Description\n\nXiao Y is an OIer who loves traveling. She has arrived in Country X and plans to visit all its cities.\n\nXiao Y learned that Country X has $n$ cities connected by $m$ bidirectional roads. Each road connects two cities. There are no multiple roads between the same pair of cities, and no road connects a city to itself. Additionally, it is guaranteed that from any city, Xiao Y can reach every other city using these roads, meaning the cities form a connected graph. Xiao Y can only travel between cities using these roads.\n\nXiao Y's travel plan is as follows: She starts from any city of her choice and begins her journey. At each step, she can either choose a road connecting the current city to another unvisited city or return along the same road she came from to the previous city. When Xiao Y returns to the starting city, she may choose to end her travel or continue exploring. Importantly, Xiao Y requires her travel plan to visit every city exactly once.\n\nTo make her travel more meaningful, Xiao Y decides to record the city number every time she enters a new city, including the starting city. This results in a sequence of length $n$. She hopes this sequence will have the smallest lexicographical order possible. Can you help her?\n\nFor two sequences $A$ and $B$ of length $n$, sequence $A$ is said to have smaller lexicographical order than sequence $B$ if and only if there exists a positive integer $x$ such that the following conditions are satisfied:\n\n- For any integer $1 \\le i < x$, the $i$-th element $A_i$ of sequence $A$ is equal to the $i$-th element $B_i$ of sequence $B$.\n- The $x$-th element $A_x$ of sequence $A$ is smaller than the $x$-th element $B_x$ of sequence $B$.\n\n---\n\n### Input Format\n\nThe input file name is `travel.in`. \nThe input file contains $m+1$ lines. \n\nThe first line contains two integers $n$ and $m$, separated by a space. \nThe following $m$ lines each contain two integers $u$ and $v$, indicating that there is a road between city $u$ and city $v$. The two integers are separated by a space.\n\n---\n\n### Output Format\n\nThe output file name is `travel.out`. \nThe output file contains a single line with $n$ integers, representing the sequence with the smallest lexicographical order. Adjacent integers are separated by a space.\n\n---\n\n### Example 1\n\nInput:\n```\n4 4\n1 2\n2 3\n3 4\n4 1\n```Output:\n```\n1 2 3 4\n```\n\n---\n\n### Example 2\n\nInput:\n```\n3 3\n1 2\n1 3\n2 3\n```\n\nOutput:\n```\n1 2 3\n```\n\n---\n\n### Constraints and Notes\n\nFor all test cases, $1 \\le n \\le 5 \\times 10^3$, and $m = n-1$ or $m = n$. It is guaranteed that $1 \\le u, v \\le n$.\n\nFor different test points, the scale of the data is defined as follows:\n\n\n| Test Point | $n=$ | $m=$ | Special Properties |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 3$ | $10$ | $m=n-1$ | None |\n| $4,5$ | $100$ | $m=n-1$ | None |\n| $6 \\sim 8$ | $10^3$ | $m=n-1$ | Each city is connected to at most two other cities |\n| $9,10$ | $10^3$ | $m=n-1$ | None |\n| $11 \\sim 13$ | $5 \\times 10^3$ | $m=n-1$ | Each city is connected to at most three other cities |\n| $14,15$ | $5 \\times 10^3$ | $m=n-1$ | None |\n| $16,17$ | $10$ | $m=n$ | None |\n| $18,19$ | $100$ | $m=n$ | None |\n| $20 \\sim 22$ | $10^3$ | $m=n$ | Each city is connected to at most two other cities |\n| $23 \\sim 25$ | $5 \\times 10^3$ | $m=n$ | None |\n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2606, "prompt": "### Problem Description\n\nDuring college, it is often necessary to rent classrooms. Whether for faculty-organized events or small group discussions, applications need to be made to the university to reserve classrooms. Classrooms vary in size and function, and the application process may differ depending on the applicant's identity.\n\nGiven the vast amount of classroom rental information, we naturally hope to address this problem programmatically.\n\nWe need to process the classroom rental data for the next $n$ days. On the $i$-th day, the school has $r_i$ classrooms available for rental. There are a total of $m$ requests, and each request is described by three positive integers $d_j$, $s_j$, $t_j$, which indicate that a requester needs to rent $d_j$ classrooms per day from day $s_j$ to day $t_j$ (both inclusive).\n\nAssume that requesters have no specific requirements regarding the size or location of the classrooms. In other words, for each request, we only need to provide $d_j$ classrooms per day, regardless of which specific classrooms are provided or whether they are the same classrooms each day.\n\nThe principle for renting classrooms is *first come, first served*. That is, we process the requests in the given order, allocating classrooms for each request one by one. If at any point we encounter a request that cannot be fully satisfied, we terminate the allocation process and notify the corresponding requester to modify their request. \"Cannot be fully satisfied\" means that on at least one day from day $s_j$ to day $t_j$, the number of remaining classrooms is less than $d_j$.\n\nYour task is to determine whether all requests can be fully satisfied. If not, identify the requester whose order needs to be modified.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of days and the total number of requests, respectively.\n\nThe second line contains $n$ positive integers, where the $i$-th number $r_i$ represents the number of classrooms available for rental on day $i$.\n\nThe following $m$ lines each contain three positive integers $d_j$, $s_j$, $t_j$, where $d_j$ indicates the number of classrooms needed per day, and $s_j$ and $t_j$ denote the start and end days of the rental period, respectively. Each pair of numbers in a line are separated by a single space. Both the days and requests are indexed starting from $1$.\n\n---\n\n### Output Format\n\nIf all requests can be fully satisfied, output a single line containing the integer $0$.\n\nOtherwise (if a request cannot be fully satisfied), output two lines: \n- The first line contains the negative integer $-1$. \n- The second line contains the index of the requester whose order needs to be modified.\n\n---\n\n### Sample\n\n#### Input\n```\n4 2\n4 3 2 3\n4 1 1\n3 2 4\n```#### Output\n```\n-1\n2\n```\n\n#### Explanation\nAfter fulfilling the 1st request, the remaining number of classrooms over the 4 days is $0$, $3$, $2$, $3$. For the 2nd request, which requires 3 classrooms daily from day 2 to day 4, the remaining classrooms on day 3 are only $2$, making it impossible to fully meet the request. Allocation stops, and the 2nd requester is notified to modify their request.\n\n---\n\n### Constraints and Notes\n\n- For 10% of test cases, $1 \\leq n, m \\leq 10^1$; \n- For 30% of test cases, $1 \\leq n, m \\leq 10^3$; \n- For 70% of test cases, $1 \\leq n, m \\leq 10^5$; \n- For 100% of test cases, $1 \\leq n, m \\leq 10^6$, $0 \\leq r_i, d_j \\leq 10^9$, $1 \\leq s_j \\leq t_j \\leq n$. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2358, "prompt": "### Problem Description\n\nLittle Nan has a cute set of toy figurines, each with a unique profession.\n\nOne day, these toy figurines hid Little Nan's glasses. She noticed that the toy figurines were arranged in a circle, with some facing inward and others facing outward, as shown in the following diagram:\n\n![](https://img.loj.ac.cn/2019/05/13/5cd9702499831.png)\n\nAt this point, the `singer` told Little Nan a riddle: \"The glasses are hidden with the toy figurine who is the 3rd toy figurine to my left, 1st toy figurine to their right, and 2nd toy figurine to their left.\"\n\nLittle Nan discovered that the direction the toy figurines are facing is crucial, as inward- and outward-facing toy figurines have opposite left and right directions. Specifically, a toy figurine facing inward has its left side in the clockwise direction, and its right side in the counter-clockwise direction. On the other hand, a toy figurine facing outward has its left side in the counter-clockwise direction and its right side in the clockwise direction.\n\nLittle Nan carefully identified and counted: \n\n- `singer` faces inward, and the 3rd toy figurine to the left is `archer`. \n- `archer` faces outward, and the 1st toy figurine to the right is `thinker`. \n- `thinker` faces outward, and the 2nd toy figurine to the left is `writer`.\n\nThus, the glasses are hidden with `writer`!\n\nAlthough she managed to retrieve her glasses successfully, Little Nan is still worried. If there are more toy figurines next time or if the riddle is longer, she might not be able to find the glasses. Hence, Little Nan hopes you can write a program to help her solve similar riddles. These riddles can specifically be described as follows:\n\nThere are $n$ toy figurines arranged in a circle. Their professions and directions are given. The first toy figurine tells Little Nan a riddle consisting of $m$ instructions. The $i^{th}$ instruction will take the form of \"count $s_i$ toy figurines to the left/right.\" You need to output the profession of the toy figurine reached by sequentially following all these instructions.\n\n---\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $m$, representing the number of toy figurines and the number of instructions, respectively.\n\nThe following $n$ lines each contain an integer and a string, specifying the direction and profession of each toy figurine in counter-clockwise order. Here, `0` indicates the toy figurine is facing inward, and `1` indicates the toy figurine is facing outward. No other values will appear. The string has a length of up to 10 characters, is composed of lowercase alphabets only, is non-empty, and each string is unique. The integer and string are separated by a single space.\n\nThe next $m$ lines each contain two integers $a_i$ and $s_i$, representing the $i^{th}$ instruction. Specifically, if $a_i = 0$, count $s_i$ toy figurines to the left; if $a_i = 1$, count $s_i$ toy figurines to the right. No other values for $a_i$ will appear. $1 \\leq s_i < n$.\n\n---\n\n### Output Format\n\nOutput a single string representing the profession of the toy figurine reached after sequentially following $m$ instructions starting from the first toy figurine.\n\n---\n\n### Example 1\n\nThis dataset corresponds to the example described in the \"Problem Description.\"\n\n### Example 2\n\n---\n\n### Constraints and Hints\n\n$1 \\leq n, m \\leq 100000$\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2422, "prompt": "### Problem Description\n\nNiuNiu has recently become obsessed with a card game called \"Fight the Landlord\". It is a game played with 54 poker cards: spades, hearts, clubs, diamonds ranging from $A$ to $K$, plus two jokers (small and big). In this game, the ranking of the cards is determined by their numeric values as follows: $3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < J < Q < K < A < 2 < \\text{small joker} < \\text{big joker}$, and card suits have no impact on card ranking. \n\nIn each game, a hand consists of $n$ cards. Players can play cards according to specific card patterns until they run out of cards. The player who plays all their cards first wins the game. Now, NiuNiu wants to know for several sets of hands how many moves are needed to play all the cards. \n\nPlease note that in this problem the types of card patterns allowed are slightly different from the standard \"Fight the Landlord\". The specific rules are as follows:\n\n| Card Pattern | Description |\n|--------------|-------------|\n| Single | One card. |\n| Pair | Two cards with the same numeric value. |\n| Triplet | Three cards with the same numeric value. |\n| Bomb | Four cards with the same numeric value, e.g., four $A$s. |\n| Rocket | The pair of jokers (small joker and big joker). |\n| Three-with-One | Three cards with the same numeric value + one single card, e.g., three 3s + single 4. |\n| Three-with-Two | Three cards with the same numeric value + one pair, e.g., three 3s + pair of 4s. |\n| Single Straight | Five or more consecutive single cards (excluding 2 and the two jokers), e.g., single 7 + single 8 + single 9 + single 10 + single $J$. |\n| Pair Straight | Three or more consecutive pairs (excluding 2 and the two jokers), e.g., pair of 3s + pair of 4s + pair of 5s. |\n| Triple Straight | Two or more consecutive triplets (excluding 2 and the two jokers), e.g., three 3s + three 4s + three 5s. |\n| Four-with-Two | Four cards with the same numeric value + any two single cards (or any two pairs), e.g., four 5s + single 3 + single 8 or four 4s + pair of 5s + pair of 7s. |\n\nAdditionally, for straight patterns (Single Straight, Pair Straight, Triple Straight), the suits of the cards are not required to be the same.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $T$ and $N$, separated by a space, representing the number of card hands and the number of cards in each hand.\n\nNext come $T$ groups of data. Each group contains $N$ lines, and each line consists of a pair of non-negative integers $A_i, B_i$ separated by a space, representing a card. Here:\n- $A_i$ represents the numeric value of the card,\n- $B_i$ represents the suit of the card. \n\nIn particular:\n- $1$ represents numeric $A$, \n- $11$ represents numeric $J$, \n- $12$ represents numeric $Q$, \n- $13$ represents numeric $K$. \n\nFor the suits:\n- Spades, hearts, clubs, diamonds are represented by $1, 2, 3, 4$ respectively. \n- The small joker is represented by `0 1`, and the big joker is represented by `0 2`.\n\n---\n\n### Output Format\n\nOutput $T$ lines. Each line contains an integer, indicating the minimum number of moves needed to play all cards in the $i$-th hand.\n\n---\n\n### Example 1\n\n\n\n---\n\n### Example 2\n\n\n\n---\n\n### Constraints and Hints\n\n| Test Case | $T$ | $n$ |\n|-----------|-----|-----|\n| $1 \\sim 6$ | $T=100$ | $n \\leq 4$ |\n| $7 \\sim 12$ | $T=100$ | $n = \\text{Test Case Number} + 3$ |\n| $13 \\sim 20$ | $T=10$ | $n = \\text{Test Case Number} + 3$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2083, "prompt": "### Problem Description\n\nIf a string can be divided into the form $\\text{AABB}$, where $\\text{A}$ and $\\text{B}$ are any **non-empty** substrings, we consider such a division of the string as excellent. \nFor example, for the string $ \\texttt{aabaabaa} $, if we let $\\text{A}=\\texttt{aab}$ and $\\text{B}=\\texttt{a}$, we find one way to divide the string into $\\text{AABB}$.\n\nA string may have no excellent division, or it may have more than one excellent division. \nFor instance, letting $\\text{A}=\\texttt{a}$ and $\\text{B}=\\texttt{baa}$ also expresses the above string as $\\text{AABB}$. However, the string $\\texttt{abaabaa}$ has no excellent division.\n\nGiven a string $S$ of length $n$, we need to calculate, among all substrings of $S$ and all their division methods, the total number of excellent divisions. Here, a substring is defined as a consecutive segment within the string.\n\nThe following points are noteworthy:\n\n1. Identical substrings appearing at different positions are considered distinct, and their excellent divisions each contribute to the total count.\n2. In one division, it is allowed to have $\\text{A}=\\text{B}$. For example, the string $\\texttt{cccc}$ has an excellent division where $\\text{A}=\\text{B}=\\texttt{c}$.\n3. The string itself is also considered one of its substrings.\n\n---\n\n### Input Format\nThe input file contains multiple test cases. \nThe first line of the input file contains a single integer $T$, representing the number of test cases. \nIn the next $T$ lines, each line contains a string $S$ composed solely of lowercase English letters, as described above.\n\n---\n\n### Output Format\nOutput $T$ lines, each containing an integer representing the total number of excellent divisions across all substrings of string $S$.\n\n---\n\n### Example\nUse $S[i, j]$ to denote the substring starting at the $i$-th character and ending at the $j$-th character of string $S$ (indexed starting from $1$).\n\n#### Example Explanation:\n\n**First Test Case:** \nThere are three substrings with excellent divisions: \n$S[1,4]=\\texttt{aabb}$, excellent division: $\\text{A}=\\texttt{a}$, $\\text{B}=\\texttt{b}$; \n$S[3,6]=\\texttt{bbbb}$, excellent division: $\\text{A}=\\texttt{b}$, $\\text{B}=\\texttt{b}$; \n$S[1,6]=\\texttt{aabbbb}$, excellent division: $\\text{A}=\\texttt{a}$, $\\text{B}=\\texttt{bb}$. \nOther substrings have no excellent divisions, so the answer for the first test case is $3$. \n\n**Second Test Case:** \nThere are two types, totaling four substrings with excellent divisions: \nFor the substrings $S[1,4]=S[2,5]=S[3,6]=\\texttt{cccc}$, their excellent division is the same: $\\text{A}=\\texttt{c}$, $\\text{B}=\\texttt{c}$, but because these substrings appear at different positions, they are counted separately, contributing three to the total; \nFor the substring $S[1,6]=\\texttt{cccccc}$, it has two excellent divisions: $\\text{A}=\\texttt{c}$, $\\text{B}=\\texttt{cc}$ and $\\text{A}=\\texttt{cc}$, $\\text{B}=\\texttt{c}$. Both contribute to the total. \nThus, the answer for the second test case is $3+2=5$. \n\n**Third Test Case:** \n$S[1,8]$ and $S[4,11]$ each have two excellent divisions. $S[1,8]$ is the example given in the problem description. \nThus, the answer for the third test case is $2+2=4$. \n\n**Fourth Test Case:** \nThe substrings $S[1,4]$, $S[6,11]$, $S[7,12]$, $S[2,11]$, $S[1,8]$ each have one excellent division, and $S[3,14]$ has two excellent divisions. \nThus, the answer for the fourth test case is $5+2=7$. \n\n---\n\n### Constraints and Notes\nFor all test cases, $1 \\leq T \\leq 10$, $n \\leq 30000$. \n\nSpecific constraints for each test case are as follows: \n\n| Test Case | $n\\le$ | Special Property | \n|:-:|:-:|:-:| \n| $1,~2$ | $300$ | All characters in $S$ are the same | \n| $3,~4$ | $2000$ | All characters in $S$ are the same | \n| $5,~6$ | $10$ | No special constraints | \n| $7,~8$ | $20$ | No special constraints | \n| $9,~10$ | $30$ | No special constraints | \n| $11,~12$ | $50$ | No special constraints | \n| $13,~14$ | $100$ | No special constraints | \n| $15$ | $200$ | No special constraints | \n| $16$ | $300$ | No special constraints | \n| $17$ | $500$ | No special constraints | \n| $18$ | $1000$ | No special constraints | \n| $19$ | $2000$ | No special constraints | \n| $20$ | $30000$ | No special constraints | \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2664, "prompt": "### Problem Description\nThe inner product of two $d$-dimensional vectors $A=[a_1, a_2 ,...,a_d]$ and $B=[b_1 ,b_2 ,...,b_d]$ is the sum of the products of their corresponding dimensions, defined as:\n$$\n(A, B) = \\displaystyle \\sum_{i=1}^d{a_i b_i} = a_1b_1 + a_2b_2 + \\ldots + a_d b_d\n$$\nGiven $n$ $d$-dimensional vectors $x_1, \\ldots, x_n$, Little Meow-Meow wants to know whether there exist two vectors whose inner product is a multiple of $k$. Please help her solve this problem.\n\n### Input Format\nThe first line contains $3$ positive integers $n, d, k$, representing the number of vectors, the dimension of each vector, and the multiple to check respectively.\n\nThe next $n$ lines each contain $d$ non-negative integers, where the $i$-th line's $j$-th integer represents the $j$-th dimension weight of vector $[x_i]$, denoted as $x_{i,j}$.\n\n### Output Format\nThe output contains two integers separated by a space.\n\nIf there exist two vectors $x_p, x_q$ such that their inner product is a multiple of $k$, output the indices $p$ and $q$ (where $p < q$). If there are multiple pairs of vectors satisfying this condition, output any pair.\n\nIf no such pair of vectors exists, output two $-1$.\n\n### Example\nIf\n$(x_1, x_2) = 1$, \n$(x_1, x_3) = 1$, \n$(x_2, x_3) = 2$, \n\nan example solution could look like:\n```\n- Example output not explicitly provided in the initial translation -\n```### Constraints and Hints\n| Test Case ID | $n$ | $d$ | $k$ | $x_i$ |\n| :-: | :-: | :-: | :-: | :-: |\n| $1$ | $2$ | $20$ | $2$ | $\\leq 10$ |\n| $2$ | $5$ | $20$ | $2$ | $\\leq 10$ |\n| $3$ | $10$ | $20$ | $3$ | $\\leq 10$ |\n| $4$ | $20$ | $20$ | $2$ | $\\leq 100$ |\n| $5$ | $50$ | $20$ | $3$ | $\\leq 100$ |\n| $6$ | $50$ | $50$ | $2$ | $\\leq 1000$ |\n| $7$ | $50$ | $50$ | $3$ | $\\leq 3000000$ |\n| $8$ | $80$ | $80$ | $2$ | $\\leq 2000000$ |\n| $9$ | $100$ | $100$ | $3$ | $\\leq 3000000$ |\n| $10$ | $500$ | $100$ | $3$ | $\\leq 3000000$ |\n| $11$ | $1000$ | $100$ | $2$ | $\\leq 2000000$ |\n| $12$ | $1000$ | $100$ | $3$ | $\\leq 3000000$ |\n| $13$ | $10000$ | $100$ | $2$ | $< 10$ |\n| $14$ | $10000$ | $100$ | $3$ | $< 10$ |\n| $15$ | $15000$ | $100$ | $2$ | $< 10$ |\n| $16$ | $18000$ | $100$ | $2$ | $< 10$ |\n| $17$ | $20000$ | $100$ | $2$ | $< 10$ |\n| $18$ | $50000$ | $30$ | $3$ | $< 10$ |\n| $19$ | $80000$ | $30$ | $3$ | $< 10$ |\n| $20$ | $100000$ | $30$ | $3$ | $< 10$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2416, "prompt": "### Problem Description\n\nTom has recently been studying an interesting sorting problem. As shown below, with the help of two stacks, $S_1$ and $S_2$, Tom wants to use the following four operations to sort an input sequence in ascending order.\n\n![Illustration](https://img.loj.ac.cn/2022/06/09/65db667c2656e.png)\n\n1. Operation $a$: Push the first element into stack $S_1$.\n2. Operation $b$: Pop the top element from stack $S_1$ into the output sequence.\n3. Operation $c$: Push the first element into stack $S_2$.\n4. Operation $d$: Pop the top element from stack $S_2$ into the output sequence.\n\nIf a permutation $P$ of $1\\sim n$ can be sorted into $(1, 2, \\dots, n-1, n)$ in ascending order via a series of valid operations, Tom calls $P$ a \"double-stack sortable permutation.\" For example, $(1, 3, 2, 4)$ is a \"double-stack sortable sequence,\" while $(2, 3, 4, 1)$ is not. The figure below illustrates an example of sorting $(1, 3, 2, 4)$ using the operation sequence $\\texttt{a,c,c,b,a,d,d,b}$.\n\n![Example Illustration](https://img.loj.ac.cn/2022/06/09/5e3b49af0ae9d.png)\n\nOf course, there could be multiple operation sequences for sorting such permutations. For instance, for the sequence $(1, 3, 2, 4)$, the sequence $\\texttt{a,b,a,a,b,b,a,b}$ is another feasible operation sequence. Tom wants to know the lexicographically smallest operation sequence among all valid ones.\n\n---\n\n### Input Format\n\nThe first line contains an integer $n$. \nThe second line contains $n$ positive integers separated by spaces, forming a permutation of $1\\sim n$. \n\n---\n\n### Output Format\n\nOutput a single line: \n- If the input permutation is not a \"double-stack sortable permutation,\" output `0`.\n- Otherwise, output the lexicographically smallest operation sequence, with each operation separated by a single space and no trailing spaces at the end of the line.\n\n---\n\n### Example 1\n\n#### Input:\n```\n4\n1 3 2 4\n```#### Output:\n```\na c c b a d d b\n```\n\n---\n\n### Example 2\n\n#### Input:\n```\n4\n2 3 4 1\n```\n\n#### Output:\n```\n0\n```\n\n---\n\n### Example 3\n\n#### Input:\n```\n4\n1 2 3 4\n```\n\n#### Output:\n```\na b a b a b a b\n```\n\n---\n\n### Constraints and Hints\n- For $30\\%$ of the test cases, $n \\leq 10$.\n- For $50\\%$ of the test cases, $n \\leq 50$.\n- For $100\\%$ of the test cases, $n \\leq 1000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2613, "prompt": "### Problem Description\n\nLittle B has recently become obsessed with the \"Huarong Dao\" puzzle. However, it usually takes him a long time to complete it. Therefore, he thought about programming to solve the puzzle: given an initial state of the board, determine whether the puzzle is unsolvable, and if solvable, calculate the minimum time needed to solve it.\n\nThe variant of the puzzle played by Little B differs slightly from the classic Huarong Dao game. The rules are as follows:\n\n1. There is an $n \\times m$ grid, consisting of $n \\times m$ cells. Among them, exactly one cell is empty, while the remaining $n \\times m - 1$ cells each contain a piece. Each piece occupies exactly a $1 \\times 1$ cell.\n2. Some pieces are fixed and cannot be moved, while other pieces are movable.\n3. Any movable piece that is adjacent (sharing one edge) to the empty cell can move into the empty cell. The objective of the game is to move a specific movable piece to a designated target position.\n\nGiven the board layout, the game can be played $q$ times. For each game, the board's fixed pieces remain unchanged, but the initial position of the empty cell, the initial position of the specified movable piece, and the target position of that piece may vary. In the $i$-th game, the empty cell starts at position $(\\mathit{EX}_i, \\mathit{EY}_i)$, the specified movable piece starts at $(\\mathit{SX}_i, \\mathit{SY}_i)$, and the target position for that piece is $(\\mathit{TX}_i, \\mathit{TY}_i)$.\n\nAssuming Little B can perform one move operation per second and that other operations take negligible time, determine the minimum time required for each game, or conclude that the game is unsolvable.\n\n---\n\n### Input Format\n\nThe first line of input contains $3$ integers, separated by spaces, representing $n$, $m$, and $q$, respectively.\n\nThe next $n$ lines describe the $n \\times m$ grid. Each line contains $m$ integers, separated by spaces. Each integer describes the state of a cell:\n- $0$: The piece in the cell is fixed and cannot be moved.\n- $1$: The piece in the cell is movable, or the cell is empty.\n\nThe subsequent $q$ lines each contain $6$ integers, separated by spaces. For the $i$-th game, these integers are $\\mathit{EX}_i$, $\\mathit{EY}_i$, $\\mathit{SX}_i$, $\\mathit{SY}_i$, $\\mathit{TX}_i$, $\\mathit{TY}_i$, representing:\n- Initial position of the empty cell: $(\\mathit{EX}_i, \\mathit{EY}_i)$,\n- Initial position of the specified movable piece: $(\\mathit{SX}_i, \\mathit{SY}_i)$,\n- Target position of the specified movable piece: $(\\mathit{TX}_i, \\mathit{TY}_i)$.\n\n---\n\n### Output Format\n\nThe output consists of $q$ lines. Each line contains a single integer:\n- The minimum time required to complete the game.\n- Or `-1` if the game is unsolvable.\n\n---\n\n### Example\n\nThe cells marked with \"X\" on the board are fixed. The red cell represents the target position, and circles represent the movable pieces. The green circle denotes the specified piece that needs to be moved to the red target.\n\n#### Game 1:\nThe empty cell starts at position $(3, 2)$ (as shown in the diagram), and the goal is to move the specified piece starting at position $(1, 2)$ (green circle) to the target position $(2, 2)$ (red cell).\n\nThe movement steps are as follows:\n\n![puzzle1.png](https://img.loj.ac.cn/2021/12/29/a3e5253055667.png)\n\n#### Game 2:\nThe empty cell starts at position $(1, 2)$ (as shown in the diagram), and the goal is to move the specified piece starting at position $(2, 2)$ (green circle) to the target position $(3, 2)$.\n\n![puzzle2.png](https://img.loj.ac.cn/2021/12/29/20f5e38dae017.png)\n\nTo move the specified piece to the target position, the empty cell would need to occupy the target position first. However, for the empty cell to reach the target position, it would need to swap places with the piece currently occupying the target position. This creates a dependency loop, making the game unsolvable.\n\n---\n\n### Constraints and Hints\n\n- For $30\\%$ of the data: $1 \\leq n, m \\leq 10$, and $q = 1$,\n- For $60\\%$ of the data: $1 \\leq n, m \\leq 30$, and $q \\leq 10$,\n- For $100\\%$ of the data: $1 \\leq n, m \\leq 30$, and $q \\leq 500$,\n- It is guaranteed that $(\\mathit{EX}_i, \\mathit{EY}_i) \\neq (\\mathit{SX}_i, \\mathit{SY}_i)$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2442, "prompt": "### Problem Description\nFarmer Dongdong has been struggling with his income recently. While worrying about how to earn more money, he overheard some children next door discussing the problem of rabbit reproduction. \n\nThe problem is as follows: At the beginning of the first month, there is a pair of newborn baby rabbits. After two months of growth, this pair of rabbits starts producing one pair of baby rabbits at the beginning of each month starting from the third month. Newly born rabbits will also reach maturity in two months, after which they will start producing one pair of rabbits each month. How many rabbits will there be by the $n$-th month? \n\nYou, being clever, might have already realized that the number of rabbits in the $n$-th month is the $n$-th Fibonacci number. Dongdong doesn't understand what Fibonacci numbers are, but he also observed the pattern: the number of rabbits in month $i+2$ equals the sum of the rabbit count in month $i$ and month $i+1$. The number of rabbits in the first few months is:\n\n$$ 1, 1, 2, 3, 5, 8, 13, 21, 34 \\dots $$\n\nDongdong noticed that the number of rabbits grows faster and faster as the months progress, and he optimistically believes raising rabbits will make him rich. Thus, Dongdong started raising rabbits by purchasing one pair of baby rabbits at the beginning of the first month. \n\nEvery day, Dongdong feeds the rabbits. The rabbits eat in a peculiar way: every $k$ pairs of rabbits form a feeding circle, and the leftover pairs (less than $k$) also form a circle. Starting from the third month, if any feeding circle consists of only one pair of rabbits, then that pair of rabbits will quickly die. Assume that the deceased are always the newborn rabbits. As a result, the number of rabbits for each month can still be computed. For example, when $k=7$, the number of rabbits in the first few months is:\n\n$$ 1, 1, 2, 3, 5, 7, 12, 19, 31, 49, 80 \\dots $$\n\nGiven $n$, can you help Dongdong calculate how many **pairs** of rabbits he will have in the $n$-th month? Since the answer could be very large, you only need to tell Dongdong the remainder of the number of rabbit pairs in the $n$-th month divided by $p$. \n\n### Input Format\nThe input consists of a single line containing three positive integers $n$, $k$, $p$. \n\n### Output Format\nOutput a single line containing an integer, which is the remainder of the number of rabbit pairs in the $n$-th month divided by $p$. \n\n### Sample 1\n\n```\nInput: \n10 5 100 \nOutput: \n55 \n```### Sample 2\n\n```\nInput: \n50 7 1000 \nOutput: \n265 \n```\n\n### Data Range and Hints\n\n| Test Case ID | $n$ | $k,p$ |\n| :-: | :-: | :-: |\n| 1 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 2 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 3 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 4 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 5 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 6 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 7 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 8 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 9 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 10 | $1 \\leq n \\leq 50$ | $2 \\leq k,p \\leq 1000$ |\n| 11 | $1 \\leq n \\leq 80$ | $2 \\leq k,p \\leq 10,000$ |\n| 12 | $1 \\leq n \\leq 1000$ | $2 \\leq k,p \\leq 10,000$ |\n| 13 | $1 \\leq n \\leq 1000$ | $2 \\leq k,p \\leq 10,000$ |\n| 14 | $1 \\leq n \\leq 10^6$ | $2 \\leq k,p \\leq 10^6$ |\n| 15 | $1 \\leq n \\leq 10^6$ | $2 \\leq k,p \\leq 10^6$ |\n| 16 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k,p \\leq 1000$ |\n| 17 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k,p \\leq 1000$ |\n| 18 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k \\leq 10^6,2 \\leq p \\leq 10^9$ |\n| 19 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k \\leq 10^6,2 \\leq p \\leq 10^9$ |\n| 20 | $1 \\leq n \\leq 10^{18}$ | $2 \\leq k \\leq 10^6,2 \\leq p \\leq 10^9$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2360, "prompt": "### Problem Description\nFor NiuNiu, who has just entered university, his first challenge is how to choose suitable courses based on the actual situation.\n\nAmong the available courses, there are $2n$ classes scheduled in $n$ time slots. In the $i$-th time slot ($1 \\leq i \\leq n$), two identical classes are held simultaneously at different locations. NiuNiu is pre-assigned to classroom $c_i$, and the other class is held in classroom $d_i$. \nWithout submitting any applications, students are required to follow the class schedule and attend all $n$ classes in sequential order. If a student wants to switch to classroom $d_i$ for the $i$-th class, they need to submit an application. If the application is approved, the student can attend the class in classroom $d_i$; otherwise, they will attend the class in classroom $c_i$. \nDue to the high demand for classroom changes, applications may not necessarily be approved. After calculation, NiuNiu finds that the probability of the application for switching the $i$-th class being approved is a known real number $k_i$. The application probabilities for different classes are independent of each other. \nThe university stipulates that all applications must be submitted once before the academic term begins, and each person can select up to $m$ classes for which they will apply for changes. This means NiuNiu must decide once whether to apply for each class change, without being able to adjust the decision based on the outcome of prior applications. NiuNiu can apply to switch the $m$ most desired classes or choose not to use up to $m$ opportunities, or even decide not to apply for any class. \n\nBecause different classes might be held in different classrooms, NiuNiu needs to travel from one classroom to another between classes. \nNiuNiu's university has $v$ classrooms and $e$ roads. Each road connects two classrooms and is bidirectional. Due to varying road lengths and congestion levels, traveling via different roads may consume different levels of physical energy. When the $i$-th ($1 \\leq i \\leq n - 1$) class ends, NiuNiu will start from that class's classroom and choose the least physically exhaustive path to travel to the next class's classroom. \n\nNow NiuNiu wants to determine which classes he should apply for to minimize the expected total physical energy expenditure from traveling between classrooms. Please help him calculate this minimum value.\n\n---\n\n### Input Format\nThe first line contains four integers $n$, $m$, $v$, $e$, where: \n- $n$ represents the number of time slots in the semester. \n- $m$ represents the maximum number of classes NiuNiu can apply for a change in classrooms. \n- $v$ represents the number of classrooms in NiuNiu's university. \n- $e$ represents the number of roads in NiuNiu's university. \n\nThe second line contains $n$ positive integers, where the $i$-th ($1 \\leq i \\leq n$) integer represents $c_i$, the classroom NiuNiu is initially scheduled for in the $i$-th time slot. Ensure that $1 \\leq c_i \\leq v$. \n\nThe third line contains $n$ positive integers, where the $i$-th ($1 \\leq i \\leq n$) integer represents $d_i$, the alternate classroom for the same class in the $i$-th time slot. Ensure that $1 \\leq d_i \\leq v$. \n\nThe fourth line contains $n$ real numbers, where the $i$-th ($1 \\leq i \\leq n$) real number represents $k_i$, the probability that NiuNiu's application to switch to classroom $d_i$ during the $i$-th time slot is approved. Ensure that $0 \\leq k_i \\leq 1$. \n\nThe following $e$ lines each contain three integers $a_j, b_j, w_j$, representing a bidirectional road connecting classroom $a_j$ and classroom $b_j$. Traveling along this road costs $w_j$ physical energy. Ensure that $1 \\leq a_j, b_j \\leq v$ and $1 \\leq w_j \\leq 100$. \n\nGuarantees: \n- $1 \\leq n \\leq 2000$, $0 \\leq m \\leq 2000$, $1 \\leq v \\leq 300$, $0 \\leq e \\leq 90000$. \n- It is guaranteed that it is possible to travel between any two classrooms using the university's roads. \n- The input real numbers will have at most $3$ decimal places.\n\n---\n\n### Output Format\nOutput a single line containing a real number, rounded to exactly two decimal places, representing the answer. Your output must match the standard output format exactly to be considered correct. \n\nFor the testing data, it is guaranteed that the absolute difference between the rounded answer and the accurate answer will not exceed $4 \\times 10^{-3}$. (If you are unfamiliar with floating-point errors, you can understand this as: for most algorithms, you can normally use floating-point types without requiring special handling.)\n\n---\n\n### Sample\n\n---\n\n### Data Constraints and Hints\n$1 \\leq n, m \\leq 2000, 1 \\leq v \\leq 300, 1 \\leq e \\leq 90000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2246, "prompt": "### Problem Description\n\nRecently, the zoo director discovered that more and more lazy animals were appearing in the zoo. For example, penguins only know how to act cute and beg tourists for food. In order to rectify the bad habits in the zoo and encourage the animals to earn their food through their true talents, the director decided to open an algorithm class for the animals to learn programming.\n\nOne day, the director explained the KMP algorithm: \nDirector: \"For a string $S$, with a length of $L$, we can calculate an array named $\\textrm{next}$ in $O(L)$ time. Has anyone reviewed the meaning of the $\\textrm{next}$ array?\" \nPanda: \"For the substring formed by the first $i$ characters of $S$, the length of the longest string (excluding itself) that is both a prefix and a suffix of the substring is denoted as $\\textrm{next}_i$.\" \nDirector: \"Very good! Can you give an example?\" \nPanda: \"For instance, if $S$ is `abcababc`, then $\\textrm{next}_5=2$, because the first five characters of $S$ are `abcab`, and `ab` is both a prefix and a suffix, and there is no longer string satisfying this property. Similarly, we can obtain $\\textrm{next}_1 = \\textrm{next}_2 = \\textrm{next}_3 = 0,\\ \\textrm{next}_4 = \\textrm{next}_6 = 1,\\ \\textrm{next}_7 = 2,\\ \\textrm{next}_8 = 3$.\" \n\nThe director praised Panda for his thorough preparation. Then, the director explained in detail how to calculate the $\\textrm{next}$ array in $O(L)$ time.\n\nBefore the class ended, the director raised a question: \"The KMP algorithm can only calculate the $\\textrm{next}$ array. Now I want to calculate an even more powerful $\\textrm{num}$ array \u2014 for the substring formed by the first $i$ characters of $S$, count the number of strings that are both prefixes and suffixes of this substring, ensuring those prefixes and suffixes do not overlap. Denote this count as $\\textrm{num}_i$. For example, if $S$ is `aaaaa`, then $\\textrm{num}_4 = 2$, because the first four characters of $S$ are `aaaa`, where both `a` and `aa` satisfy the property of being prefixes and suffixes, and they do not overlap. However, `aaa` satisfies the property but overlaps, so it is not counted. Similarly, $\\textrm{num}_1 = 0,\\ \\textrm{num}_2 = \\textrm{num}_3 = 1,\\ \\textrm{num}_5 = 2$.\"\n\nFinally, the director announced a reward: the first student to solve the problem would receive a box of chocolate. Upon hearing this, the penguin, who had been sleeping during the lecture, woke up immediately. However, the penguin doesn't know how to solve the problem, so he is asking for help from you, the tourist visiting the zoo. Can you help the penguin write a program to calculate the $\\textrm{num}$ array?\n\nSpecifically, to avoid excessive output, you do not need to explicitly output $\\textrm{num}_i$ for each $i$. Instead, you only need to output $\\prod_{i=1}^L (\\textrm{num}_i+1) \\mod 1,000,000,007$.\n\n---\n\n### Input Format\n\nThe first line contains a positive integer $n$, indicating the number of test cases. \nThe subsequent $n$ lines each describe a test case. \nEach test case contains only one string $S$, as defined in the problem description. The data ensures that $S$ only contains lowercase letters. The input file will not contain extra blank lines, and there will be no trailing spaces at the end of lines.\n\n---\n\n### Output Format\n\nThe output contains $n$ lines, each describing the result of one test case. The order of the results should correspond to the order of the input data. \nFor each test case, output a single integer, which represents the result of the test case modulo $1,000,000,007$. The output file should not contain any extra blank lines.\n\n---\n\n### Example\n\n#### Input\n```\n2\naaaaa\nabcababc\n```#### Output\n```\n6\n36\n```\n\n---\n\n### Constraints and Hints\n\nFor all data, $n \\leq 5, L \\leq 10^6$.\n\n| Test Case No. | Constraints |\n|:-------------:|:-----------:|\n| $1$ | $n \\leq 5, L \\leq 50$ |\n| $2$ | $n \\leq 5, L \\leq 200$ |\n| $3$ | $n \\leq 5, L \\leq 200$ |\n| $4$ | $n \\leq 5, L \\leq 10,000$ |\n| $5$ | $n \\leq 5, L \\leq 10,000$ |\n| $6$ | $n \\leq 5, L \\leq 100,000$ |\n| $7$ | $n \\leq 5, L \\leq 200,000$ |\n| $8$ | $n \\leq 5, L \\leq 500,000$ |\n| $9$ | $n \\leq 5, L \\leq 1,000,000$ |\n| $10$ | $n \\leq 5, L \\leq 1,000,000$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2314, "prompt": "### Problem Description\n\nXiao Kai has two types of gold coins, each with a positive integer denomination, and the two denominations are coprime. He has an unlimited number of each denomination. Without providing change, there are some items whose value cannot be paid exactly using these two types of coins. Xiao Kai wants to know the maximum value of an item that cannot be paid exactly without providing change. \n**Note**: It is guaranteed that there exist items Xiao Kai cannot pay for exactly.\n\n### Input Format\n\nThe input consists of just one line, containing two positive integers $a$ and $b$ separated by a space, representing the denominations of Xiao Kai's gold coins.\n\n### Output Format\n\nThe output consists of just one line, containing one positive integer $N$, which represents the maximum value of an item that Xiao Kai cannot pay exactly for without providing change.\n\n### Example\n\nXiao Kai has an unlimited number of coins with denominations 3 and 7. Without providing change, he cannot pay exactly for items with values $1, 2, 4, 5, 8, 11$. The most expensive item he cannot pay exactly for is valued at $11$. \nFor example, any value greater than $11$ can be paid exactly: \n- $ 12 = 3 \\times 4 + 7 \\times 0$\n- $ 13 = 3 \\times 2 + 7 \\times 1$\n- $ 14 = 3 \\times 0 + 7 \\times 2$\n- $ 15 = 3 \\times 5 + 7 \\times 0$\n\n### Constraints and Hints\n\n- For $30\\%$ of the test cases: $ 1 \\le a, b \\le 50$\n- For $60\\%$ of the test cases: $1 \\le a, b \\le 10,000$\n- For $100\\%$ of the test cases: $1 \\le a, b \\le 1,000,000,000$ \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2602, "prompt": "### Problem Description\n\nIn the 16th century, French diplomat Blaise de Vigen\u00e8re designed a polyalphabetic cipher encryption algorithm called the Vigen\u00e8re Cipher. The Vigen\u00e8re Cipher is simple to use for both encryption and decryption while being relatively difficult to crack, which made it widely adopted by the Confederate Army during the American Civil War.\n\nIn cryptography, the information to be encrypted is called the plaintext, denoted as $M$. The encrypted information is called the ciphertext, denoted as $C$. A key is a parameter used as input in the algorithm to convert plaintext into ciphertext or decrypt ciphertext back into plaintext. The key is denoted as $K$ and is a string, $K = k_1k_2 \\dots k_n$. When the plaintext $M = m_1m_2 \\dots m_n$, the corresponding ciphertext $C = c_1c_2 \\dots c_n$ is obtained, where $c_i = m_i \\mathbin{\u00ae} k_i$. The operation $\u00ae$ follows the rules in the table below:\n\n![vigenere.png](https://img.loj.ac.cn/2021/12/29/96f91ff36955b.png)\n\nIn Vigen\u00e8re encryption, the following rules are observed:\n\n1. The $\u00ae$ operation ignores the case of the letters involved in the operation but preserves the case format of the letters in the plaintext $M$.\n2. If the length of the plaintext $M$ exceeds the length of the key $K$, the key $K$ is repeated cyclically.\n\nFor example, given plaintext $M = \\texttt{Helloworld}$ and key $K = \\texttt{abc}$, the ciphertext $C = \\texttt{Hfnlpyosnd}$.\n\n| Plaintext | H | e | l | l | o | w | o | r | l | d |\n|-----------|:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|\n| Key | a | b | c | a | b | c | a | b | c | a |\n| Ciphertext| H | f | n | l | p | y | o | s | n | d |\n\n### Input Format\n\nThe first line contains a string representing the key $K$. The length of $K$ does not exceed $100$, and it consists only of uppercase and lowercase letters.\n\nThe second line contains a string representing the encrypted ciphertext. The length of the ciphertext does not exceed $1,000$, and it consists only of uppercase and lowercase letters.\n\n### Output Format\n\nOutput one line, a string representing the plaintext corresponding to the given key and ciphertext.\n\n### Example\n\n#### Input:\n```\nabc\nHfnlpyosnd\n```#### Output:\n```\nHelloworld\n```\n\n### Constraints and Notes\n\nFor 100% of the test cases, the length of the input key does not exceed $100$ and the length of the input ciphertext does not exceed $1,000$. Both the key and ciphertext consist only of uppercase and lowercase letters.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2674, "prompt": "### Problem Description\n\nTo welcome students from all over the country, the city of CZ is hosting a grand food festival.\n\nAs someone who loves to try new dishes, Little M naturally doesn't want to miss out on this feast. He quickly tried all the dishes at the food festival. However, the urge to taste new things is insatiable. Even though all the dishes are tasty and the chefs cook them quickly, Little M still finds it unbearable to not have dishes on his table that are already served at someone else's. Thus, Little M started studying the order of cooking, in an attempt to arrange a sequence that minimizes the waiting time for students.\n\nLittle M noticed that there are $n$ different dishes available at the food festival. Each time a student orders, they can choose **one dish** among the $n$ types. There are $m$ chefs preparing these dishes. After all students have placed their orders, the cooking tasks for the dishes are assigned to the chefs. Each chef then begins cooking simultaneously. **The chefs must cook the dishes in the specified order, and they can only cook one serving at a time.**\n\nAdditionally, Little M discovered another interesting thing: while all $m$ chefs can prepare all $n$ types of dishes, **the time taken to prepare the same dish may vary from chef to chef**. The dishes are numbered as $1, 2, \\ldots, n$, and the chefs are numbered as $1, 2, \\ldots , m$. The time taken by the $j$th chef to prepare the $i$th type of dish is denoted as $t_{i,j}$.\n\nLittle M believes that the waiting time for each student is defined as **the total time, starting from when all chefs begin cooking, to when their ordered dish is completed**. In other words, if a dish ordered by a student is the $k$th dish prepared by a chef, their waiting time is the sum of the times for the chef to prepare their first $k$ dishes in sequence. The **total waiting time** is defined as the sum of the waiting times for all students.\n\nNow, Little M has obtained the dish order information from all the students\u2014$p_i$ students have ordered the $i$th type of dish ($i = 1, 2, \\ldots , n$). He wants to know the minimum possible **total waiting time**.\n\n---\n\n### Input Format\n\nThe first line of the input file contains two positive integers $n$ and $m$, representing the number of dish types and the number of chefs. \n\nThe second line contains $n$ positive integers, where the $i$th number is $p_i$, representing the number of students who have ordered the $i$th type of dish.\n\nThe next $n$ lines each contain $m$ non-negative integers. The $i$th line contains $m$ numbers, where the $j$th number is $t_{i,j}$, representing the time taken by the $j$th chef to prepare the $i$th dish.\n\nAdjacent numbers in each line are separated by a single space, and there are no trailing spaces at the end of each line.\n\n---\n\n### Output Format\n\nThe output contains only one line with a single integer, representing the minimum total waiting time.\n\n---\n\n### Example\n\nChef $1$ first cooks $1$ serving of dish $2$, then cooks $2$ servings of dish $1$. The three students who ordered these dishes have waiting times of $3, 3+5=8, 3+5+5=13$, respectively. \n\nChef $2$ first cooks $1$ serving of dish $1$, then cooks $1$ serving of dish $3$. The two students who ordered these dishes have waiting times of $7, 7+9=16$, respectively. \n\nThe total waiting time is $3+8+13+7+16=47$. \n\nAlthough dish $1$ and dish $3$ are cooked faster by chef $1$, if all servings of these dishes were cooked by chef $1$, the total waiting time would be longer. By assigning $1$ serving of dish $1$ and $1$ serving of dish $3$ to chef $2$, this arrangement ensures chef $2$ doesn't remain idle, reducing the total waiting time.\n\nIt can be proven that no better serving arrangement exists than the above.\n\n---\n\n### Constraints and Hints\n\nFor $100\\%$ of the data, $n \\leq 40$, $m \\leq 100$, $p \\leq 800$, and $t_{i,j} \\leq 1000$ (where $p = \\sum{p_i}$, representing the total number of students ordering dishes).\n\nThe values of $n$, $m$, and $p$ for each test case are as follows:\n\n| Test Case | $n$ | $m$ | $p$ |\n| :-: | :-: | :-: | :-: |\n| 1 | $n=5$ | $m=5$ | $p=10$ |\n| 2 | $n=40$ | $m=1$ | $p=400$ |\n| 3 | $n=40$ | $m=2$ | $p=300$ |\n| 4 | $n=40$ | $m=40$ | $p=40$ |\n| 5 | $n=5$ | $m=40$ | $p=100$ |\n| 6 | $n=10$ | $m=50$ | $p=200$ |\n| 7 | $n=20$ | $m=60$ | $p=400$ |\n| 8 | $n=40$ | $m=80$ | $p=600$ |\n| 9 | $n=40$ | $m=100$ | $p=800$ |\n| 10 | $n=40$ | $m=100$ | $p=800$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2319, "prompt": "### Problem Description\n\nSylvia is a girl who loves learning.\n\nRecently, Sylvia participated in her school\u2019s military training. As we all know, military training often involves standing in a square formation. Sylvia\u2019s square formation consists of $n \\times m$ students, with $n$ rows and $m$ columns.\n\nFor ease of management, the instructor numbered the students from $1$ to $n \\times m$ at the beginning of training, in front-to-back, left-to-right order (as shown in the example below). Specifically, initially, the student in row $i$ and column $j$ has the number $(i \u2212 1) \\times m + j$.\n\nHowever, during formation exercises, it sometimes happens that a student leaves the team due to various reasons. Over the course of a day, a total of $q$ such departure events occur. Each student departure event can be described using a pair $(x, y)$ ($1 \\leq x \\leq n, 1 \\leq y \\leq m)$, indicating that the student at row $x$ and column $y$ left the formation.\n\nWhen a student leaves the formation, a vacancy appears. To maintain the integrity of the formation, the instructor issues two sequential commands:\n\n1. **Align to the left**: At this point, the first column remains unchanged, and all other students shift left to fill the vacancy. After this command, the vacancy will be in row $x$, column $m$.\n\n2. **Align forward**: At this point, the first row remains unchanged, and all other students shift upward to fill the vacancy. After this command, the vacancy will be in row $n$, column $m$.\n\nThe instructor specifies that two or more students cannot leave at the same time. This means that each student can only leave the formation after the previously departed student has returned to fill the vacancy. Thus, at the moment when each departing student is about to return, there is only one vacancy in the square formation, located in row $n$, column $m$. The departing student naturally fills this position.\n\nSince standing in formation is really boring, Sylvia wants to calculate the number of each departing student for every single departure event.\n\n**Note**: The numbering of each student does not change due to departure events. After such events, the numbering of students in the formation may become disordered.\n\n---\n\n### Input Format\n\nThe input consists of $q+1$ lines:\n\n- The first line contains three positive integers $n$, $m$, and $q$, separated by spaces, indicating the size of the square formation with $n$ rows and $m$ columns, and the occurrence of a total of $q$ events.\n- The next $q$ lines describe the $q$ events in chronological order. Each line consists of two integers $x, y$, separated by a space, indicating that the student in row $x$, column $y$ is the one leaving the formation in this event.\n\n---\n\n### Output Format\n\nFor each event, output a single integer on a separate line, indicating the number of the departing student for that event.\n\n---\n\n### Example\n\n$$\\large\\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}\\Rightarrow\\begin{bmatrix}&2\\\\3&4\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&\\\\3&4\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}$$\n\n$$\\large\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}$$\n\n$$\\large\\begin{bmatrix}2&4\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&\\\\3&1\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&1\\\\3&\\end{bmatrix}\\Rightarrow\\begin{bmatrix}2&1\\\\3&4\\end{bmatrix}$$\n\nThe process of rearranging the formation for each event is illustrated in the diagram above.\n\nFor the first event, student number $1$ leaves the formation, resulting in the vacancy being in the first row and first column. All students then align to the left, with student number $2$ moving one step left to fill the vacancy, which then moves to the first row and second column. All students then align forward, with student number $4$ moving one step upward, and the vacancy moves to the second row and second column. Finally, student number $1$ returns to fill the vacancy.\n\n---\n\n### Data Constraints and Notes\n\n\n\n| Test Case ID | $n$ | $m$ | $q$ | Other Constraints |\n|:-:|:-:|:-:|:-:|:-:|\n| $1\\sim 6$ | $\\le 1000$ | $\\le 1000$ | $\\le 500$ | None |\n| $7\\sim 10$ | $\\le 5 \\times 10^{4}$ | $\\le 5 \\times 10^{4}$ | $\\le 500$ | None |\n| $11,12$ | $=1$ | $\\le 10^{5}$ | $\\le 10^{5}$ | All events $x=1$ |\n| $13,14$ | $=1$ | $\\le 3\\times 10^{5}$ | $\\le 3\\times 10^{5}$ | All events $x=1$ |\n| $15,16$ | $\\le 3 \\times 10^{5}$ | $\\le 3\\times 10^{5}$ | $\\le 3\\times 10^{5}$ | All events $x=1$ |\n| $17,18$ | $\\le 10^{5}$ | $\\le 10^{5}$ | $\\le 10^{5}$ | None |\n| $19,20$ | $\\le 3 \\times 10^{5}$ | $\\le 3 \\times 10^{5}$ | $\\le 3 \\times 10^{5}$ | None |\n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2302, "prompt": "### Problem Description\nDr. P abstracts his computational tasks as operations on an integer.\n\nSpecifically, there is an integer $x$, which initially has a value of $0$.\n\nThen, there are $n$ operations, each being one of the two types below:\n\n- `1 a b`: Add the integer $a\\cdot 2^b$ to $x$, where $a$ is an integer, and $b$ is a non-negative integer.\n\n- `2 k`: Query the value of the $2^k$ bit in the binary representation of $x$ (i.e., whether this bit is $1$ or $0$, with $1$ representing $2^k$).\n\nIt is guaranteed that, at any time, $x \\geqslant 0$.\n\n### Input Format\nThe first line of input contains four positive integers $n,t_1,t_2,t_3$, where the meaning of $n$ is described above, and $t_1$, $t_2$, $t_3$ correspond to the subtasks.\n\nThe next $n$ lines each describe one operation, with the format and meaning detailed above.\n\n### Output Format\nFor each query operation, output one line representing the result of the query ($0$ or $1$). There is no output for addition operations.\n\nAcross all test cases, $1 \\leqslant t_1 \\leqslant 3$, $1 \\leqslant t_2 \\leqslant 4$, $1 \\leqslant t_3 \\leqslant 2$. The specific constraints for different values of $t_1$, $t_2$, and $t_3$ are as follows:\n\n- For test cases where $t_1 = 1$, $a = 1$.\n- For test cases where $t_1 = 2$, $|a| = 1$.\n- For test cases where $t_1 = 3$, $|a| \\leqslant 10^9$.\n- For test cases where $t_2 = 1$, $0 \\leqslant b, k \\leqslant 30$.\n- For test cases where $t_2 = 2$, $0 \\leqslant b, k \\leqslant 100$.\n- For test cases where $t_2 = 3$, $0 \\leqslant b, k \\leqslant n$.\n- For test cases where $t_2 = 4$, $0 \\leqslant b, k \\leqslant 30n$.\n- For test cases where $t_3 = 1$, all query operations occur after all modification operations.\n- For test cases where $t_3 = 2$, there is no guarantee on the order of query operations and modification operations.\n\nThis problem consists of 25 test cases, each worth 4 points. The data range for each test case is described below:\n\n| Test Case Number | $n \\leq$ | $t_1$ | $t_2$ | $t_3$ |\n|:-:|:-:|:-:|:-:|:-:|\n| $1$ | $10$ | $3$ | $1$ | $2$ |\n| $2$ | $100$ | $3$ | $2$ | $2$ |\n| $3$ | $2000$ | $3$ | $2$ | $2$ |\n| $4$ | $4000$ | $1$ | $3$ | $2$ |\n| $5$ | $6000$ | $3$ | $3$ | $1$ |\n| $6$ | $8000$ | $2$ | $3$ | $2$ |\n| $7$ | $9000$ | $3$ | $4$ | $2$ |\n| $8$ | $10000$ | $3$ | $3$ | $2$ |\n| $9$ | $30000$ | $3$ | $4$ | $2$ |\n| $10$ | $50000$ | $3$ | $4$ | $1$ |\n| $11$ | $60000$ | $3$ | $3$ | $2$ |\n| $12$ | $65000$ | $2$ | $4$ | $2$ |\n| $13$ | $70000$ | $3$ | $4$ | $2$ |\n| $14$ | $200000$ | $3$ | $4$ | $2$ |\n| $15$ | $300000$ | $2$ | $4$ | $2$ |\n| $16$ | $400000$ | $3$ | $4$ | $2$ |\n| $17$ | $500000$ | $3$ | $3$ | $2$ |\n| $18$ | $600000$ | $3$ | $4$ | $2$ |\n| $19$ | $700000$ | $3$ | $4$ | $2$ |\n| $20$ | $800000$ | $1$ | $4$ | $2$ |\n| $21$ | $900000$ | $2$ | $4$ | $2$ |\n| $22$ | $930000$ | $3$ | $3$ | $2$ |\n| $23$ | $960000$ | $3$ | $4$ | $1$ |\n| $24$ | $990000$ | $3$ | $3$ | $2$ |\n| $25$ | $1000000$ | $3$ | $4$ | $2$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2603, "prompt": "### Problem Description\nOn the occasion of the National Day in the Kingdom of H, the king invited $n$ ministers to participate in a prize-winning game. First, he asked each minister to write an integer on their left and right hands. The king also wrote an integer on his left and right hands. Then, the $n$ ministers were arranged in a line, with the king standing at the front of the queue. Once the lineup was complete, all the ministers would receive a certain number of gold coins as a reward. The number of coins each minister receives is calculated as follows: **\"The product of all the integers on the left hands of the people standing in front of that minister in the queue\" divided by **\"the integer on the minister's right hand,\" rounded down.**\n\nThe king wanted to ensure that no single minister ended up receiving too much of a reward. Therefore, he sought your help in rearranging the lineup of the ministers to minimize the maximum reward received by any minister. **Note that the king's position is fixed at the front of the lineup.**\n\n### Input Format\nThe first line contains an integer $n$ denoting the number of ministers.\n\nThe second line contains two integers $a$ and $b$, separated by a space, representing the numbers written on the king's left and right hands, respectively.\n\nThe following $n$ lines each contain two integers $a$ and $b$, separated by a space, representing the two integers on the left and right hands of each minister.\n\n### Output Format\nOutput a single integer: the minimum possible value of the maximum reward received by any minister after rearranging the lineup.\n\n### Example\n- In the arrangement with ministers 1, 2, 3, the maximum reward is $2$;\n- In the arrangement with ministers 1, 3, 2, the maximum reward is $2$;\n- In the arrangement with ministers 2, 1, 3, the maximum reward is $2$;\n- In the arrangement with ministers 2, 3, 1, the maximum reward is $9$;\n- In the arrangement with ministers 3, 1, 2, the maximum reward is $2$;\n- In the arrangement with ministers 3, 2, 1, the maximum reward is $9$.\n\nThus, the minimum possible value of the maximum reward is $2$. The output is $2$.\n\n### Constraints and Notes\n- For 20% of the test cases: $1 \\leq n \\leq 10$, $0 < a, b < 8$;\n- For 40% of the test cases: $1 \\leq n \\leq 20$, $0 < a, b < 8$;\n- For 60% of the test cases: $1 \\leq n \\leq 100$;\n- For 60% of the test cases, the answer is guaranteed to not exceed $10^9$;\n- For 100% of the test cases: $1 \\leq n \\leq 1,000$, $0 < a, b < 10,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2612, "prompt": "### Problem Description\nGardener Dongdong has planted a row of flowers, each with its own height. As the flowers grow larger, they become more cramped. Dongdong has decided to remove some of the flowers from this row to leave the remaining ones with space to grow. At the same time, Dongdong wants the arrangement of the remaining flowers to look aesthetically pleasing.\n\nSpecifically, the heights of Dongdong's flowers can be represented as a sequence of integers $h_1, h_2, \\dots, h_n$. Suppose that after removing some flowers, the heights of the remaining flowers are $g_1, g_2, \\dots, g_m$. Dongdong wants at least one of the following two conditions to be satisfied:\n\n* For all integers $i$, $g_{2i} > g_{2i-1}$ and $g_{2i} > g_{2i+1}$;\n* For all integers $i$, $g_{2i} < g_{2i-1}$ and $g_{2i} < g_{2i+1}$.\n\nNote that in the case where $m = 1$, both of the conditions above are simultaneously satisfied. When $m > 1$, at most one of the conditions can be satisfied.\n\nPlease determine the maximum number of flowers that Dongdong can leave in place.\n\n---\n\n### Input Format\nThe first line contains a single integer $n$, representing the initial number of flowers.\n\nThe second line contains $n$ integers, $h_1, h_2, \\dots, h_n$, representing the heights of each flower.\n\n---\n\n### Output Format\nOutput a single integer $m$, representing the maximum number of flowers that can be left in place.\n\n---\n\n### Example\nThere are multiple ways to leave exactly $3$ flowers remaining. For instance, keeping the $1^\\text{st}$, $4^\\text{th}$, and $5^\\text{th}$ flowers, with heights $5$, $1$, and $2$ respectively, satisfies condition $B$.\n\n---\n\n### Constraints and Hints\nFor $15\\%$ of the test cases, $n \\leq 10$;\n\nFor $25\\%$ of the test cases, $n \\leq 25$;\n\nFor $55\\%$ of the test cases, $n \\leq 1,000$, $h_i \\leq 1,000$;\n\nFor $80\\%$ of the test cases, $n \\leq 100,000$, $h_i \\leq 10^6$, where all $h_i$ are randomly generated under a uniform distribution across arbitrary intervals;\n\nFor $100\\%$ of the test cases, $1 \\leq n \\leq 2,000,000$, $0 \\leq h_i \\leq 10^9$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2084, "prompt": "### Problem Description\n\nThe King of Fleas and the King of Crickets are playing a game.\n\nThey are arranging their armies on a grid with $n$ rows and $m$ columns. Among these, $c$ cells $(0 \\leq c \\leq n \\cdot m)$ have a cricket placed on them, and each of the other cells has a flea.\n\nWe consider two fleas occupying adjacent cells (sharing an edge) as **neighbors**.\n\nWe consider two fleas to be **connected** if and only if they are neighbors, or there exists another flea that is connected to both of them.\n\nNow, the King of Crickets wishes to replace some (zero, one, or more) fleas with crickets such that after this replacement, there exist at least two fleas that are not connected.\n\n\"left\"\n\"right\"\n\nFor example, we use the image \"flea\" to represent a flea and the image \"cricket\" to represent a cricket. The left diagram demonstrates a scenario where $n=4$, $m=4$, and $c=2$.\n\nIn this scenario, the King of Crickets can achieve his goal by replacing the fleas at the cells in the second row, second column, and the third row, third column with crickets, as shown in the right diagram. There is no better solution, though there may be other ways to replace two fleas. \n\nYour task is to determine whether it is possible for the King of Crickets to achieve his goal. If it is possible, you need to minimize the number of fleas replaced.\n\n---\n\n### Input Format\n\nThe input consists of multiple test cases.\n\nThe first line of the input contains a single integer $T$, representing the number of test cases.\n\nFor each of the next $T$ test cases:\n\n- The first line contains three integers $n$, $m$, and $c$.\n- The next $c$ lines each contain two integers $x, y$, where $x$ and $y$ denote the row and column indices of a cell occupied by a cricket. Each cricket is described only once in the input. \n- Consecutive integers on the same line are separated by a single space.\n\n---\n\n### Output Format\n\nFor each test case, output a single line containing the answer.\n\n- If it is impossible for the King of Crickets to achieve his goal, output `-1`.\n- Otherwise, output the minimum number of fleas that must be replaced.\n\n---\n\n### Examples\n\n**Example 1 (First Case)** \nThis case corresponds to the situation described in the problem description. \n\n**Example 2 (Second Case)** \nThe King of Crickets can achieve his goal by replacing the flea at the second row, second column with a cricket such that there exist two fleas that are not connected. There is no better solution in this case.\n\n**Example 3 (Third Case)** \nInitially, there are already two fleas that are not connected, so no replacement is necessary.\n\n**Example 4 (Fourth Case)** \nSince there is at most one flea, it is impossible to make two fleas unconnected no matter how replacements are made.\n\n---\n\n### Constraints and Notes\n\nFor all test cases:\n\n- $1 \\leq n, m \\leq 10^9$\n- $0 \\leq c \\leq \\min(n \\cdot m, 10^5)$\n- $1 \\leq x \\leq n$\n- $1 \\leq y \\leq m$\n- $1 \\leq T \\leq 20$\n\nLet $\\sum c$ denote the total sum of $c$ values across all $T$ test cases in a single dataset. It is guaranteed that $\\sum c \\leq 10^5$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2589, "prompt": "### Problem Description\n\nDr. Hanks is a renowned expert in the BT (Bio-Tech) field, and his son\u2019s name is Hankson. Now, after returning home from school, Hankson is pondering an interesting problem.\n\nToday in class, the teacher explained how to calculate the greatest common divisor (GCD) and least common multiple (LCM) of two positive integers $c_1$ and $c_2$. Now, Hankson believes he has fully mastered this knowledge and has started thinking about a reverse problem concerning \"finding the GCD\" and \"finding the LCM.\" The problem is as follows: Given four positive integers $a_0, a_1, b_0, b_1$, suppose there exists some unknown positive integer $x$ that satisfies the following conditions:\n\n1. The greatest common divisor of $x$ and $a_0$ is $a_1$;\n2. The least common multiple of $x$ and $b_0$ is $b_1$.\n\nHankson's \"reverse problem\" is to find all integers $x$ that satisfy these conditions. However, after a bit of thought, he realizes that such $x$ may not be unique, or may not even exist. Therefore, he\u2019s shifted focus to determine how many such integers $x$ satisfy the conditions. Your task is to help him write a program to solve this problem.\n\n---\n\n### Input Format\n\nThe first line contains a positive integer $n$, representing the number of test cases. \nThe next $n$ lines each contain a group of four positive integers $a_0, a_1, b_0, b_1$, with each pair of integers separated by a space. \nThe input data guarantees that $a_0$ is divisible by $a_1$ and $b_1$ is divisible by $b_0$.\n\n---\n\n### Output Format\n\nOutput a total of $n$ lines. The result for each test case should occupy one line and be a single integer. \nFor each group of input data: \n- If no such $x$ exists, output `0`. \n- If there are $k$ integers $x$ that satisfy the conditions, output $k$.\n\n---\n\n### Example\n\n#### Input:\n```plaintext\n2\n36 9 24 288\n48 24 1776 1776\n```#### Output:\n```plaintext\n6\n2\n```\n\n#### Explanation: \n- For the first test case, the possible values of $x$ are $9, 18, 36, 72, 144, 288$, for a total of $6$ values. \n- For the second test case, the possible values of $x$ are $48$ and $1776$, for a total of $2$ values.\n\n---\n\n### Constraints and Hints\n\n- For $50\\%$ of the test cases, it is guaranteed that $a_0, a_1, b_0, b_1 \\leq 10^4$ and $n \\leq 100$. \n- For $100\\%$ of the test cases, it is guaranteed that $1 \\leq a_0, a_1, b_0, b_1 \\leq 2 \\times 10^9$ and $n \\leq 2000$. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2363, "prompt": "### Problem Description\nKiana has recently become obsessed with a magical game. \nIn simple terms, the game takes place on a 2D plane. A slingshot is located at $ (0, 0) $, and each time, Kiana can use it to shoot a bird into the first quadrant. The birds follow flight trajectories in the form of $ y = ax^2 + bx $, where $ a $ and $ b $ are parameters specified by Kiana, and $ a $ must satisfy $ a < 0 $. When a bird falls back to the ground (i.e., the $ x $-axis), it instantly disappears.\n\nIn a certain level of the game, there are $ n $ pigs located in the first quadrant, with the $ i $-th pig positioned at $ (x_i, y_i) $. If a bird's flight trajectory passes through $ (x_i, y_i) $, the $ i $-th pig will be eliminated, and the bird will continue to fly along its original trajectory. If the bird\u2019s trajectory doesn\u2019t pass through $ (x_i, y_i) $, then the bird's flight has no effect on the $ i $-th pig. \nFor example, if two pigs are located at $ (1, 3) $ and $ (3, 3) $, Kiana can choose to shoot a bird with the flight trajectory $ y = -x^2 + 4x $, and both pigs will be eliminated by this bird. \nThe goal of the game is to eliminate all pigs with as few birds as possible.\n\nEach level of this magical game is quite challenging, so Kiana has entered some mysterious instructions to make it easier for herself to complete the game. These instructions are specified in the \"Input Format\" section below. \nIt is assumed that there are $ T $ levels in this game, and Kiana wants to figure out, for each level, how many birds are needed at minimum to eliminate all the pigs. Since Kiana isn\u2019t good at calculations, she asks you to solve this for her.\n\n### Input Format\nThe first line contains a positive integer $ T $, representing the total number of game levels.\n\nThe following input consists of information for these $ T $ levels. For each level, the first line contains two non-negative integers $ n $ and $ m $, representing the number of pigs and the type of mysterious instructions entered by Kiana for that level, respectively.\n\nThe next $ n $ lines contain two positive real numbers $ (x_i, y_i) $, indicating that the $ i $-th pig is located at $ (x_i, y_i) $. It is guaranteed that no two pigs in the same level have the exact same coordinates.\n\n- If $ m = 0 $, it means Kiana entered an instruction with no effect. \n- If $ m = 1 $, this level satisfies: at most $ \\lceil \\frac{n}{3} + 1 \\rceil $ birds are required to eliminate all the pigs. \n- If $ m = 2 $, this level satisfies: there must exist an optimal solution where at least one bird eliminates at least $ \\lfloor \\frac{n}{3} \\rfloor $ pigs.\n\nThe constraints guarantee that $ 1 \\leq n \\leq 18 $, $ 0 \\leq m \\leq 2 $, $ 0 < x_i, y_i < 10 $, and all real numbers in the input are preserved to two decimal places.\n\nIn the above notation, $ \\lceil x \\rceil $ and $ \\lfloor x \\rfloor $ represent the ceiling and floor functions of $ x $, respectively.\n\n### Output Format\nFor each level, output a single line.\n\nEach line contains a positive integer representing the minimum number of birds required to eliminate all the pigs in the corresponding level.\n\n### Sample 1\nIn this example, there are two levels.\n\nFor the first level, the situation is the same as described in the \"Problem Description\": there are $ 2 $ pigs located at $ (1.00, 3.00) $ and $ (3.00, 3.00) $, which can be eliminated by shooting one bird on the trajectory $ y = -x^2 + 4x $.\n\nIn the second level, there are $ 5 $ pigs, but upon observation, it is found that all their coordinates lie on the parabola $ y = -x^2 + 6x $, so Kiana only needs to shoot one bird to eliminate all the pigs.\n\n### Sample 2\n\n(additional examples can be added here for demonstration consistency)\n\n### Sample 3\n\n(additional examples can be added here for demonstration consistency)\n\n### Constraints and Hints\n\n| Test Point Index | $n\\leqslant$ | $m=$ | $T\\leqslant$ |\n| :----------: | :----------: | :----------: | :----------: |\n| $1$ | $2$ | $0$ | $10$ |\n| $2$ | $2$ | $0$ | $30$ |\n| $3$ | $3$ | $0$ | $10$ |\n| $4$ | $3$ | $0$ | $30$ |\n| $5$ | $4$ | $0$ | $10$ |\n| $6$ | $4$ | $0$ | $30$ |\n| $7$ | $5$ | $0$ | $10$ |\n| $8$ | $6$ | $0$ | $10$ |\n| $9$ | $7$ | $0$ | $10$ |\n| $10$ | $8$ | $0$ | $10$ |\n| $11$ | $9$ | $0$ | $30$ |\n| $12$ | $10$ | $0$ | $30$ |\n| $13$ | $12$ | $1$ | $30$ |\n| $14$ | $12$ | $2$ | $30$ |\n| $15$ | $15$ | $0$ | $15$ |\n| $16$ | $15$ | $1$ | $15$ |\n| $17$ | $15$ | $2$ | $15$ |\n| $18$ | $18$ | $0$ | $5$ |\n| $19$ | $18$ | $1$ | $5$ |\n| $20$ | $18$ | $2$ | $5$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2425, "prompt": "### Problem Description\n\nIn the year $2044$, humanity has entered the space age.\n\nCountry L has $n$ planets and $n - 1$ bidirectional space routes. Each space route connects two planets and these $n - 1$ space routes form a connected graph of all the planets in Country L.\n\nA logistics company managed by Xiao P has received numerous transportation plans. Each transportation plan specifies that a logistics spaceship needs to travel from planet $u_i$ to planet $v_i$ along the fastest space route. Clearly, traveling through a space route costs time. For space route $j$, the time required for any spaceship to traverse it is $t_j$, and there is no interference between different spaceships.\n\nTo foster technological innovation, the king of Country L allows Xiao P's logistics company to participate in the construction of space routes. Specifically, Xiao P is permitted to upgrade one of the space routes into a wormhole. A wormhole allows spaceships to traverse it without consuming any time.\n\nBefore the construction of the wormhole is completed, Xiao P\u2019s logistics company has already pre-scheduled $m$ transportation plans. Once the wormhole is complete, these $m$ transportation plans will begin simultaneously, with all spaceships departing at the same time. Xiao P's logistics company\u2019s phase of work is considered complete when all $m$ transportation plans are finished.\n\nIf Xiao P is free to choose which space route to upgrade to a wormhole, determine the minimum time required for Xiao P\u2019s logistics company to complete this phase of work.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of planets in Country L and the number of transportation plans pre-scheduled by Xiao P's company. The planets are numbered from $1$ to $n$.\n\nThe next $n - 1$ lines describe the construction details of the space routes. Each of these lines contains three integers $a_i$, $b_i$, and $t_i$, indicating that the $i$-th bidirectional space route is built between planets $a_i$ and $b_i$, and the time required for any spaceship to traverse it is $t_i$.\n\nThe subsequent $m$ lines describe the transportation plans. Each line contains two positive integers $u_j$ and $v_j$, indicating that the $j$-th transportation plan involves traveling from planet $u_j$ to planet $v_j$.\n\n---\n\n### Output Format\n\nOutput a single line containing one integer, which represents the minimum time required for Xiao P\u2019s logistics company to complete this phase of work.\n\n---\n\n### Example\n\n---\n\n### Data Range and Hints\n\nFor $100\\%$ of the test cases: \n$100 \\leq n \\leq 300,000$, \n$1 \\leq m \\leq 300,000$, \n$1 \\leq a_i, b_i, u_i, v_i \\leq n$, \n$0 \\leq t_i \\leq 10^3$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2501, "prompt": "### Problem Description\n\nWith the increasing popularity of smartphones, the demand for wireless networks is growing rapidly. A city has decided to cover public places within the city with wireless networks.\n\nAssume the city layout is a grid formed by exactly $129$ east-west streets and $129$ north-south streets, with a distance of $1$ between adjacent parallel streets. The east-west streets are numbered from $0, 1, 2, \\ldots, 128$ from north to south, and the north-south streets are numbered $0, 1, 2, \\ldots, 128$ from west to east. \nThe intersections of the east-west and north-south streets are designated as junctions, and it is specified that the intersection of the north-south street with number $x$ and the east-west street with number $y$ has coordinates $(x, y)$. At some of these junctions, there exist a certain number of public places. \n\nDue to budget constraints, the city can only install one large wireless transmitter. The coverage of this wireless transmitter is a square of side length $2d$ centered at the installation point. The coverage includes the boundaries of the square. \nFor example, the figure below illustrates the coverage area of a wireless transmitter with $d = 1$. \n\n![wireless.png](https://img.loj.ac.cn/2019/02/24/5c72325da31df.png)\n\nThe local government needs to install a wireless transmitter with a propagation parameter of $d$, and seeks your help to determine the best possible junction for installation, such that the maximum number of public places are covered.\n\n### Input Format\n\nThe first line contains an integer $d$, representing the propagation radius of the wireless transmitter. \n\nThe second line contains an integer $n$, representing the number of junctions with public places. \n\nThe next $n$ lines each contain three integers $x, y, k$, separated by a space, which respectively represent the coordinates $(x, y)$ of a junction and the number of public places at that junction. The same coordinates will only be provided once.\n\n### Output Format\n\nOutput a single line containing two integers, separated by a space, representing the number of installation site plans that can cover the maximum number of public places and the maximum number of public places that can be covered.\n\n### Example\n\n#### Input\n```\n1\n3\n1 1 5\n2 2 8\n4 4 3\n```#### Output\n```\n4 13\n```\n\n### Data Constraints and Hints\n\n$1 \\leq d \\leq 20$, $1 \\leq n \\leq 20$, $0 \\leq x \\leq 128$, $0 \\leq y \\leq 128$, $0 < k \\leq 1000000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 3758, "prompt": "### Problem Description\n\nDongdong has a rectangular piece of land where he grows energy plants that can harness solar energy. After these plants collect energy, Dongdong uses an energy collection machine to gather all the energy collected by the plants.\n\nDongdong has planted the energy plants in a very neat arrangement. There are $n$ columns in total, and each column has $m$ plants. The horizontal and vertical spacing between the plants is uniform. Therefore, each plant can be represented by a coordinate $(x, y)$, where $x$ ranges from $1$ to $n$ and $y$ ranges from $1$ to $m$, representing the $y$-th plant in column $x$.\n\nBecause the energy collection machine is large and inconvenient to move, Dongdong placed it at a corner of the land with coordinates $(0, 0)$.\n\nDuring energy collection, there is a certain amount of energy loss. If a plant connected to the energy collection machine has $k$ plants located along the line segment between the plant and the machine, the energy loss is calculated as $2k + 1$. For example, when the energy collection machine gathers energy from the plant at coordinate $(2, 4)$, there is $1$ plant $(1, 2)$ located along the line segment, resulting in an energy loss of $3$. Note that if there are no plants along the line segment between a plant and the energy collection machine, the energy loss is $1$. The goal is to calculate the total energy loss.\n\nBelow is an example of energy collection where $n = 5$ and $m = 4$, with a total of $20$ plants. The energy loss caused by the machine collecting energy from each plant is labeled on each plant.\n\n![1654079504639.png](https://img.loj.ac.cn/2022/06/01/da7540f14de33.png)\n\nIn this example, the total energy loss is $36$.\n\n---\n\n### Input Format\n\nA single line contains two integers $n$ and $m$.\n\n---\n\n### Output Format\n\nA single integer representing the total energy loss.\n\n---\n\n### Example 1\n\n```\nInput:\n5 4\n\nOutput:\n36\n```---\n\n### Example 2\n\n```\nInput:\n3 3\n\nOutput:\n18\n```\n\n---\n\n### Constraints and Notes\n\n- For $10\\%$ of the test cases: $n, m \\leq 10$.\n- For $50\\%$ of the test cases: $n, m \\leq 100$.\n- For $80\\%$ of the test cases: $n, m \\leq 10^3$.\n- For $90\\%$ of the test cases: $n, m \\leq 10^4$.\n- For $100\\%$ of the test cases: $1 \\leq n, m \\leq 10^5$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2317, "prompt": "### Problem Description\nThere is a large piece of cheese with a height of $h$. Its length and width can be considered infinite. Inside the cheese, there are many spherical cavities with the **same radius**. We can establish a spatial coordinate system in the cheese. In this coordinate system, the bottom surface of the cheese is at $z = 0$, and the top surface of the cheese is at $z = h$.\n\nNow, on the bottom surface of the cheese, there is a small mouse named Jerry who knows the coordinates of the centers of all the cavities inside the cheese. If two cavities are tangent or intersect, Jerry can travel from one cavity to the other. Specifically:\n\n- If a cavity is tangent to or intersects the bottom surface, Jerry can travel from the bottom surface of the cheese into the cavity.\n- If a cavity is tangent to or intersects the top surface, Jerry can travel from the cavity to the top surface of the cheese.\n\nJerry, located on the bottom surface of the cheese, wants to know whether he can reach the top surface using the existing cavities, **without damaging the cheese**.\n\nThe distance between two points $P_1(x_1,y_1,z_1)$ and $P_2(x_2,y_2,z_2)$ in space is calculated using the following distance formula:\n\n$$\n\\operatorname{dist}(P_1,P_2)=\\sqrt{(x_1-x_2)^2+(y_1-y_2)^2+(z_1-z_2)^2}\n$$\n\n### Input Format\nThe input file contains multiple test cases.\n\n- The first line of the input file contains a positive integer $T$, representing the number of test cases in the file.\n\n- For the next $T$ sets of data, each test case is formatted as follows:\n - The first line of each test case contains three positive integers $n, h,$ and $r$, separated by spaces. These represent the number of cavities in the cheese, the height of the cheese, and the radius of the cavities, respectively.\n - The following $n$ lines each contain three integers $x, y, z$, separated by spaces, representing the coordinates of the centers of the spherical cavities $(x, y, z)$.\n\n### Output Format\nThe output file contains $T$ lines, corresponding to the answers for the $T$ test cases. If Jerry can travel from the bottom surface to the top surface in the $i$-th test case, output \u201cYes\u201d. Otherwise, output \u201cNo\u201d. (Exclude quotation marks.)\n\n### Sample\n![cheese.png](https://img.loj.ac.cn/2021/12/29/5940a76e8e720.png)\n\n### Constraints and Notes\n- For $20\\%$ of the data, $n = 1,$ $1 \\le h , r \\le 10^4$, and the absolute value of the coordinates does not exceed $10^4$.\n- For $40\\%$ of the data, $1 \\le n \\le 8,$ $1 \\le h , r \\le 10^4$, and the absolute value of the coordinates does not exceed $10^4$.\n- For $80\\%$ of the data, $1 \\le n \\le 1000,$ $1 \\le h , r \\le 10^4$, and the absolute value of the coordinates does not exceed $10^4$.\n- For $100\\%$ of the data, $1 \\le n \\le 1000,$ $1 \\le h , r \\le 10^9,$ $T \\le 20$, and the absolute value of the coordinates does not exceed $10^9$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2673, "prompt": "### Problem Description\n\nThe vacation has started, and Xiao Z feels incredibly bored staying at home. He decides to go to the amusement park alone. Upon entering the park, Xiao Z takes a look at the park's map and realizes he can abstract the amusement park as an **undirected connected graph with $n$ attractions and $m$ roads, where this graph contains at most one cycle (i.e., $m$ can only equal $n$ or $n-1$)**.\n\nThe entrance, where Xiao Z currently stands, is also considered one of the attractions. Xiao Z doesn\u2019t know which attractions would be fun, so he decides to start from his current position and randomly visit one of the attractions connected by a road. He also decides **not to revisit any attraction (including the starting point)** that he has already visited. Being playful, Xiao Z will continue exploring until there are no unvisited attractions adjacent to his current position.\n\nThe attractions visited by Xiao Z in order form a non-repeating path, and he wants to know the **expected length** of this path.\n\nXiao Z has sketched a map of the amusement park and brought it home, but he forgot to label which attraction is the entrance. Therefore, he assumes that every attraction is equally likely to be the starting point (i.e., all attractions have an equal probability of being the starting point). Additionally, whenever he chooses the next attraction to visit, he does so by **equally and randomly selecting** one of the **unvisited adjacent attractions**.\n\n---\n\n### Input Format\n\nThe input consists of the following:\n\nThe first line contains two integers, $n$ and $m$, representing the number of attractions and roads, respectively.\n\nThe next $m$ lines each contain three integers, $X_i$, $Y_i$, $W_i$, which denote a road connecting attractions $X_i$ and $Y_i$ with a length of $W_i$. All attractions are labeled from $1$ to $n$, and there is at most one road between any two attractions.\n\n---\n\n### Output Format\n\nOutput a single line containing a real number, which is the expected length of the path.\n\n---\n\n### Example\n\nIn the example, there are a total of $6$ possible paths:\n\n| Path | Length | Probability |\n|:-------------:|:------:|:-----------:|\n| $1 \\rightarrow 4$ | $8$ | $\\frac{1}{4}$ |\n| $2 \\rightarrow 1$ | $3$ | $\\frac{1}{8}$ |\n| $2 \\rightarrow 4$ | $5$ | $\\frac{1}{8}$ |\n| $3 \\rightarrow 1$ | $4$ | $\\frac{1}{8}$ |\n| $3 \\rightarrow 4$ | $4$ | $\\frac{1}{8}$ |\n| $4 \\rightarrow 1$ | $8$ | $\\frac{1}{4}$ |\n\nThus, the expected length is: \n$$ \\text{Expected Length} = \\frac{8}{4} + \\frac{3}{8} + \\frac{5}{8} + \\frac{4}{8} + \\frac{4}{8} + \\frac{8}{4} = 6.00 $$\n\n---\n\n### Constraints and Notes\n\nFor $100\\%$ of the test cases, $1 \\leq W_i \\leq 100$.\n\n| Test Case ID | $n$ | $m$ | Description |\n|:------------:|:-----:|:-----:|:-----------------------------------------------:|\n| 1 | $n=10$ | $m=n-1$ | The graph forms a linear chain. |\n| 2 | $n=100$ | $m=n-1$ | Only node $1$ has a degree greater than $2$. |\n| 3 | $n=1000$ | $m=n-1$ | - |\n| 4 | $n=100000$ | $m=n-1$ | - |\n| 5 | $n=100000$ | $m=n-1$ | - |\n| 6 | $n=10$ | $m=n$ | - |\n| 7 | $n=100$ | $m=n$ | The number of nodes in the cycle $\\leq 5$. |\n| 8 | $n=1000$ | $m=n$ | The number of nodes in the cycle $\\leq 10$. |\n| 9 | $n=100000$ | $m=n$ | The number of nodes in the cycle $\\leq 15$. |\n| 10 | $n=100000$ | $m=n$ | The number of nodes in the cycle $\\leq 20$. |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2610, "prompt": "### Problem Description\n\nCountry A has $n$ cities, numbered from $1$ to $n$, connected by $m$ bidirectional roads. Each road has a weight limit for vehicles, referred to as the weight limit. There are $q$ freight trucks transporting goods, and the drivers want to know the maximum weight of goods each truck can carry without exceeding the weight limit of the roads.\n\n### Input Format\n\nThe first line of the input contains two integers $n$ and $m$ separated by a space, indicating that Country A has $n$ cities and $m$ roads.\n\nThe next $m$ lines each contain three integers $x$, $y$, and $z$, separated by spaces, indicating that there is a road between City $x$ and City $y$ with a weight limit of $z$. Note that $x \\neq y$, and there may be multiple roads between two cities.\n\nThe next line contains a single integer $q$, indicating that there are $q$ freight trucks requiring transportation.\n\nThe following $q$ lines each contain two integers $x$ and $y$, separated by a space, indicating that a truck needs to transport goods from City $x$ to City $y$. Note that $x \\neq y$.\n\n### Output Format\n\nThe output comprises $q$ lines, each containing a single integer. For each truck, output the maximum weight it can carry. If the truck cannot reach its destination, output $-1$.\n\n### Example\n\n**Input:**\n```\n5 6\n1 2 10\n2 3 20\n3 4 30\n4 5 40\n1 3 15\n3 5 25\n2\n1 5\n2 4\n```**Output:**\n```\n25\n20\n```\n\n### Constraints and Hints\n\n- For 30% of the data, $0 < n < 1\\,000$, $0 < m < 10\\,000$, $0 < q < 1\\,000$;\n- For 60% of the data, $0 < n < 1\\,000$, $0 < m < 50\\,000$, $0 < q < 1\\,000$;\n- For 100% of the data, $0 < n < 10\\,000$, $0 < m < 50\\,000$, $0 < q < 30\\,000$, $0 \\leq z \\leq 100\\,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2669, "prompt": "### Problem Description\n\nLittle T plans to open a food delivery restaurant in city C. The delivery time to a certain location is proportional to the shortest path distance between the restaurant and that location. Little T wants to choose a location for the restaurant such that the maximum distance to the furthest customer is minimized.\n\nThe customers of the restaurant are distributed across $N$ buildings in city C. These $N$ buildings are connected by exactly $N$ bidirectional roads, and no two roads connect the same pair of buildings. Furthermore, there exists at least one path, formed by bidirectional roads, between any two buildings. The food delivery restaurant can be located in any building or at any point along any road (the location on the road does not necessarily need to have integer distances from the endpoints of the road).\n\nGiven the map of city C (the road layout and their lengths), please determine the optimal location for the restaurant and output the distance to the furthest customer.\n\n---\n\n### Input Format\n\nThe first line contains an integer $N$, representing the number of buildings and roads in city C.\n\nThe next $N$ lines each contain three integers $A_i$, $B_i$, and $L_i$ ($1 \\leq i \\leq N; L_i > 0$), describing a road that connects building $A_i$ and building $B_i$ with a length of $L_i$.\n\n---\n\n### Output Format\n\nOutput a real number rounded to exactly one decimal place, representing the distance to the furthest customer from the optimal restaurant location.\n\n**Note**: Your result must have exactly one decimal place. Solutions with incorrect decimal formatting will not receive points.\n\n---\n\n### Sample 1\n\n![](https://i.loli.net/2018/06/10/5b1d07c4dc6a4.png)\n\nAs shown in the figure, the optimal location is at building $1$. The distances to the $4$ buildings are $0$, $1$, $2$, and $2$ respectively.\n\n---\n\n### Sample 2\n\n![](https://i.loli.net/2018/06/10/5b1d081843770.png)\n\n---\n\n### Sample 3\n\nRefer to the attached files `foodshop.in` and `foodshop.ans`.\n\n---\n\n### Constraints and Hints\n\n- For $10\\%$ of the test cases, $N \\leq 80$, and $L_i = 1$;\n- For $30\\%$ of the test cases, $N \\leq 600$, and $L_i \\leq 100$;\n- For $60\\%$ of the test cases, $N \\leq 2000$, and $L_i \\leq 10^9$;\n- For $100\\%$ of the test cases, $N \\leq 10^5$, and $L_i \\leq 10^9$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2304, "prompt": "## Problem Description\n\nJiulian is a fun-loving girl.\n\nSummer vacation has finally arrived, and Jiulian decided to invite her friends for swimming. She plans to carve out a rectangular area in the sea near her private beach as the swimming zone. However, the sea is full of various dangers: some areas are too deep, while others have poisonous jellyfish. She wants the selected swimming area to be completely safe.\n\nAfter preliminary analysis, the sea area can be viewed as a rectangular grid of $N$ meters in width and $1001$ meters in height. The bottom edge of this rectangular grid corresponds to her private beach. Each square of size $1 \\:\\textrm{m}\\times 1\\:\\textrm{m}$ represents a unit of marine area. She asked her father to measure whether each unit of the marine area is safe tomorrow. Upon obtaining this information, what she needs to do is select the swimming zone.\n\nHer ideal swimming zone must satisfy the following criteria:\n* It must ensure safety: every unit in the swimming zone must be safe.\n* It must be rectangular, i.e., the swimming zone must be a subgrid of size $a\\times b$.\n* It must be adjacent to the beach: the bottom boundary of the swimming zone must be adjacent to the bottom edge of the grid.\n\nFor example, when $N = 5$, if the measurement results are as follows (since $1001$ is too large, only the bottom three rows are displayed, with the remaining areas assumed to be dangerous):\n\n\"Screen\n\nShe can select a $1\\times 4$ swimming area in the bottom row or a $3\\times 1$ swimming area in the third column. Note that she cannot select a $1\\times 5$ swimming area in the top row since it does not touch the beach.\n\nTo make the swimming experience enjoyable for her friends, she wants the swimming area's size to be as large as possible. Therefore, she would select the $1\\times 4$ swimming area in the bottom row as the final option.\n\nAlthough she will only know whether each unit is safe tomorrow, she wants to estimate the probability of the swimming area's size being __exactly__ $K$ now. Based on a simple estimate, she assumes each unit has an independent probability $q$ of being safe and a probability $1 - q$ of being unsafe. She wants you to calculate the value of this probability.\n\n## Input Format\n\nA single line containing four positive integers $N, K, x, y$, where $1 \\leq x < y < 998244353$. The value of $q$ is $\\frac{x}{y}$.\n\n## Output Format\n\nPrint a single integer\u2014representing the result modulo $998244353$.\n\nSpecifically, let the result be expressed as the irreducible fraction $\\frac{a}{b}$, where $a$ and $b$ are coprime. Output the integer $x$ such that $bx \\equiv a \\mod 998244353$ and $0 \\leq x < 998244353$. It can be proven that such an integer $x$ is unique.\n\n## Example\n\n*(No examples provided in the question.)*\n\n## Hints and Constraints\n\n#### Hint\n\n$x^{p-1} \\equiv 1 \\pmod p$, where $p$ is a prime and $x \\in [1, p)$.\n\n#### Subtasks\n\n| Test Case Index | $N$ | $K$ |\n|:-:|:-:|:-:|\n| 1,2 | $=1$ | $\\leq 1000$ |\n| 3 | $\\leq 10$ | $\\leq 8$ |\n| 4 | $\\leq 10$ | $\\leq 9$ |\n| 5 | $\\leq 10$ | $\\leq 10$ |\n| 6 | $\\leq 1000$ | $\\leq 7$ |\n| 7 | $\\leq 1000$ | $\\leq 8$ |\n| 8 | $\\leq 1000$ | $\\leq 9$ |\n| 9,10,11 | $\\leq 1000$ | $\\leq 100$ |\n| 12,13,14 | $\\leq 1000$ | $\\leq 1000$ |\n| 15,16 | $\\leq 10^9$ | $\\leq 10$ |\n| 17,18 | $\\leq 10^9$ | $\\leq 100$ |\n| 19,20 | $\\leq 10^9$ | $\\leq 1000$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2316, "prompt": "### Problem Description\n\nCeci loves visiting parks. A park can be represented as a directed graph with $N$ nodes and $M$ edges, without self-loops or multiple edges between any two nodes. Node $1$ is the entry to the park, and node $N$ is the exit. Each edge has a non-negative weight, which represents the time Ceci needs to spend traversing that edge. \n\nCeci visits the park every day. She always starts at node $1$ and exits at node $N$.\n\nCeci enjoys exploring new paths and doesn't want her routes to be exactly the same on different days. Additionally, as a diligent student, Ceci doesn\u2019t want to spend too much time walking in the park. If the shortest path from node $1$ to node $N$ has a length of $d$, Ceci will only consider routes with a length no greater than $d + K$. \n\nCeci wants to know how many such valid routes exist. Can you help her with the answer?\n\nTo avoid outputting excessively large numbers, output the answer modulo $P$.\n\nIf there are infinitely many valid routes, output $\u22121$.\n\n---\n\n### Input Format\n\nThe first line contains an integer $T$, representing the number of test cases. \n\nFor the next $T$ test cases: \n\n- The first line contains four integers $N, M, K, P$, separated by spaces.\n- The next $M$ lines each contain three integers $a_i, b_i, c_i$, indicating a directed edge from node $a_i$ to node $b_i$ with a weight of $c_i$. Each pair of integers is separated by a space.\n\n---\n\n### Output Format\n\nThe output should contain $T$ lines, each containing one integer representing the answer.\n\n---\n\n### Example\n\nFor the first test case, the shortest path has a length of $3$. \n\nThe three valid paths are: \n\n$1 - 5, 1 - 2 - 4 - 5, 1 - 2 - 3 - 5$. \n\n---\n\n### Sample Input \n\n``` \n1 \n5 6 0 100 \n1 2 1 \n2 3 1 \n2 4 1 \n3 5 1 \n4 5 1 \n1 5 3 \n```### Sample Output \n\n``` \n3 \n```\n\n---\n\n### Constraints and Hints\n\nFor different test cases, the maximum scale of each parameter can be **no larger than** the following:\n\n| Test Case Index | $T$ | $N$ | $M$ | $K$ | Edge with weight $0$ exists? |\n|:---------------:|:---:|:---:|:---:|:---:|:----------------------------:|\n| $1$ | $5$ | $5$ | $10$| $0$ | No |\n| $2$ | $5$ | $1000$ | $2000$ | $0$ | No |\n| $3$ | $5$ | $1000$ | $2000$ | $50$ | No |\n| $4$ | $5$ | $1000$ | $2000$ | $50$ | No |\n| $5$ | $5$ | $1000$ | $2000$ | $50$ | No |\n| $6$ | $5$ | $1000$ | $2000$ | $50$ | Yes |\n| $7$ | $5$ | $100000$ | $200000$ | $0$| No |\n| $8$ | $3$ | $100000$ | $200000$ | $50$| No |\n| $9$ | $3$ | $100000$ | $200000$ | $50$| Yes |\n| $10$ | $3$ | $100000$ | $200000$ | $50$| Yes |\n\nFor $100\\%$ of the data: \n\n$1 \\le P \\le 10^9, 1 \\le a_i, b_i \\le N, 0 \\le c_i \\le 1000$. \n\nThe data guarantees that there is at least one valid route.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2592, "prompt": "### Problem Description\n\nXiao Chen has a machine translation software installed on his computer, which he often uses to translate English articles.\n\nThe principle behind this translation software is quite simple. It works sequentially, translating each English word into its corresponding Chinese meaning. When processing each English word, the software first looks up its Chinese meaning in the memory. If the translation exists in the memory, it uses that for the translation. If not, the software searches for the word's meaning in the dictionary stored on external memory, translates the word, and then stores the word and its meaning in the memory for future lookups and translations.\n\nAssume the memory has $M$ slots, each capable of storing a word and its translation. Every time the software needs to store a new word in memory:\n1. If the current number of words in memory does not exceed $M\u22121$, the software will store the new word in an unused memory slot.\n2. If the memory already holds $M$ words, the software will evict the earliest-stored word to free up a slot and then store the new word.\n\nAssume the length of an English article is $N$ words. Given this article, how many times will the translation software need to look up the dictionary stored on external memory? Assume that the memory is empty at the beginning of the translation process.\n\n---\n\n### Input Format\n\nThe input consists of 2 lines, with numbers separated by a single space:\n\n1. The first line contains two positive integers $M$ and $N$, representing the memory capacity and the length of the article, respectively.\n2. The second line contains $N$ non-negative integers in article order, where each number (not exceeding $1,000$) represents an English word. Two words are the same if and only if they correspond to the same non-negative integer.\n\n---\n\n### Output Format\n\nThe output consists of a single integer, representing the number of times the software needs to look up the dictionary.\n\n---\n\n### Example 1\n\nKey steps of dictionary lookups and memory updates are given below; each line shows the memory state after processing a word, with the initial state denoted as \"empty\":\n\n- `empty`: The memory starts empty.\n1. `$1$`: Lookup word `$1$` and add it to memory.\n2. `$1$ $2$`: Lookup word `$2$` and add it to memory.\n3. `$1$ $2$`: Find word `$1$` in memory.\n4. `$1$ $2$ $5$`: Lookup word `$5$` and add it to memory.\n5. `$2$ $5$ $4$`: Lookup word `$4$` and replace word `$1$` in memory.\n6. `$2$ $5$ $4$`: Find word `$4$` in memory.\n7. `$5$ $4$ $1$`: Lookup word `$1$` and replace word `$2$` in memory.\n\nTotal dictionary lookups: `$5$`.\n\n---\n\n### Example 2\n\n_(No example text provided in original prompt.)_\n\n---\n\n### Data Range and Hints\n\n- For $10\\%$ of the test cases, $M=1$, and $N \\leq 5$.\n- For $100\\%$ of the test cases, $0 < M \\leq 100$ and $0 < N \\leq 1,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2597, "prompt": "### Problem Description\n\nAlong the riverside of Lijiang, there are $n$ uniquely styled inns, numbered from $1$ to $n$ according to their positions.\n\nEach inn is decorated using one of $k$ different color tones (numbered $0$ through $k-1$), and each inn has its own coffee shop with a minimum spending requirement.\n\nTwo tourists traveling to Lijiang share a preference for the same color tone, but they also want to try two different inns. Therefore, they decide to each stay in a different inn but with the same color tone.\n\nIn the evening, they plan to visit a coffee shop for coffee. The coffee shop must be located somewhere between the two inns (inclusive of the inns they stay in), and its minimum spending requirement must not exceed $p$.\n\nThey are curious about how many valid accommodation combinations exist such that the above evening coffee conditions are satisfied.\n\n---\n\n### Input Format\n\nThe input consists of $n+1$ lines.\n\n- The first line contains three integers $n$, $k$, and $p$, separated by a space, representing the number of inns, the total number of color tones, and the maximum acceptable minimum spending for the coffee shop, respectively. \n\n- The next $n$ lines each contain two integers, separated by a space. For the $i$-th line, the first integer represents the decoration color tone of Inn $i$, and the second integer represents the minimum spending required for the coffee shop in Inn $i$.\n\n---\n\n### Output Format\n\nThe output consists of a single line with one integer, representing the total number of valid accommodation combinations.\n\n---\n\n### Example\n\n![hotel.png](https://img.loj.ac.cn/2021/12/29/729407abe93ec.png)\n\nThe two tourists must stay in inns decorated with the **same color tone**, and all valid accommodation combinations include:\n- Stay in Inns $1$ and $3$,\n- Stay in Inns $2$ and $4$,\n- Stay in Inns $2$ and $5$,\n- Stay in Inns $4$ and $5$.\n\nHowever, if choosing Inns $4$ and $5$, the coffee shops between these two inns have a minimum spending requirement of $4$, but the maximum acceptable spending is $3$, which does not meet the condition. Thus, only the first three combinations satisfy the conditions.\n\n---\n\n### Constraints and Hints\n\n- For $25\\%$ of the test cases, $n \\leq 100$.\n- For $40\\%$ of the test cases, $n \\leq 1,000$.\n- For $80\\%$ of the test cases, $n \\leq 200,000$, with $0 < k \\leq 50$.\n\n\n- For $100\\%$ of the test cases, $2 \\leq n \\leq 2 \\times 10^6$, $0 < k \\leq 10^4$, $0 \\leq p \\leq 100$, $0 \\leq$ coffee shop minimum spending requirement $\\leq 100$.\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2723, "prompt": "### Problem Description\n\nJiulian is a girl who loves creating problems.\n\nAfter this year\u2019s World Final ended, Jiulian became particularly fond of computational geometry. She decided to create a computational geometry problem for the NOI exam \u2014 a problem with only the name and its association with computational geometry.\n\nFirstly, Jiulian provides a rooted tree $T$ with $n\\ (n \\geq 2)$ nodes, where the root node is labeled as $1$. A leaf node is defined as any node (excluding the root) with a degree of exactly $1$. The figure below shows an example tree $T$, where the set of leaf nodes is $\\{3, 4, 5\\}$.\n\n![polygon1.png](https://img.loj.ac.cn/2019/07/01/5d19932673391.png)\n\nNext, Jiulian constructs a sequence $A$ using this tree:\n- Starting from the root node, perform a depth-first traversal of the entire tree in such a way that children nodes are accessed in ascending order of their labels. This yields the DFS sequence for tree $T$.\n- Then, arrange all the leaf nodes according to their appearance order in the DFS sequence, yielding sequence $A$.\n\nFurthermore, based on sequence $A$, Jiulian defines the distance $d(u, v)$ between two leaf nodes $u$ and $v$: Suppose $u$ is the $i$-th element and $v$ is the $j$-th element in $A$, then $d(u, v) = \\min(|i \u2212 j|, |A| \u2212 |i \u2212 j|)$, where $|A|$ is the length of sequence $A$, i.e., the number of leaf nodes in tree $T$, and $i, j$ represent appearance positions starting from $1$.\n\nIn the example above, sequence $A$ is $\\{4, 5, 3\\}$. Distances between leaf nodes are $d(3, 5) = d(3, 4) = d(4, 5) = 1$, where the positions of $3, 4, 5$ are $3, 1, 2$, respectively.\n\nFinally, Jiulian provides a parameter $K$. Using tree $T$ and sequence $A$, we can construct an **undirected graph $G$ without duplicate edges and self-loops**, consisting of $n$ nodes. For any two different nodes $u, v$, an edge exists between them if at least one of the following conditions is satisfied:\n- There is an edge connecting $u$ and $v$ in tree $T$.\n- Both $u, v$ are leaf nodes and $d(u, v) \\leq K$.\n\nFor $K = 1$ or $2$, the graph $G$ constructed from the example above looks as follows:\n\n![polygon2.png](https://img.loj.ac.cn/2019/07/01/5d19933b911fe.png)\n\nNow, Jiulian wants you to calculate how many different Hamiltonian cycles exist in $G$. The answer may be very large, so please output the result modulo $998244353$.\n\nAdditional definitions:\n- A Hamiltonian cycle $H$ in an undirected graph $G$ without duplicate edges and self-loops is a subset of its edges such that:\n - Every node has exactly two distinct adjacent edges in $H$.\n - Any two nodes can be directly or indirectly connected by edges in $H$.\n- Two Hamiltonian cycles $H_1, H_2$ in an undirected graph $G$ are considered different if there exists an edge $e$ such that $e$ is in $H_1$ but not in $H_2$.\n\n---\n\n### Input Format\nRead from the file `polygon.in`.\n\nThe first line contains two integers $n$ and $K$, representing the number of nodes in the tree $T$ and the parameter $K$ provided by Jiulian.\n\nThe second line contains $n \u2212 1$ integers $f_i\\ (1 \\leq f_i \\leq i)$, where $f_i$ denotes an edge $(f_i, i + 1)$ in tree $T$.\n\n---\n\n### Output Format\nWrite to the file `polygon.out`.\n\nOutput a single integer, representing the number of Hamiltonian cycles modulo $998244353$.\n\n---\n\n### Example\nThis example corresponds exactly to the example from the problem statement. The two Hamiltonian cycles traverse the nodes in the following orders: $(1, 2, 4, 5, 3)$ and $(1, 2, 5, 4, 3)$.\n\n---\n\n### Constraints and Hints\nThe scale and characteristics of the test cases are listed below:\n\n| ID | $n$ | $K$ | Special Properties | ID | $n$ | $K$ | Special Properties |\n| :--: | :---------: | :-----: | :----------------: | :--: | :---------: | :-----: | :----------------: |\n| $1$ | $\\leq 5$ | $\\leq 3$| None | $11$ | $\\leq 1000$ | $\\leq 2$| A |\n| $2$ | $\\leq 10$ | $\\leq 3$| None | $12$ | $\\leq 1000$ | $\\leq 2$| A |\n| $3$ | $\\leq 15$ | $\\leq 3$| None | $13$ | $\\leq 1000$ | $\\leq 2$| A |\n| $4$ | $\\leq 20$ | $\\leq 3$| None | $14$ | $\\leq 1000$ | $\\leq 2$| None |\n| $5$ | $\\leq 1000$ | $=1$ | A | $15$ | $\\leq 1000$ | $\\leq 2$| None |\n| $6$ | $\\leq 1000$ | $=1$ | A | $16$ | $\\leq 1000$ | $\\leq 2$| None |\n| $7$ | $\\leq 1000$ | $=1$ | A | $17$ | $\\leq 1000$ | $\\leq 3$| A |\n| $8$ | $\\leq 1000$ | $=1$ | None | $18$ | $\\leq 1000$ | $\\leq 3$| A |\n| $9$ | $\\leq 1000$ | $=1$ | None | $19$ | $\\leq 1000$ | $\\leq 3$| None |\n| $10$ | $\\leq 1000$ | $=1$ | None | $20$ | $\\leq 1000$ | $\\leq 3$| None |\n\nProperty A guarantees that every node in the tree has at most two children.\n\nFor all test cases, it is guaranteed that $1 \\leq f_i \\leq i, 2 \\leq n \\leq 1000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2672, "prompt": "### Problem Description\n\nLittle Q, who is about to enter the second grade, bought a new type of educational toy \u2014 a Magic Chessboard. It is an $N \\times M$ grid chessboard, where each cell contains a positive integer. The chessboard guardian resides in the cell located at the $X$th row and $Y$th column (both rows and columns are 1-based indexed) and will never move. The chessboard guardian can perform two types of operations:\n\n- (a) **Query**: The guardian randomly extends outwards from their current position to form a rectangular area of arbitrary size and asks you for the greatest common divisor (GCD) of all numbers within this rectangular region.\n- (b) **Modify**: The guardian chooses any rectangular region on the chessboard and increments all the numbers within this region by a given integer.\n\nThe instruction manual for the game includes the statement: \"Smart kids, if you answer 19,930,324 consecutive queries correctly, you'll receive a surprise!\" Little Q is eager to get that surprise but often makes mistakes due to carelessness, making it difficult to achieve this goal. Thus, Little Q is asking for your help to write a program that can answer the guardian's queries with $100\\%$ accuracy.\n\nTo simplify the problem, your program only needs to handle $T$ operations from the chessboard guardian. It is guaranteed that at any time, all numbers on the chessboard will be positive integers not exceeding $2^{62} - 1$.\n\n---\n\n### Input Format\n\nThe input consists of the following information:\n\n1. The first line contains two positive integers $N$ and $M$, representing the dimensions of the chessboard.\n2. The second line contains two positive integers $X$ and $Y$, indicating the chessboard guardian's position.\n3. The third line contains a single positive integer $T$, representing the number of operations performed by the chessboard guardian.\n4. The next $N$ lines each contain $M$ positive integers, representing the initial numbers on the chessboard.\n5. The next $T$ lines describe the $T$ operations in chronological order. Each line starts with a number $0$ or $1$:\n - If the line begins with $0$, it represents a **query** operation. Four non-negative integers $x_1, y_1, x_2, y_2$ follow, describing the queried rectangular region. The region is defined relative to the guardian's position as follows:\n - Extend upwards by $x_1$ rows.\n - Extend downwards by $x_2$ rows.\n - Extend leftwards by $y_1$ columns.\n - Extend rightwards by $y_2$ columns.\n - If the line begins with $1$, it represents a **modify** operation. Four positive integers $x_1, y_1, x_2, y_2$ and an integer $c$ follow, where:\n - $x_1$ and $x_2$ are the upper and lower row boundaries of the rectangular region.\n - $y_1$ and $y_2$ are the left and right column boundaries of the rectangular region.\n - Add $c$ to all numbers within this rectangular region. Note that $c$ can be negative.\n\n---\n\n### Output Format\n\nFor each **query** operation, output a single number on a separate line, which represents the GCD of all numbers within the queried region.\n\n---\n\n### Example\n\n| Initial State | After First Operation | After Second Operation | After Third Operation | After Fourth Operation |\n|:---------------------:|:---------------------:|:-----------------------:|:---------------------:|:-----------------------:|\n| 6 12
18 24 | **6** 12
**18** 24 | **12** **18**
18 24 | 12 18
**24** **30** | **12** **18**
**24** **30** |\n\nFor the first and fourth operations (query operations), the bolded region indicates the queried area.\n\nFor the second and third operations (modify operations), the bolded region indicates the modified area.\n\n---\n\n### Constraints and Hints\n\n1. The test data is categorized into three groups: A, B, and C:\n - Group A comprises $20\\%$ of the data and satisfies $N \\leq 100$, $M \\leq 100$, $T \\leq 20,000$.\n - Group B comprises $40\\%$ of the data and satisfies $N = 1$, $M \\leq 500,000$, $T \\leq 100,000$.\n - Group C comprises $40\\%$ of the data and satisfies $N \\times M \\leq 500,000$, $T \\leq 100,000$.\n2. For each group, $50\\%$ of the test cases involve modification operations that affect only a single cell (i.e., $x_1 = x_2$ and $y_1 = y_2$).\n3. The input data is guaranteed to satisfy all the conditions described in the problem statement.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2720, "prompt": "### Problem Description\n\nThe highly skilled individual, A, has been appointed as the problem setter for ION2018 and now faces the challenge of naming the problems.\n\nA has been chosen as the problem setter for ION2018 and has carefully crafted a top-quality problem. However, all aspects of the problem have been finalized except for its name.\n\nBecause ION has been held for many years, the naming of the problems follows specific rules. According to the ION problem-setting manual, every year the problem-setting committee specifies a lowercase alphabetical string, referred to as that year's \"naming string.\" **The name of each problem must be a non-empty contiguous substring of that year's naming string and must not coincide with any of the names of the problems from the previous year.**\n\nDue to certain special circumstances, A does not know any of the names of the ION2017 problems. However, through some special means, A has obtained the naming string of ION2017. A now has $Q$ queries, where each query specifies the naming string for ION2017 and ION2018. Your task is to determine how many valid problem names can be created, such that these names satisfy the rules set by the problem-setting committee: being a non-empty contiguous substring of the ION2018 naming string and not coinciding with any problem name from ION2017.\n\nDue to specific constraints, all given ION2017 naming strings in the queries must be contiguous substrings of a string $S$, as detailed in the input format below.\n\n---\n\n### Input Format\n\nRead input from the file `name.in`.\n\n- The first line contains a string $S$. All ION2017 naming strings provided in the queries are contiguous substrings of $S$.\n- The second line contains an integer $Q$, representing the number of queries.\n- The next $Q$ lines each contain a string $T$ and two integers $l, r$. This indicates a query asking for the number of valid problem names if the ION2017 naming string is $S[l..r]$ and the ION2018 naming string is $T$.\n\nThe strings in the input consist only of lowercase alphabetical characters.\n\n---\n\n### Output Format\n\nPrint the output to the file `name.out`.\n\nOutput $Q$ lines. The $i^{th}$ line contains a non-negative integer representing the answer to the $i^{th}$ query.\n\n---\n\n### Sample\n\nSee the provided files `name2.in` and `name2.ans` for examples.\n\n---\n\n### Constraints and Hints\n\n\n\n| Test Case | $\\lvert S \\rvert \\leq$ | $Q \\leq$ | $\\sum \\lvert T \\rvert \\leq$ | Query Constraint | Other Constraints |\n|:-:|:-:|:-:|:-:|:-:|:-:|\n| 1 | $200$ | $200$ | $40000$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | $\\lvert T \\rvert \\leq 200$ |\n| 2 | $1000$ | $200$ | $40000$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | $\\lvert T \\rvert \\leq 200$ |\n| 3 | $1000$ | $200$ | $40000$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | $\\lvert T \\rvert \\leq 200$ |\n| 4 | $1000$ | $200$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 5 | $1000$ | $200$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 6 | $5 \\times 10^5$ | $1$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 7 | $5 \\times 10^5$ | $1$ | $5 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 8 | $10^5$ | $10^5$ | $2 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 9 | $10^5$ | $10^5$ | $2 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 10 | $2 \\times 10^5$ | $10^5$ | $4 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 11 | $2 \\times 10^5$ | $10^5$ | $4 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 12 | $3 \\times 10^5$ | $10^5$ | $6 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 13 | $3 \\times 10^5$ | $10^5$ | $6 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 14 | $4 \\times 10^5$ | $10^5$ | $8 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 15 | $4 \\times 10^5$ | $10^5$ | $8 \\times 10^5$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 16 | $5 \\times 10^5$ | $10^5$ | $10^6$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | None |\n| 17 | $5 \\times 10^5$ | $10^5$ | $10^6$ | For all queries, $l = 1, r = \\lvert S \\rvert$ | Random string |\n| 18 | $2 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 19 | $3 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 20 | $4 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 21 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 22 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 23 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 24 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n| 25 | $5 \\times 10^5$ | $10^5$ | $10^6$ | None | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2130, "prompt": "### Problem Description\n\nLinux and OSX users are likely familiar with package managers. With a package manager, you can install a software package using a single command. The package manager will then help you download the package from a repository, automatically resolve all dependencies (i.e., download and install any other packages required for the installation of the desired package), and complete the configuration. Popular package managers include `apt-get` for Debian/Ubuntu, `yum` for Fedora/CentOS, and `Homebrew` for OSX.\n\nYou decide to design your own package manager. Inevitably, you will need to deal with package dependencies. If package $A$ depends on package $B$, installing package $A$ requires package $B$ to be installed first. Similarly, uninstalling package $B$ requires package $A$ to be uninstalled as well. Now, you have been given all dependency relationships between packages. Furthermore, due to your prior work, every package in your package manager (except for package $0$) depends on exactly one other package, and package $0$ does not depend on any package. The dependency relationships do not contain any cycles (i.e., if there are $m \\ (m \\geq 2)$ packages $A_1, A_2, A_3, \\ldots, A_m$ such that $A_1$ depends on $A_2$, $A_2$ depends on $A_3$, $A_3$ depends on $A_4$, ..., $A_{m\u22121}$ depends on $A_m$, and $A_m$ depends on $A_1$, this forms a dependency cycle). Additionally, no package depends on itself.\n\nNow, you need to write a dependency resolution program for your package manager. Based on user feedback, users want to quickly know how many packages' installation statuses will change when installing or uninstalling a given package (i.e., for an install operation, how many packages will go from uninstalled to installed; and for an uninstall operation, how many packages will go from installed to uninstalled). Your task is to implement this feature. Note that if a user attempts to install an already installed package or uninstall an already uninstalled package, no package's installation status will change, i.e., the number of packages whose installation status changes in this case is $0$.\n\n### Input Format\n\nThe first line of the input contains a single positive integer $n$, representing the total number of packages. Packages are numbered from $0$. \nThe second line contains $n\u22121$ integers separated by single spaces, where the $i^{th}$ integer represents the package on which package $i+1$ depends (for $i \\in \\{1, 2, ..., n-1\\}$). \nThe third line contains a single positive integer $q$, representing the total number of queries. \nThe following $q$ lines each contain a single query, which can be one of two types: \n``install x``: Indicates installing package $x$. \n``uninstall x``: Indicates uninstalling package $x$. \n\nYou need to maintain the installation status of each package. All packages are initially uninstalled. For each query, you must output the number of packages whose installation status changes as a result of the operation, and then apply the operation (i.e., update the maintained installation status accordingly).\n\n### Output Format\n\nThe output consists of $q$ lines. \nThe $i^{th}$ line contains a single integer, representing the number of packages whose installation status changes as a result of the $i^{th}$ query.\n\n### Example\n\nInitially, all packages are uninstalled.\n\n- Installing package $5$ requires installing packages $0, 1, 5$, for a total of $3$ packages. \n- Installing package $6$ afterward only requires installing package $6$. At this point, packages $0, 1, 5, 6$ are installed. \n- Uninstalling package $1$ requires uninstalling packages $1, 5, 6$, for a total of $3$ packages. Now, only package $0$ remains installed. \n- Installing package $4$ requires installing packages $1, 4$, for a total of $2$. At this point, packages $0, 1, 4$ are installed. \n- Finally, uninstalling package $0$ uninstalls all packages.\n\n#### Input\n```\n7\n0 0 1 1 0 1\n5\ninstall 5\ninstall 6\nuninstall 1\ninstall 4\nuninstall 0\n```#### Output\n```\n3\n1\n3\n2\n3\n```\n\n### Constraints and Notes\n\nFor all inputs, $n \\leq 100000, \\ q \\leq 100000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2601, "prompt": "### Problem Description\nThe picturesque small town of Y City has $n$ beautiful scenic spots. As tourists flock to the area in ever-increasing numbers, Y City has arranged a sightseeing bus to provide more convenient transportation services for visitors.\n\nThe sightseeing bus appears at scenic spot $1$ at minute $0$, and subsequently visits scenic spots $2, 3, \\dots, n$ in sequence. It takes $D_i$ minutes to travel from scenic spot $i$ to scenic spot $i+1$. At any given time, the bus can only move forward or wait at the current spot.\n\nThere are $m$ tourists, each of whom needs to travel exactly once from one scenic spot to another. The $i^{th}$ tourist arrives at scenic spot $A_i$ at minute $T_i$ and wants to travel to scenic spot $B_i$ $(A_i < B_i)$. To ensure all passengers reach their destination, the bus must wait at each stop until all passengers departing from that spot have boarded before heading to the next spot. Assume that boarding and alighting take no time.\n\nA passenger's travel time is defined as the time they reach their destination minus the time they arrived at the departure spot. Since there is only one sightseeing bus, it may need to stop and wait for other passengers, causing complaints about long travel times. To address this issue, the driver ZZ has installed $k$ nitrous accelerators on the bus. Each accelerator can reduce one specific $D_i$ by $1$ minute. The same accelerator can be applied multiple times to the same $D_i$, but the condition $D_i \\geq 0$ must be satisfied after usage.\n\nZZ needs to decide how to use these accelerators to minimize the total travel time of all passengers.\n\n### Input Format\nThe first line contains three integers $n$, $m$, and $k$, separated by spaces. These integers represent the number of scenic spots, the number of passengers, and the number of nitrous accelerators, respectively.\n\nThe second line contains $n-1$ integers separated by spaces, where the $i^{th}$ integer represents the time required to travel from scenic spot $i$ to scenic spot $i+1$, denoted by $D_i$.\n\nThe next $m$ lines (from the 3rd line to the $(m+2)^{th}$ line) each contain three integers $T_i$, $A_i$, and $B_i$, separated by spaces. The $(i+2)^{th}$ line represents the $i^{th}$ passenger's arrival time at the departure scenic spot, the departure scenic spot number, and the destination scenic spot number.\n\n### Output Format\nPrint a single integer representing the minimum possible total travel time.\n\n### Example\nUsing two accelerators on $D_2$, the travel time from scenic spot $2$ to scenic spot $3$ becomes $2$ minutes.\n\nThe bus departs scenic spot $1$ at minute $1$, arrives at scenic spot $2$ at minute $2$, departs scenic spot $2$ at minute $5$, and arrives at scenic spot $3$ at minute $7$.\n\n- The travel time for passenger $1$ is $7 - 0 = 7$ minutes.\n- The travel time for passenger $2$ is $2 - 1 = 1$ minute.\n- The travel time for passenger $3$ is $7 - 5 = 2$ minutes.\n\nTotal travel time: $7 + 1 + 2 = 10$ minutes.\n\n### Constraints & Hints\n- For $8\\%$ of the data, $k=0$.\n- For $16\\%$ of the data, $k=1$.\n- For $32\\%$ of the data, $2 \\leq n \\leq 50$, $m \\leq 1000$, $k \\leq 20$, $D_i \\leq 10$, $T_i \\leq 500$.\n- For $48\\%$ of the data, $n \\leq 100$, $m \\leq 1000$, $k \\leq 100$, $T_i \\leq 10^4$.\n- For $80\\%$ of the data, $n \\leq 1000$, $m \\leq 10^4$, $k \\leq 10^5$, $D_i \\leq 100$, $T_i \\leq 10^5$.\n- **For $100\\%$ of the data,** $1 \\leq n, m \\leq 10^5$, $0 \\leq k \\leq 5 \\times 10^6$, $0 \\leq D_i \\leq 1000$, $0 \\leq T_i \\leq 10^6$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3386, "prompt": "### Problem Description\nFor a city, the drainage system is an extremely important component.\n\nOne day, Little C obtained the design blueprint of a city's drainage system. The drainage system consists of $n$ drainage nodes (numbered from $1 \\sim n$) and several one-way drainage pipes. Each drainage node has several pipes to collect wastewater from other drainage nodes (referred to as the node's collection pipes) and several other pipes to discharge wastewater to other drainage nodes (known as the node's discharge pipes).\n\nAmong the drainage nodes, $m$ nodes are designated as wastewater inlets, numbered as $1, 2, \\ldots, m$, and wastewater can only flow into the drainage system through these inlets. These nodes do not have collection pipes. Additionally, the drainage system has several final outlets that transport wastewater to treatment plants; these nodes are considered final outlets if they have no discharge pipes.\n\nCurrently, each wastewater inlet receives $1$ tonne of wastewater. When wastewater flows into a node, it is evenly distributed among all the discharge pipes of the node and flows to other drainage nodes, while final outlets discharge wastewater out of the system.\n\nLittle C wants to determine how much wastewater each final outlet discharges in the city's drainage system. The city's drainage system is scientifically designed, and the pipes do not form loops\u2014i.e., wastewater will not form circular flows.\n\n### Input Format\nThe first line contains two integers $n$ and $m$ separated by a single space, representing the number of drainage nodes and the number of wastewater inlets, respectively. \nThe following $n$ lines describe the discharge pipes for each node. The $i$-th line starts with an integer $d_i$, representing the number of discharge pipes for node $i$. The next $d_i$ integers $a_1, a_2, \\ldots, a_{d_i}$ indicate the destination drainage nodes of these pipes, separated by single spaces. \nIt is guaranteed that no two pipes will have the same starting and destination nodes.\n\n### Output Format\nOutput several lines, in ascending order of node numbers, showing the volume of wastewater discharged by each final outlet. The volume must be expressed in fractional form. Each line should output two integers $p$ and $q$ separated by a single space, indicating that the discharged volume is $\\frac{p}{q}$. It is required that $p$ and $q$ are coprime, and $q = 1$ should also be included in the output.\n\n**Explanation for Sample #1**\n\nNode $1$ is a wastewater inlet, and nodes $4$ and $5$ are final outlets because they have no discharge pipes. \nWhen $1$ tonne of wastewater flows into node $1$, it is evenly distributed to nodes $2, 3, 5$ via discharge pipes, each receiving $\\frac{1}{3}$ tonne of wastewater. \nWhen node $2$ receives $\\frac{1}{3}$ tonne of wastewater, it is evenly distributed to nodes $4$ and $5$, each receiving $\\frac{1}{6}$ tonne of wastewater. \nWhen node $3$ receives $\\frac{1}{3}$ tonne of wastewater, it is evenly distributed to nodes $4$ and $5$, each receiving $\\frac{1}{6}$ tonne of wastewater. \nFinally, node $4$ discharges $\\frac{1}{6} + \\frac{1}{6} = \\frac{1}{3}$ tonne of wastewater, and node $5$ discharges $\\frac{1}{3} + \\frac{1}{6} + \\frac{1}{6} = \\frac{2}{3}$ tonne of wastewater.\n\n**Sample Input**\n\n```\n5 1\n3 2 3 5\n2 4 5\n2 4 5\n0\n0\n```**Sample Output**\n\n```\n1 3\n2 3\n```\n\n### Data Constraints\n\n| Test Case Number | $n \\le$ | $m \\le$ |\n|:-:|:-:|:-:|\n| $1 \\sim 3$ | $10$ | $1$ |\n| $4 \\sim 6$ | ${10}^3$ | $1$ |\n| $7 \\sim 8$ | ${10}^5$ | $1$ |\n| $9 \\sim 10$ | ${10}^5$ | $10$ |\n\nFor all test cases, it is guaranteed that $1 \\le n \\le {10}^5$, $1 \\le m \\le 10$, $0 \\le d_i \\le 5$. \n\nThe data also guarantees that when wastewater flows from a wastewater inlet to a final outlet, it will pass through no more than $10$ intermediate drainage nodes (not counting the inlet and the final outlet). \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2297, "prompt": "### Problem Description\n\nThe island of Crete is known for its tribe of wild men. There are $m$ caves on the island, arranged in a circular formation. These caves are numbered clockwise as $1, 2, \\dots, m$. There are $n$ wild men living on the island, and initially, they reside in caves $C_1, C_2, \\dots, C_n$, respectively. Each year, the $i$-th wild man moves forward $P_i$ caves clockwise and settles in that cave.\n\nEach wild man $i$ has a lifespan $L_i$, which represents the number of years they will survive.\n\nThe following four diagrams illustrate the first four years on an island with $6$ caves and $3$ wild men. The initial cave numbers for the wild men are $1, 2, 3$, respectively. The number of caves they move forward each year is $3, 7, 2$, respectively, and their lifespans are $4, 3, 1$.\n\n![](https://img.loj.ac.cn/2022/06/09/2cf510b3762ac.png)\n\nInterestingly, despite having many wild men, no two wild men ever reside in the same cave during their lifetimes. This keeps the island perpetually peaceful, which amazes scientists. They want to determine the minimum number of caves required to maintain peace on the island.\n\n---\n\n### Input Format\n\nThe first line contains an integer $n$, the number of wild men.\n\nThe next $n$ lines each contain three integers, $C_i, P_i, L_i$, indicating the initial cave number, the number of caves the wild man moves forward each year, and their lifespan, respectively.\n\n---\n\n### Output Format\n\nOutput a single integer $M$, the minimum number of caves required. The input guarantees a solution exists, and $M$ will not exceed $10^6$.\n\n---\n\n### Example\n\n**Input:**\n```\n3\n1 3 4\n2 7 3\n3 2 1\n```**Output:**\n```\n6\n```\n\n---\n\n### Constraints and Hints\n\n- For $100\\%$ of the test cases:\n - $1 \\leq n \\leq 15$.\n - $1 \\leq C_i, P_i \\leq 100$.\n - $0 \\leq L_i \\leq 10^6$.\n - The solution satisfies $M \\leq 10^6$.\n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3342, "prompt": "### Problem Description\nThe chef plans to prepare $m$ dishes for children, with each dish requiring $k$ grams of ingredients. To achieve this, the chef has purchased $n$ types of ingredients, numbered from $1$ to $n$. The weight of the $i$-th ingredient is $d_i$ grams. The **total weight of the $n$ ingredients is exactly $m \\times k$ grams**, and both $d_i$ and $k$ are **positive integers**.\n\nWhen preparing dishes, each ingredient can be used in multiple dishes. However, to preserve the purity of the flavor, the chef wants each dish to use **at most 2 types of ingredients**. Your task is to determine whether there exists a preparation plan that satisfies the following conditions:\n- Exactly $m$ dishes are prepared.\n- Each dish uses at most $2$ types of ingredients.\n- Each dish uses exactly $k$ grams of ingredients.\n- The weight of each ingredient used in a dish is a positive integer.\n- All $n$ types of ingredients are used up exactly.\n\nIf such a preparation plan exists, you should also provide one valid preparation plan.\n\n### Input Format\n**This problem contains multiple test cases in a single input file.**\n\nThe first line contains an integer $T$, the number of test cases. For each test case:\n- The first line contains three positive integers $n$, $m$, and $k$, representing the number of ingredient types, the number of dishes to prepare, and the weight of ingredients required for each dish, respectively.\n- The second line contains $n$ integers, where the $i$-th integer represents the weight $d_i$ of the $i$-th ingredient.\n\n### Output Format\nFor each test case:\n- **If no valid preparation plan exists, output a single line containing the integer $-1$.**\n- Otherwise, output $m$ lines, each describing how one dish is prepared. Depending on the number of ingredient types used in the dish, the format should be one of the following:\n - Output a single line with two integers $i$ and $x$, meaning the dish is prepared using $x$ grams of the $i$-th ingredient. You must ensure $1 \\leq i \\leq n$, and $x = k$.\n - Output a single line with four integers $i$, $x$, $j$, and $y$, meaning the dish is prepared using $x$ grams of the $i$-th ingredient and $y$ grams of the $j$-th ingredient. You must ensure $1 \\leq i, j \\leq n$, $i \\neq j$, $x + y = k$, and $x, y > 0$.\n\nThis problem uses a **custom checker** to validate your solution. Therefore, if there are multiple valid solutions, you only need to output **any one** of them.\n\nEnsure that the output format is correct and that numbers in the same line are separated by a single space. Apart from this, your output should **not contain any extra characters**.\n\n#### Sample Explanation 1\n\nFor the second test case, one valid preparation plan is as follows:\n- Use $80$ grams of ingredient $1$ and $20$ grams of ingredient $2$ to make the first dish.\n- Use $10$ grams of ingredient $2$ and $90$ grams of ingredient $3$ to make the second dish.\n- Use $100$ grams of ingredient $4$ to make the third dish.\n\n#### Sample 2\n\nRefer to the files `dish/dish2.in` and `dish/dish2.ans` in the participant's directory.\n\n#### Sample 3\n\nRefer to the files `dish/dish3.in` and `dish/dish3.ans` in the participant's directory.\n\n---\n\n### Constraints\nFor all test cases:\n$1 \\leq T \\leq 10$, $1 \\leq n \\leq 500$, $n - 2 \\leq m \\leq 5000$, $m \\geq 1$, $1 \\leq k \\leq 5000$, $\\sum_{i=1}^{n}d_i = m \\times k$.\n\nThe specific constraints for each test case are given in the table below:\n\n| Test Case Index | $n$ | $m$ | $k$ |\n| :-: | :-: | :-: | :-: |\n| $1\\sim 3$ | $\\le 4$ | $\\le 4$ | $\\le 50$ |\n| $4\\sim 5$ | $\\le 10$ | $\\le 10$ | $\\le 5\\times 10^3$ |\n| $6\\sim 7$ | $\\le 500$ | $=n-1$ | $\\le 5\\times 10^3$ |\n| $8\\sim 9$ | $\\le 500$ | $n-1\\le m\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n| $10$ | $\\le 25$ | $\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n| $11\\sim 12$ | $\\le 25$ | $\\le 5\\times 10^3$ | $\\le 500$ |\n| $13\\sim 14$ | $\\le 50$ | $\\le 5\\times 10^3$ | $\\le 500$ |\n| $15\\sim 17$ | $\\le 100$ | $\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n| $18\\sim 20$ | $\\le 500$ | $\\le 5\\times 10^3$ | $\\le 5\\times 10^3$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2132, "prompt": "### Problem Description\n\n> \"The one who chases shadows becomes the shadow.\" \u2014 Homer\n\nAllison has recently developed an interest in literature. She enjoys sipping a cup of cappuccino on a lazy afternoon while indulging in her cherished copy of the *Homeric Epics*. A monumental work composed of *The Odyssey* and *The Iliad*, the Homeric Epics are too lengthy for her liking. Thus, Allison seeks to shorten it by employing an encoding technique. \n\nThe Homeric Epics contain $n$ distinct words, numbered from $1$ to $n$. The $i$th word appears $w_i$ times in total. Allison wants to replace the $i$th word with a $k$-ary string $s_i$ such that the following condition is satisfied: \nFor any $1 \\leq i, j \\leq n$, where $i \\neq j$, $s_i$ is not a prefix of $s_j$. \n\nNow Allison wishes to determine how to choose the $s_i$ values in order to minimize the total length of the encoded Homeric Epics. Furthermore, under the condition of minimizing the total length, she also wants to know the shortest possible length of the longest string $s_i$. \n\nSome definitions: \n\n- A string is called a **$k$-ary string** if and only if each character in the string is an integer between $0$ and $k-1$ (inclusive). \n- A string $\\text{Str}_1$ is called the **prefix** of a string $\\text{Str}_2$ if and only if there exists $1 \\leq t \\leq m$ such that $\\text{Str}_1 = \\text{Str}_2[1 \\ldots t]$, where $m$ is the length of $\\text{Str}_2$, and $\\text{Str}_2[1 \\ldots t]$ represents the substring composed of the first $t$ characters of $\\text{Str}_2$. \n\n---\n\n### Input Format\nThe input file consists of multiple lines: \n\n- The first line contains two positive integers, $n$ and $k$, separated by a single space, indicating that there are $n$ distinct words to be replaced using $k$-ary strings. \n- The next $n$ lines each contain a single non-negative integer $w_i$, representing the frequency of occurrence of the $i$th word. \n\n---\n\n### Output Format\nThe output file consists of two lines: \n\n- The first line outputs an integer, representing the minimum length of the encoded Homeric Epics after the replacement. \n- The second line outputs an integer, representing the shortest possible length of the longest $s_i$ string under the condition of achieving the minimum total length. \n\n---\n\n### Example 1\nLet $X_{(k)}$ denote that $X$ is a string in $k$-ary notation. \n\nOne optimal solution is: \n- Replace the first word with $00_{(2)}$, \n- Replace the second word with $01_{(2)}$, \n- Replace the third word with $10_{(2)}$, \n- Replace the fourth word with $11_{(2)}$. \n\nIn this solution, the encoded length is: \n$1 \\times 2 + 1 \\times 2 + 2 \\times 2 + 2 \\times 2 = 12$, \nand the length of the longest $s_i$ is $2$. \n\nA non-optimal solution is: \n- Replace the first word with $000_{(2)}$, \n- Replace the second word with $001_{(2)}$, \n- Replace the third word with $01_{(2)}$, \n- Replace the fourth word with $1_{(2)}$. \n\nIn this case, the encoded length is: \n$1 \\times 3 + 1 \\times 3 + 2 \\times 2 + 2 \\times 1 = 12$, \nbut the length of the longest $s_i$ is $3$. Compared to the optimal solution, the total length is the same, but the length of the longest string is higher. \n\n---\n\n### Example 2\nAn optimal solution is: \n- Replace the first word with $000_{(3)}$, \n- Replace the second word with $001_{(3)}$, \n- Replace the third word with $01_{(3)}$, \n- Replace the fourth word with $02_{(3)}$, \n- Replace the fifth word with $1_{(3)}$, \n- Replace the sixth word with $2_{(3)}$. \n\n---\n\n### Constraints and Hints\n\n#### Limits and Constraints\n\n| Case # | Scale of $n$ | Scale of $k$ | Additional Constraints |\n|:-:|:-:|:-:|:-:|\n| 1 | $n = 3$ | $k = 2$ | - |\n| 2 | $n = 5$ | $k = 2$ | - |\n| 3 | $n = 16$ | $k = 2$ | All $w_i$ are equal |\n| 4 | $n = 1000$ | $k = 2$ | $w_i$ are uniformly random |\n| 5 | $n = 1000$ | $k = 2$ | - |\n| 6 | $n = 100000$ | $k = 2$ | - |\n| 7 | $n = 100000$ | $k = 2$ | All $w_i$ are equal |\n| 8 | $n = 100000$ | $k = 2$ | - |\n| 9 | $n = 7$ | $k = 3$ | - |\n| 10 | $n = 16$ | $k = 3$ | All $w_i$ are equal |\n| 11 | $n = 1001$ | $k = 3$ | All $w_i$ are equal |\n| 12 | $n = 99999$ | $k = 4$ | All $w_i$ are equal |\n| 13 | $n = 100000$ | $k = 4$ | - |\n| 14 | $n = 100000$ | $k = 4$ | - |\n| 15 | $n = 1000$ | $k = 5$ | - |\n| 16 | $n = 100000$ | $k = 7$ | $w_i$ are uniformly random |\n| 17 | $n = 100000$ | $k = 7$ | - |\n| 18 | $n = 100000$ | $k = 8$ | $w_i$ are uniformly random |\n| 19 | $n = 100000$ | $k = 9$ | - |\n| 20 | $n = 100000$ | $k = 9$ | - |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2668, "prompt": "### Problem Description\nStudent Xiao E is very fond of calligraphy. Upon hearing that NOI2013 has started, he wants to create a calligraphy piece that spells \"NOI\" and present it to everyone.\n\nXiao E has a magical sheet of paper that can be represented by an $n$-row by $m$-column 2D grid matrix. For convenience, we define the coordinate of the bottom-left grid cell in the matrix as $(1,1)$ and the coordinate of the top-right grid cell as $(m, n)$.\n\nEach grid cell in the matrix has an integer value called \"luck value\". Writing on the grid cells increases everyone's luck. The degree of luck enhancement is precisely the sum of the luck values of all the cells covered by writing. Now, you need to write the letters `N`, `O`, `I` on the paper.\n\nHere are the definitions of the three calligraphy letters:\n\n* `N` consists of multiple (at least 3) rectangles whose sides are parallel to the coordinate axes. Suppose it is composed of $K$ rectangles (indexed as $1 \\ldots K$); the bottom-left coordinate of the $i^{th}$ rectangle is $(L_i, B_i)$, and the top-right coordinate is $(R_i, T_i)$. The rectangles must satisfy:\n1. $L_i \\leq R_i$, $B_i \\leq T_i$;\n2. For any $1 < i \\leq K$, $L_i = R_{i\u22121} + 1$;\n3. For any $3 \\le i < K$, $B_{i\u22121} \u2212 1 \\le T_i \\le T_{i\u22121}$, $B_i \\le B_{i\u22121}$;\n4. $B_2 > B_1$, $T_2 = T_1$, $B_{K\u22121} = B_K$, $T_{K\u22121} < T_K$;\n\n* `O` is created by cutting out a smaller rectangle $B$ from a larger rectangle $A`. Both rectangles have sides parallel to the coordinate axes. Assume that the bottom-left coordinate of the larger rectangle $A$ is $(u, v)$, with a length of $W$ and a width of $H$. Rectangle $B` satisfies the following conditions: the bottom-left coordinate is $(u+1, v+1)$, with a length of $W \u2212 2` and a width of $H \u2212 2`. The conditions to satisfy are:\n1. $W \\geq 3$, $H \\geq 3$;\n2. $u > R_K + 1`;\n\n* `I` consists of three solid rectangles whose sides are parallel to the coordinate axes, stacked from bottom to top and numbered $1, 2, 3` (from bottom to top). The bottom-left coordinate of the $i^{th}$ rectangle is $(P_i, Q_i)`, and its top-right coordinate is $(G_i, H_i)`. The conditions to satisfy are:\n1. $P_i \\leq G_i$, $Q_i \\leq H_i`;\n2. $P_1 = P_3 > u + W`, $G_1 = G_3`;\n3. $Q_1 = H_1 = Q_2 \u2212 1, H_2 + 1 = Q_3 = H_3`;\n4. $P_1 < P_2 \\leq G_2 < G_1`;\n\nBelow is an example of the letters `N`, `O`, and `I`.\n![](https://i.loli.net/2018/06/10/5b1cf2cd05775.png)\n\nAdditionally, all drawn shapes must not exceed the edges of the sheet of paper. Now, Xiao E wants to know the maximum luck he can achieve by drawing these letters.\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, representing the number of rows and columns of the matrix.\n\nThe next $n$ lines each contain $m$ integers. The $(i+1)^{th}$ line's $j^{th}$ number represents the luck value of the grid cell $(j, n \u2212 i + 1)`.\n\n---\n\n### Output Format\nOutput a single integer $T`, representing the maximum luck Xiao E can achieve.\n\n---\n\n### Examples\n#### Sample Input 1\n```plain\n3 13\n1 1 -1 -1 1 -1 1 1 1 -1 1 1 1\n1 -1 1 -1 1 -1 1 -1 1 -1 -1 1 -1\n1 -1 -1 1 1 -1 1 1 1 -1 1 1 1\n```#### Sample Output 1\n```plain\n24\n```\n\n#### Explanation 1\n![](https://i.loli.net/2018/06/10/5b1cf34eecabe.png)\n\n---\n\n#### Sample Input 2\n```plain\n3 13\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n```\n\n#### Sample Output 2\n```plain\n-20\n```\n\n#### Explanation 2\nBelow is an example of an optimal solution; other optimal solutions may exist.\n![](https://i.loli.net/2018/06/10/5b1cf38caea6c.png)\n\n---\n\n#### Sample Input/Output 3\nRefer to the provided files `penman.in` and `penman.ans`.\n\n---\n\n### Constraints and Hints\n| Test Case Number | $n$ | $m$ | Luck Value Range |\n| :--------------: | :------: | :------: | :---------------: |\n| 1 | $=3$ | $=12$ | $[-50,50]$ |\n| 2 | $=3$ | $=12$ | $[-50,50]$ |\n| 3 | $=3$ | $=12$ | $[-50,50]$ |\n| 4 | $=3$ | $=12$ | $[-50,50]$ |\n| 5 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 6 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 7 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 8 | $\\leq10$ | $\\leq20$ | $[-50,50]$ |\n| 9 | $\\leq150$ | $\\leq500$ | $=1$ |\n| 10 | $\\leq150$ | $\\leq500$ | $=1$ |\n| 11 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 12 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 13 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 14 | $\\leq80$ | $\\leq80$ | $[-200,200]` |\n| 15 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 16 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 17 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 18 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 19 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n| 20 | $\\leq150$ | $\\leq500$ | $[-200,200]` |\n\nFor all test cases, it is guaranteed that $n \\geq 3$, $m \\geq 12`.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3387, "prompt": "### Problem Description\n\nC is learning about string matching and is working on a problem.\n\nFor a string $S$, the task is to find the number of possible splitting schemes of $S$ that satisfy the following forms:\n\n$S = ABC$, $S = ABABC$, $S = ABAB \\ldots ABC$, where $A$, $B$, and $C$ are all non-empty strings, and the number of characters that appear an odd number of times in $A$ does not exceed that in $C$.\n\nMore specifically, we can define $AB$ to denote the concatenation of two strings $A$ and $B$. For example, if $A = \\texttt{aab}$ and $B = \\texttt{ab}$, then $AB = \\texttt{aabab}$.\n\nWe can also recursively define $A^1 = A$, $A^n = A^{n - 1} A$ (where $n \\geq 2$ and is a positive integer). For example, if $A = \\texttt{abb}$, then $A^3 = \\texttt{abbabbabb}$.\n\nThus, C\u2019s task is to find the number of splitting schemes for $S = {(AB)}^iC$, where $F(A) \\leq F(C)$. Here, $F(S)$ represents the number of characters in string $S$ that appear an odd number of times. Two schemes are considered different if and only if at least one of the strings $A$, $B$, $C$ differs.\n\nC doesn\u2019t know how to solve this problem, so they\u2019re asking for your help.\n\n### Input Format\n\nThe input consists of multiple test cases. The first line contains a positive integer $T$, representing the number of test cases.\n\nEach test case consists of a single line containing a string $S$, as described in the problem statement. $S$ consists only of lowercase English letters.\n\n### Output Format\n\nFor each test case, output a single integer on a new line, representing the answer.\n\n### **Sample Input #1**\n\n```\n1\nnnrnrr\n```### **Sample Output #1**\n\n```\n8\n```\n\n### **Explanation for Sample #1**\n\nFor the first test case, all possible schemes are:\n\n1. $A = \\texttt{n}$, $B = \\texttt{nr}$, $C = \\texttt{nnr}$.\n2. $A = \\texttt{n}$, $B = \\texttt{nrn}$, $C = \\texttt{nr}$.\n3. $A = \\texttt{n}$, $B = \\texttt{nrnn}$, $C = \\texttt{r}$.\n4. $A = \\texttt{nn}$, $B = \\texttt{r}$, $C = \\texttt{nnr}$.\n5. $A = \\texttt{nn}$, $B = \\texttt{rn}$, $C = \\texttt{nr}$.\n6. $A = \\texttt{nn}$, $B = \\texttt{rnn}$, $C = \\texttt{r}$.\n7. $A = \\texttt{nnr}$, $B = \\texttt{n}$, $C = \\texttt{nr}$.\n8. $A = \\texttt{nnr}$, $B = \\texttt{nn}$, $C = \\texttt{r}$.\n\n### Constraints\n\n| Test Point ID | $\\lvert S \\rvert \\leq$ | Special Properties |\n|:-:|:-:|:-:|\n| $1 \\sim 4$ | $10$ | None |\n| $5 \\sim 8$ | $100$ | None |\n| $9 \\sim 12$ | $1000$ | None |\n| $13 \\sim 14$ | $2^{15}$ | $S$ contains only one type of character |\n| $15 \\sim 17$ | $2^{16}$ | $S$ contains only two types of characters |\n| $18 \\sim 21$ | $2^{17}$ | None |\n| $22 \\sim 25$ | $2^{20}$ | None |\n\nFor all test cases, it is guaranteed that $1 \\leq T \\leq 5$, $1 \\leq \\lvert S \\rvert \\leq 2^{20}$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3565, "prompt": "### Problem Description\n\nGiven integers $n, m, k$, and a positive integer array of length $m + 1$ denoted as $v_0, v_1, \\ldots, v_m$.\n\nFor a non-negative integer sequence $\\{a_i\\}$ of length $n$, where the indices start from $1$ and each element does not exceed $m$, we define its weight as $v_{a_1} \\times v_{a_2} \\times \\cdots \\times v_{a_n}$.\n\nIf such a sequence $\\{a_i\\}$ satisfies the condition that the number of $1$s in the binary representation of the integer $S = 2^{a_1} + 2^{a_2} + \\cdots + 2^{a_n}$ does not exceed $k$, we consider $\\{a_i\\}$ to be a valid sequence.\n\nCompute the sum of the weights of all valid sequences $\\{a_i\\}$, modulo $998244353$.\n\n### Input Format\n\nThe first line contains three integers $n, m, k$.\n\nThe second line contains $m + 1$ integers, $v_0, v_1, \\ldots, v_m$.\n\n### Output Format\n\nOutput a single integer, representing the sum of the weights of all valid sequences modulo $998244353$.\n\n**Example Explanation #1**\n\nSince $k = 1$, and from $n \\leq S \\leq n \\times 2^m$ we know $5 \\leq S \\leq 10$, the only valid $S$ is $S = 8$. This requires the sequence $a$ to contain exactly $2$ zeros and $3$ ones. There are $\\binom{5}{2} = 10$ possible sequences, and each sequence contributes a weight of $v_0^2 v_1^3 = 4$. Thus, the total weight sum is $10 \\times 4 = 40$.\n\n### Constraints\n\nAll test cases guarantee that $1 \\leq k \\leq n \\leq 30$, $0 \\leq m \\leq 100$, and $1 \\leq v_i < 998244353$.\n\n| Test Case | $n$ | $k$ | $m$ |\n| :-------------: | :---: | :------: | :----: |\n| $1 \\sim 4$ | $=8$ | $\\leq n$ | $=9$ |\n| $5 \\sim 7$ | $=30$ | $\\leq n$ | $=7$ |\n| $8 \\sim 10$ | $=30$ | $\\leq n$ | $=12$ |\n| $11 \\sim 13$ | $=30$ | $=1$ | $=100$ |\n| $14 \\sim 15$ | $=5$ | $\\leq n$ | $=50$ |\n| $16$ | $=15$ | $\\leq n$ | $=100$ |\n| $17 \\sim 18$ | $=30$ | $\\leq n$ | $=30$ |\n| $19 \\sim 20$ | $=30$ | $\\leq n$ | $=100$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2670, "prompt": "### Problem Description\n\nDongdong has recently become fascinated by random algorithms, and random number generation is the foundation of random algorithms. Dongdong plans to use the Linear Congruential Method to generate a sequence of random numbers. This method requires setting four non-negative integer parameters $m$, $a$, $c$, and $X_0$, and generates a sequence of random numbers $\\lbrace X_n \\rbrace$ based on the following formula:\n\n$$\nX_{n+1} = (aX_n + c) \\bmod m\n$$\n\nHere, $\\bmod m$ represents the remainder of the division of the preceding number by $m$. From this formula, it can be observed that the next number in the sequence is always derived from the previous number.\n\nSequences generated using this method exhibit properties of randomness, and this method is widely used, including in common C++ and Pascal random number generation library functions, which implement this method.\n\nAlthough Dongdong knows that sequences generated this way have good randomness, he is eager to know the value of $X_n$ as soon as possible. Since Dongdong needs random numbers between $0$, $1$, ..., $g-1$, he will take the remainder of $X_n$ divided by $g$, i.e., $X_n \\bmod g$. Your task is to simply tell Dongdong the result of $X_n \\bmod g$.\n\n---\n\n### Input Format\n\nA single line containing $6$ space-separated integers $m$, $a$, $c$, $X_0$, $n$, and $g$, where $a$, $c$, $X_0$ are non-negative integers, and $m$, $n$, $g$ are positive integers.\n\n---\n\n### Output Format\n\nOutput a single integer, which is the value of $X_n \\bmod g$.\n\n---\n\n### Examples\n\nThe first few terms of $\\lbrace X_n \\rbrace$ are:\n\n$$\n\\begin{array}{ l | c | r } \\hline\nk & 0 & 1 & 2 & 3 & 4 & 5 \\\\ \\hline\nX_k & 1 & 4 & 6 & 0 & 7 & 8 \\\\ \\hline\n\\end{array}\n$$\n\nThus, the answer is $X_5 \\bmod g = 8 \\bmod 3 = 2$.\n\n---\n\n### Constraints and Hints\n\n| Test Case Number | $n$ | $m,a,c,X_0$ | Properties of $m,a$ |\n| :-: | :-: | :-: | :-: |\n| 1 | $n \\leq 100$ | $m,a,c,X_0 \\leq 100$ | $m$ is a prime number |\n| 2 | $n \\leq 1000$ | $m,a,c,X_0 \\leq 1000$ | $m$ is a prime number |\n| 3 | $n \\leq 10^4$ | $m,a,c,X_0 \\leq 10^4$ | $m$ is a prime number |\n| 4 | $n \\leq 10^4$ | $m,a,c,X_0 \\leq 10^4$ | $m$ is a prime number |\n| 5 | $n \\leq 10^5$ | $m,a,c,X_0 \\leq 10^4$ | $m$ and $a-1$ are coprime |\n| 6 | $n \\leq 10^5$ | $m,a,c,X_0 \\leq 10^4$ | $m$ and $a-1$ are coprime |\n| 7 | $n \\leq 10^5$ | $m,a,c,X_0 \\leq 10^4$ | $m$ and $a-1$ are coprime |\n| 8 | $n \\leq 10^6$ | $m,a,c,X_0 \\leq 10^4$ | - |\n| 9 | $n \\leq 10^6$ | $m,a,c,X_0 \\leq 10^9$ | $m$ is a prime number |\n| 10 | $n \\leq 10^6$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 11 | $n \\leq 10^{12}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ is a prime number |\n| 12 | $n \\leq 10^{12}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ is a prime number |\n| 13 | $n \\leq 10^{16}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ and $a-1$ are coprime |\n| 14 | $n \\leq 10^{16}$ | $m,a,c,X_0 \\leq 10^9$ | $m$ and $a-1$ are coprime |\n| 15 | $n \\leq 10^{16}$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 16 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 17 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^9$ | - |\n| 18 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^{18}$ | $m$ is a prime number |\n| 19 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^{18}$ | $m$ and $a-1$ are coprime |\n| 20 | $n \\leq 10^{18}$ | $m,a,c,X_0 \\leq 10^{18}$ | - |\n\nFor all test cases, $n \\geq 1$, $m \\geq 1$, $a \\geq 0$, $c \\geq 0$, $X_0 \\geq 0$, $1 \\leq g \\leq 10^8$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3566, "prompt": "### Problem Description\n\nGiven a sequence of positive integers of length $n$ that is non-strictly increasing, $1 \\leq a_1 \\leq a_2 \\leq \\cdots \\leq a_n$. The operation you can perform each time is: arbitrarily select any positive integer $1 < i < n$ and replace $a_i$ with $a_{i - 1} + a_{i + 1} - a_i$. Find the minimum variance of this sequence after performing some number of operations. Output the result multiplied by $n^2$.\n\nThe definition of variance is: the average of the squares of the differences between each number in the sequence and the mean of the sequence. More formally, the variance is defined as $D = \\frac{1}{n} \\sum_{i = 1}^{n} {(a_i - \\bar{a})}^2$, where $\\bar{a} = \\frac{1}{n} \\sum_{i = 1}^{n} a_i$.\n\n### Input Format\n\nThe first line of the input contains a positive integer $n$, ensuring $n \\leq {10}^4$.\n\nThe second line contains $n$ positive integers, where the $i$th number represents the value of $a_i$. It is guaranteed that $1 \\leq a_1 \\leq a_2 \\leq \\cdots \\leq a_n$.\n\n### Output Format\n\nOutput a single line containing a non-negative integer, which represents the minimum variance multiplied by $n^2$.\n\n**Sample Explanation #1**\n\nFor $(a_1, a_2, a_3, a_4) = (1, 2, 4, 6)$, after the first operation, the sequence becomes $(1, 3, 4, 6)$, and after the second operation, the sequence becomes $(1, 3, 5, 6)$. No new sequences can be obtained after this.\n\nFor $(a_1, a_2, a_3, a_4) = (1, 2, 4, 6)$, the mean value is $\\frac{13}{4}$, and the variance is $\\frac{1}{4}({(1 - \\frac{13}{4})}^2 + {(2 - \\frac{13}{4})}^2 + {(4 - \\frac{13}{4})}^2 + {(6 - \\frac{13}{4})}^2) = \\frac{59}{16}$.\n\nFor $(a_1, a_2, a_3, a_4) = (1, 3, 4, 6)$, the mean value is $\\frac{7}{2}$, and the variance is $\\frac{1}{4}({(1 - \\frac{7}{2})}^2 + {(3 - \\frac{7}{2})}^2 + {(4 - \\frac{7}{2})}^2 + {(6 - \\frac{7}{2})}^2) = \\frac{13}{4}$.\n\nFor $(a_1, a_2, a_3, a_4) = (1, 3, 5, 6)$, the mean value is $\\frac{15}{4}$, and the variance is $\\frac{1}{4}({(1 - \\frac{15}{4})}^2 + {(3 - \\frac{15}{4})}^2 + {(5 - \\frac{15}{4})}^2 + {(6 - \\frac{15}{4})}^2) = \\frac{59}{16}$.\n\n**Data Constraints**\n\n| Test Case ID | $n \\leq$ | $a_i \\leq$ |\n|:-:|:-:|:-:|\n| $1 \\sim 3$ | $4$ | $10$ |\n| $4 \\sim 5$ | $10$ | $40$ |\n| $6 \\sim 8$ | $15$ | $20$ |\n| $9 \\sim 12$ | $20$ | $300$ |\n| $13 \\sim 15$ | $50$ | $70$ |\n| $16 \\sim 18$ | $100$ | $40$ |\n| $19 \\sim 22$ | $400$ | $600$ |\n| $23 \\sim 25$ | ${10}^4$ | $50$ |\n\nFor all test cases, it is ensured that $1 \\leq n \\leq {10}^4$ and $1 \\leq a_i \\leq 600$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2447, "prompt": "### Problem Description\n\nThese days, Bunny and Eggy have become fond of a new board game.\n\nThe game is played on a chessboard with $n$ rows and $m$ columns. Before the game starts, one cell on the chessboard is empty, while all other cells contain a chess piece, which can either be black or white.\n\nIn each round of the game, Bunny goes first, followed by Eggy, taking turns alternately. The rules for their moves are as follows:\n* On each turn, Bunny chooses a white chess piece adjacent to the empty cell and moves it into the empty cell.\n* On each turn, Eggy chooses a black chess piece adjacent to the empty cell and moves it into the empty cell.\n\nThe first player who cannot make a valid move according to the rules loses the game. To make the description clearer, the move of \"moving the chess piece in row $x$, column $y$ into the empty cell\" is denoted as $M(x,y)$.\n\nFor example, the following are three examples of the game:\n\n![](https://i.loli.net/2018/06/11/5b1e029d60b0d.png)\n\n![](https://i.loli.net/2018/06/11/5b1e029d6886a.png)\n\n![](https://i.loli.net/2018/06/11/5b1e029d7f3b9.png)\n\nRecently, Bunny has been losing games a lot, and Eggy has been especially smug about it. As a result, Bunny has approached you, her good friend, for help. She has brought you the game record of a match where she lost to Eggy. Your task is to identify all the moments during the game where Bunny \"made mistakes.\"\n\nNote:\n* Two cells are considered adjacent if and only if they share a common edge.\n* Bunny's move is considered a \"mistake\" if and only if she had a winning strategy before the move but, after the move, Eggy has a winning strategy.\n\n---\n\n### Input Format\nThe first line contains two integers $n$ and $m$.\n\nThe next $n$ lines describe the initial chessboard. The $i$-th line contains $m$ characters, where each character is one of the following:\n* An uppercase letter `X`, `O`, or a dot `.`. \n * The letter `X` represents a cell with a black chess piece.\n * The letter `O` represents a cell with a white chess piece.\n * The dot `.` represents the empty cell.\n\nIt is guaranteed that the board contains exactly one empty cell.\n\nThe next line contains an integer $k$ ($1 \\le k \\le 1000$), representing the total number of moves made by Bunny and Eggy (Bunny moves $k$ times, and Eggy also moves $k$ times).\n\nThe next $2k$ lines describe the gameplay process. Specifically:\n* The $2i - 1$-th line corresponds to Bunny's $i$-th move (the move with index $i$).\n* The $2i$-th line corresponds to Eggy's $i$-th move.\n\nEach move is described by two integers $x, y$, which represent moving the chess piece in row $x$, column $y$ into the empty cell.\n\nIt is guaranteed that throughout the game:\n* There is exactly one empty cell on the board at any time.\n* Every move made by Bunny and Eggy is valid.\n* Eggy wins the game in the end.\n\n---\n\n### Output Format\nThe first line of the output contains an integer $r$, representing the total number of times Bunny made mistakes during the game.\n\nThe next $r$ lines contain the indices of Bunny's mistaken moves in increasing order. Specifically:\n* The $i$-th line contains an integer $a_i$, indicating that Bunny's $i$-th mistake occurred on her $a_i$-th move during the game.\n\n---\n\n### Sample 1\n\n#### Input\n```plaintext\n2 2\nXO\n.O\n2\n1 2\n2 2\n2 1\n1 1\n```#### Output\n```plaintext\n1\n1\n```\n\n---\n\n### Sample 2\n\n#### Input\n```plaintext\n3 3\nOOO\nO.O\nXXX\n2\n2 2\n2 3\n1 3\n3 3\n```\n\n#### Output\n```plaintext\n1\n2\n```\n\n---\n\n### Sample 3\n\n#### Input\n```plaintext\n3 4\nXXXX\n.OOX\nXOOX\n2\n2 2\n2 3\n2 4\n1 4\n```\n\n#### Output\n```plaintext\n0\n```\n\n---\n\n### Sample Interpretations\n* **Sample 1** corresponds to the game shown in the first figure.\n* **Sample 2** corresponds to the game shown in the third figure.\n\n---\n\n### Constraints and Notes\n\nThe following table outlines the constraints on the problem:\n\n| Test Case Number | Scale of $n$ | Scale of $m$ |\n| :-: | :-: | :-: |\n| 1 | $n = 1$ | $1 \\le m \\le 20$ |\n| 2 | $n = 1$ | $1 \\le m \\le 20$ |\n| 3 | $n = 3$ | $m = 4$ |\n| 4 | $n = 4$ | $m = 4$ |\n| 5 | $n = 4$ | $m = 4$ |\n| 6 | $n = 4$ | $m = 5$ |\n| 7 | $n = 4$ | $m = 5$ |\n| 8 | $n = 3$ | $m = 7$ |\n| 9 | $n = 2$ | $1 \\le m \\le 40$ |\n| 10 | $n = 2$ | $1 \\le m \\le 40$ |\n| 11 | $n = 2$ | $1 \\le m \\le 40$ |\n| 12 | $n = 2$ | $1 \\le m \\le 40$ |\n| 13 | $n = 2$ | $1 \\le m \\le 40$ |\n| 14 | $n = 2$ | $1 \\le m \\le 40$ |\n| 15 | $1 \\le n \\le 16$ | $1 \\le m \\le 16$ |\n| 16 | $1 \\le n \\le 16$ | $1 \\le m \\le 16$ |\n| 17 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n| 18 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n| 19 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n| 20 | $1 \\le n \\le 40$ | $1 \\le m \\le 40$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2608, "prompt": "### Problem Description\n$n$ friends (numbered from $0$ to $n-1$) sit in a circle and play a game. The positions are numbered clockwise from $0$ to $n-1$. Initially, the $0$th friend is at position $0$, the $1$st friend is at position $1$, and so on.\n\nThe rules of the game are as follows: During each round, the friend at position $0$ moves clockwise to position $m$, the friend at position $1$ moves to position $m+1$, and so forth. The friend at position $n\u2212m$ moves to position $0$, the friend at position $n\u2212m+1$ moves to position $1$, and finally, the friend at position $n\u22121$ moves clockwise to position $m\u22121$.\n\nGiven that a total of $10^k$ rounds are played, determine the position of the friend numbered $x$ after all the rounds.\n\n### Input Format\nThe input consists of $1$ line containing $4$ integers $n$, $m$, $k$, and $x$, separated by spaces.\n\n### Output Format\nOutput $1$ line containing $1$ integer, representing the final position of the friend numbered $x$ after $10^k$ rounds.\n\n### Example\n\n#### Input:\n```\n10 3 1 4\n```#### Output:\n```\n7\n```\n\n### Constraints and Notes\n- For $30\\%$ of the data, $0 < k < 7$;\n- For $80\\%$ of the data, $0 < k < 10^7$;\n- For $100\\%$ of the data, $1 < n < 10^6$, $0 < m < n$, $1 \\leq x \\leq n$, $0 < k < 10^9$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2421, "prompt": "### Problem Description\n\nThere are $n$ students (numbered from $1$ to $n$) playing an information transmission game. In the game, each student has a fixed target to whom they transmit information. Specifically, the information transmission target for the student numbered $i$ is the student numbered $T_i$. At the beginning of the game, each student only knows their own birthday. In each subsequent round, all students simultaneously share the birthday information they currently know with their respective transmission targets (note: some students may receive information from multiple people, but every student only shares their information with one person \u2014 their transmission target). The game ends when a student learns their own birthday from someone else. Your task is to determine the total number of rounds the game can proceed before it ends.\n\n---\n\n### Input Format\n\nThe input consists of $2$ lines:\n\n- The first line contains a single positive integer $n$, representing the number of students. \n- The second line contains $n$ positive integers $T_1, T_2, \\ldots, T_n$, where the integer $T_i$ indicates that the transmission target of the student numbered $i$ is the student numbered $T_i$. Here, $T_i \\leq n$ and $T_i \\neq i$.\n\nIt is guaranteed that the game will eventually end.\n\n---\n\n### Output Format\n\nOutput a single line containing one integer, representing the total number of rounds the game runs.\n\n---\n\n### Sample\n\n(Provide example input and output here.)\n\n---\n\n### Constraints and Hints\n\n- For $30\\%$ of the data, $n \\leq 200$; \n- For $60\\%$ of the data, $n \\leq 2500$; \n- For $100\\%$ of the data, $n \\leq 200,000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2355, "prompt": "### Problem Description\nT Company is a manufacturer that specializes in producing colorful beaded necklaces. Their necklaces are known for innovative designs, diverse styles, and reasonable prices, making them highly popular among young people. Recently, T Company decided to launch a necklace self-production system, allowing customers to design their own beautiful necklaces according to their preferences. \n\nThis necklace self-production system consists of hardware and software components. The software system interacts with the user and controls the hardware system, while the hardware system executes commands from the software to produce the specified necklace. The hardware system has already been completed, but the software system is yet to be developed. T Company has approached you, a participant in a national informatics competition, to help them develop a software simulation system. \n\nA necklace consists of $N$ beads, each of a color chosen from the set $1, 2, \\dots , c$. The necklace is affixed to a flat surface, and one position on the surface is designated as position $1$. The other positions are numbered $2, 3, \\dots, N$ in a clockwise direction.\n\n![fff(1).png](https://i.loli.net/2018/02/12/5a81482d1a124.png)\n\nYour task is to write a software system that supports the following commands:\n\n![fa.png](https://i.loli.net/2018/02/12/5a81482d414fe.png)\n\n#### Clarifications\n- **On Rotation and Reversal:** \n The `Rotate` command rotates the \"beads\" without changing the numbering of the \"positions\", while the `Flip` command always uses position $1$ as the axis of symmetry.\n \n- **On the `CountSegment` Command:** \n The `CS` command queries how many \"segments\" are present in a specified \"line segment\". Note that when the queried length equals $N$, the query is still considered as a \"line segment\".\n\n---\n\n### Input Format\nThe first line of input contains two integers $N$ and $c$, representing the number of beads in the necklace and the number of colors, respectively. \nThe second line contains $N$ integers, $x_1, x_2, \\dots, x_N$, representing the colors of the beads from position $1$ to position $N$, where $1 \\leq x_i \\leq c$. \nThe third line contains an integer $Q$, representing the number of commands. The following $Q$ lines each contain one command as described above. \n\n---\n\n### Output Format\nFor every `Count` (`C`) and `CountSegment` (`CS`) command, output an integer representing the corresponding answer.\n\n---\n\n### Example\n\n#### Input\n```\n10 3\n1 1 2 2 3 3 3 2 2 1\n6\nR 2\nC 3\nCS 1 6\nF\nC 4\nCS 1 10\n```#### Output\n```\n2\n2\n1\n3\n4\n```\n\n---\n\n### Data Range and Notes\n- For $60\\%$ of the test cases, $N \\leq 1000$ and $Q \\leq 1000$. \n- For $100\\%$ of the test cases, $N \\leq 500,000$, $Q \\leq 500,000$, and $c \\leq 1000$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2296, "prompt": "### Problem Background\n\nThe legendary Nine-Headed Dragon is an extremely gluttonous creature. Although it is called the \"Nine-Headed Dragon,\" this name only refers to the fact that it was born with nine heads. During its growth, it sometimes grows many new heads, causing the total number of heads to greatly exceed nine; naturally, some older heads may also fall off due to aging.\n\n### Problem Description\n\nOne day, a Nine-Headed Dragon with $M$ heads encounters a tree with $N$ fruits and becomes ecstatic, wishing it could eat all the fruits in one bite. However, every head must be attended to. Thus, the $N$ fruits need to be split into $M$ groups, with each group containing at least one fruit, so that each head can eat one group.\n\nAmong these $M$ heads, there is one head that is the largest, known as the \"big head,\" which is the leader of all the heads. The big head must eat exactly $K$ fruits, and these $K$ fruits must include the single biggest fruit. The fruits are connected by $N-1$ branches, forming a structure such that the entire tree is interconnected: starting from any fruit, one can traverse the branches to reach any other fruit.\n\nFor each branch, if the two fruits it connects are eaten by different heads, the two heads will jointly break the branch to separate the fruits. If the two fruits are eaten by the same head, this head will eat the fruits together with the branch, avoiding the need for separation. However, eating a branch is uncomfortable; each branch has a \"discomfort value,\" and the dragon's overall discomfort value is defined as the sum of the discomfort values of all the branches eaten by its heads.\n\nThe Nine-Headed Dragon hopes to minimize its overall discomfort value. Can you help it calculate the minimum discomfort value?\n\n### Input Format\n\n- The first line contains three integers $N$, $M$, and $K$. The $N$ fruits are numbered $1, 2, \\dots, N$, and the biggest fruit is always numbered as $1$.\n- Lines $2$ through $N$ describe the structure of the tree. Each line contains three integers $a$, $b$, and $c$, indicating there is a branch with a discomfort value of $c$ connecting fruit $a$ and fruit $b$.\n\n### Output Format\n\n- Output a single integer in one line, representing the minimum discomfort value of the dragon while meeting the requirement of the \"big head.\" If the requirements cannot be satisfied, output $-1$.\n\n### Example\n\nFor the example shown in **Figure 1**, the fruit tree contains $8$ fruits and $7$ branches. The discomfort values are labeled next to each branch. The Nine-Headed Dragon has $2$ heads, and the big head needs to eat $4$ fruits, including the biggest fruit. That is, $N=8$, $M=2$, and $K=4$:\n\n![](https://img.loj.ac.cn/2022/06/09/9f4ca2a84dced.png)\n\n**Figure 1** shows the structure of the fruit tree, and **Figure 2** shows the optimal strategy.\n\n### Constraints and Hints\n\nFor $100\\%$ of the data:\n- $1 \\leq K \\leq N \\leq 300$\n- $2 \\leq M \\leq N$\n- $1 \\leq a, b \\leq N$\n- $0 \\leq c \\leq 10^5$\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3160, "prompt": "### Problem Description\nLittle S is playing a game called \"Dou Dizhu\" with Little F.\n\nUnfortunately, Little S finds that he cannot win against Little F during the card play phase, so he decides to cheat during the shuffling phase.\n\nA deck consists of $n$ cards, numbered sequentially from $1 \\sim n$ from top to bottom. The **score** of the card numbered $i$ is denoted as $f(i)$. In this problem, $f(i)$ can only have two possible values: $f(i) = i$ or $f(i) = i^2$.\n\nThe shuffling process is similar to how we shuffle cards in real-life games. Below is a formalized definition of the process:\n\nThe shuffling consists of $m$ rounds, which are executed in sequence. During the $i$-th round of shuffling:\n1. Little S takes out the top $A_i$ cards. This splits the deck into two piles: the first pile contains the top $A_i$ cards, and the second pile contains the remaining $n - A_i$ cards, both maintaining their relative order. Specifically, if $A_i = n$ or $A_i = 0$, one of the piles will be empty.\n2. The two piles are then merged into a new third pile. If the first pile still contains $X$ cards and the second pile still contains $Y$ cards, there is a probability of $\\frac{X}{X+Y}$ of taking the bottom card of the first pile and placing it on the top of the new third pile, and a probability of $\\frac{Y}{X+Y}$ of taking the bottom card of the second pile and placing it on the top of the new third pile.\n3. Step 2 is repeated until both piles are empty. At this point, the current round of shuffling is complete.\n\nSince the shuffling process is random, Little S cannot determine the exact card in a specific position. However, Little S wants to ask about the **expected score** of the card at a specific position after $m$ rounds of shuffling. He will ask you $Q$ such questions.\n\n---\n\n### Input Format\nThe input is read from a file named `landlords.in`.\n\nThe first line contains three positive integers $n$, $m$, and $\\text{type}$, which represent the number of cards, the number of shuffling rounds, and the type of $f(i)$, respectively. When $\\text{type} = 1$, $f(i) = i$. When $\\text{type} = 2$, $f(i) = i^2$.\n\nThe second line contains $m$ integers, denoting $A_1 \\sim A_m$.\n\nThe third line contains a positive integer $Q$, representing the number of questions Little S will ask.\n\nThe next $Q$ lines each contain a positive integer $c_i$, representing that Little S wants to know the **expected score** of the card at the $c_i$-th position from the top. It is guaranteed that $1 \\leq c_i \\leq n$.\n\n---\n\n### Output Format\nThe output is written to a file named `landlords.out`.\n\nThe output consists of $Q$ lines, each containing an integer, representing the answer under modulo $998244353$.\n\nSpecifically, if the answer in its simplest fractional form is $\\frac{a}{b}$, where $a$ and $b$ are coprime, output an integer $x$ such that $bx \\equiv a \\pmod{998244353}$ and $0 \\leq x < 998244353$. It can be proven that such an integer $x$ is unique.\n\n---\n\n### Example\nThere is a $\\frac{1}{4}$ probability that, after shuffling, the deck order from top to bottom is $\\{1, 2, 3, 4\\}$.\n\nThere is a $\\frac{1}{4}$ probability that the deck order is $\\{1, 2, 4, 3\\}$.\n\nThere is a $\\frac{1}{4}$ probability that the deck order is $\\{1, 4, 2, 3\\}$.\n\nThere is a $\\frac{1}{4}$ probability that the deck order is $\\{4, 1, 2, 3\\}$.\n\nThus, the first position has a $\\frac{1}{4}$ probability of being $4$ and a $\\frac{3}{4}$ probability of being $1$, resulting in an expected score of $\\frac{7}{4}$.\n\nTo help you better understand the shuffling process, the following diagram illustrates the process that results in $\\{1, 4, 2, 3\\}$:\n\n![No.3160.CN.png](https://img.loj.ac.cn/2020/12/22/5fe13fd6d76c0.png)\n\n---\n\n### Constraints and Hints\nFor all test cases: $3 \\leq n \\leq 10^7$, $1 \\leq m, Q \\leq 5 \\times 10^5$, $0 \\leq A_i \\leq n$, and $\\text{type} \\in \\{1, 2\\}$.\n\nAdditional constraints for specific test cases are as follows:\n\n| Test Case ID | $n$ | $m$ | $\\text{type}=$ | Additional Properties |\n| :----------: | :-------: | :------------: | :------------: | :-----------------------------: |\n| $1$ | $\\leq 10$ | $\\leq 1$ | $1$ | None |\n| $2$ | $\\leq 80$ | $\\leq 80$ | $1$ | None |\n| $3$ | $\\leq 80$ | $\\leq 80$ | $2$ | None |\n| $4$ | $\\leq 100$| $5 \\times 10^5$| $2$ | All $A_i$ are identical |\n| $5$ | $10^7$ | $5 \\times 10^5$| $1$ | None |\n| $6$ | $10^7$ | $5 \\times 10^5$| $1$ | None |\n| $7$ | $10^7$ | $5 \\times 10^5$| $1$ | None |\n| $8$ | $10^7$ | $5 \\times 10^5$| $2$ | None |\n| $9$ | $10^7$ | $5 \\times 10^5$| $2$ | None |\n| $10$ | $10^7$ | $5 \\times 10^5$| $2$ | None |\n\nNote that we do **not guarantee** $Q \\leq n$.\n\nHere we provide the definition of the expected value $\\mathbb{E}[x]$ of a discrete random variable $X$:\n\nGiven a discrete random variable $X$ with possible values $X_1, X_2, \\ldots, X_k$ and corresponding probabilities $\\text{Pr}[X_1], \\text{Pr}[X_2], \\ldots, \\text{Pr}[X_k]$, the expected value is defined as:\n$$\n\\mathbb{E}[x] = \\sum_{i=1}^k X_i \\text{Pr}[X_i]\n$$\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2667, "prompt": "### Problem Description\n\nTingting is a little girl who loves matrices. One day, she decided to use a computer to generate a huge matrix with $n$ rows and $m$ columns (you don\u2019t need to worry about how she stores it). The matrix she generates satisfies a magical property: if $F[i][j]$ represents the element in the $i$-th row and $j$-th column of the matrix, then $F[i][j]$ satisfies the following recurrence relations:\n$$\n\\begin{cases}\nF[1][1] = 1 \\\\\nF[i][j] = a * F[i][j-1]+b & j \\neq 1 \\\\\nF[i][1] = c * F[i-1][m]+d & i \\neq 1\n\\end{cases}\n$$\nHere, $a$, $b$, $c$, $d$ are given constants.\n\nNow Tingting wants to know the value of $F[n][m]$. Please help her calculate it. Since the final result may be very large, you only need to output $F[n][m]$ modulo $1,000,000,007$.\n\n---\n\n### Input Format\n\nA single line containing six integers: $n$, $m$, $a$, $b$, $c$, $d$, as described in the problem statement.\n\n---\n\n### Output Format\n\nOutput a single integer, representing $F[n][m]$ modulo $1,000,000,007$.\n\n---\n\n### Examples\n\n#### Example Input 1\n```plain\n3 4 1 3 2 6\n```#### Example Output 1\n```plain\n85\n```\n\n#### Example Explanation 1\nThe matrix for the example is:\n$$\n\\begin{pmatrix} \n1 & 4 & 7 & 10 \\\\ \n26 & 29 & 32 & 35 \\\\ \n76 & 79 & 82 & 85 \n\\end{pmatrix}\n$$\n\n#### Example Input/Output 2\nRefer to the attached files: `matrix.in` and `matrix.ans`.\n\n---\n\n### Constraints and Hints\n\n| Test Case ID | Constraints |\n| :-: | :-: |\n| 1 | $1 \\le n,m \\le 10$; $1 \\le a,b,c,d \\le 1,000$ |\n| 2 | $1 \\le n,m \\le 100$; $1 \\le a,b,c,d \\le 1,000$ |\n| 3 | $1 \\le n,m \\le 10^3$; $1 \\le a,b,c,d \\le 10^9$ |\n| 4 | $1 \\le n,m \\le 10^3$; $1 \\le a,b,c,d \\le 10^9$ |\n| 5 | $1 \\le n,m \\le 10^9$; $1 \\le a = c \\le 10^9$; $1 \\le b = d \\le 10^9$ |\n| 6 | $1 \\le n,m \\le 10^9$; $a = c = 1$; $1 \\le b,d \\le 10^9$ |\n| 7 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 8 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 9 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 10 | $1 \\le n,m,a,b,c,d \\le 10^9$ |\n| 11 | $1 \\le n,m \\le 10^{1000}$; $a = c = 1$; $1 \\le b,d \\le 10^9$ |\n| 12 | $1 \\le n,m \\le 10^{1000}$; $1 \\le a = c \\le 10^9$; $1 \\le b = d \\le 10^9$ |\n| 13 | $1 \\le n,m \\le 10^{1000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 14 | $1 \\le n,m \\le 10^{1000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 15 | $1 \\le n,m \\le 10^{20000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 16 | $1 \\le n,m \\le 10^{20000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 17 | $1 \\le n,m \\le 10^{1,000,000}$; $a = c = 1$; $1 \\le b,d \\le 10^9$ |\n| 18 | $1 \\le n,m \\le 10^{1,000,000}$; $1 \\le a = c \\le 10^9$; $1 \\le b = d \\le 10^9$ |\n| 19 | $1 \\le n,m \\le 10^{1,000,000}$; $1 \\le a,b,c,d \\le 10^9$ |\n| 20 | $1 \\le n,m \\le 10^{1,000,000}$; $1 \\le a,b,c,d \\le 10^9$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3760, "prompt": "### Problem Description\nDuring the World Expo, the air passenger traffic in Shanghai greatly exceeded normal levels, leading to frequent air traffic control occurrences. Recently, Xiao X experienced two consecutive delays of more than two hours at the airport due to air traffic control. Xiao X is quite dissatisfied with this situation.\n\nOn a recent trip to Yantai, Xiao X unfortunately encountered air traffic control again. This prompted Xiao X to ponder the problem of air traffic control.\n\nSuppose there are currently $n$ delayed flights, numbered from $1$ to $n$. The airport has only one runway for takeoff, and all flights must take off in a certain sequence (referred to as the takeoff sequence). The takeoff order of a flight is defined as its position in the takeoff sequence, i.e., the order in which the flight takes off.\n\nThe takeoff sequence is subject to two types of constraints:\n\n- **Type 1 (Latest Takeoff Time Constraint):** The takeoff order of the flight numbered $i$ must not exceed $k_i$.\n\n- **Type 2 (Relative Takeoff Order Constraint):** Some relative takeoff order constraints $(a, b)$ exist, indicating that flight $a$ must take off before flight $b$. In other words, the takeoff order of flight $a$ must be smaller than that of flight $b$.\n\nXiao X considers two questions: \n1. Given the above two types of constraints, is it possible to compute a feasible takeoff sequence? \n2. Considering both types of constraints, what is the minimum possible takeoff order for each flight out of all feasible takeoff sequences?\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, where $n$ represents the number of flights and $m$ represents the number of Type 2 constraints (relative takeoff order constraints).\n\nThe second line contains $n$ positive integers $k_1, k_2, \\cdots, k_n$.\n\nThe following $m$ lines each contain two positive integers $a$ and $b$, representing a Type 2 constraint $(a, b)$, where $1 \\leq a, b \\leq n$, indicating that flight $a$ must take off before flight $b$.\n\n---\n\n### Output Format\n- The first line contains $n$ integers, representing one feasible takeoff sequence, separated by a space. The input guarantees that at least one feasible takeoff sequence exists. If there are multiple solutions, you can output any one of them.\n- The second line contains $n$ integers $t_1, t_2, \\cdots, t_n$, where $t_i$ represents the minimum possible takeoff order for flight $i$ among all feasible takeoff sequences, separated by a space.\n\n---\n\n### Sample Input 1\n```\n5 4\n5 5 3 5 4\n3 1\n5 1\n3 4\n2 5\n```### Sample Output 1\n```\n3 5 1 4 2\n3 5 1 4 4\n```\n\n#### Explanation for Sample 1:\nThe takeoff sequence `3 5 1 4 2` satisfies all the constraints. All takeoff sequences that meet the constraints are:\n\n$$\n\\begin{aligned}\n3\\ 4\\ 5\\ 1\\ 2\\\\\n3\\ 5\\ 1\\ 2\\ 4\\\\\n3\\ 5\\ 1\\ 4\\ 2\\\\\n3\\ 5\\ 4\\ 1\\ 2\\\\\n5\\ 3\\ 1\\ 2\\ 4\\\\\n5\\ 3\\ 1\\ 4\\ 2\\\\\n5\\ 3\\ 4\\ 1\\ 2\n\\end{aligned}\n$$\n\nBecause there are Type 2 constraints $(5,1)$ and $(3,1)$, flight $1$ can only be scheduled to take off after both flights $5$ and $3$, so its earliest takeoff order is $3$. The other flights follow a similar approach.\n\n---\n\n### Sample Input 2\n```\n5 3\n5 5 3 5 5\n1 4\n2 4\n3 4\n```\n\n### Sample Output 2\n```\n1 2 3 5 4\n1 2 3 4 4\n```\n\n#### Explanation for Sample 2:\nAlthough flights $4$ and $5$ have no relative takeoff order constraints, flights $1$, $2$, and $3$ must take off in the first three slots, meaning flights $4$ and $5$ can only take off starting from the fourth slot.\n\n---\n\n### Constraints and Hints\n- For $30\\%$ of the test cases, $n \\leq 10$. \n- For $60\\%$ of the test cases, $n \\leq 500$. \n- For $100\\%$ of the test cases, $n \\leq 2 \\times 10^3$ and $m \\leq 10^4$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3761, "prompt": "### Problem Description\n\nLittle Z is a well-known pianist. Recently, Dr. C gifted Little Z a super piano, and Little Z hopes to use this piano to create the most beautiful music in the world.\n\nThis super piano can play $n$ notes, numbered from $1$ to $n$. The beauty value of the $i$-th note is $A_i$, where $A_i$ can be positive or negative.\n\nA \"super chord\" is composed of a series of consecutive notes, containing at least $L$ and at most $R$ notes. The beauty value of a super chord is defined as the sum of the beauty values of all the notes it contains. Two super chords are considered the same if and only if the set of notes they contain is identical.\n\nLittle Z plans to compose a piece of music consisting of $k$ super chords. To make the music more melodious, the $k$ super chords must all be distinct. The beauty value of a piece of music is defined as the sum of the beauty values of all the super chords it contains. Little Z wants to know the maximum beauty value of a piece of music he can compose.\n\n---\n\n### Input Format\n\nThe first line contains four positive integers $n$, $k$, $L$, and $R$. Here:\n- $n$ is the number of notes,\n- $k$ is the number of super chords in the piece of music,\n- $L$ and $R$ are the lower and upper limits on the number of notes a super chord can contain, respectively.\n\nThe next $n$ lines each contain a single integer $A_i$, which represents the beauty value of the $i$-th note in order.\n\n---\n\n### Output Format\n\nOutput a single integer, representing the maximum possible beauty value of the piece of music.\n\n---\n\n### Example\n\nThere are $5$ different super chords:\n\n1. Notes $1 \\sim 2$, beauty value $3 + 2 = 5$;\n2. Notes $2 \\sim 3$, beauty value $2 + (-6) = -4$;\n3. Notes $3 \\sim 4$, beauty value $(-6) + 8 = 2$;\n4. Notes $1 \\sim 3$, beauty value $3 + 2 + (-6) = -1$;\n5. Notes $2 \\sim 4$, beauty value $2 + (-6) + 8 = 4$.\n\nThe optimal solution is: the piece of music consists of super chords $1$, $3$, and $5$, with a total beauty value of $5 + 2 + 4 = 11$.\n\n---\n\n### Constraints and Hints\n\n| Test Case | $n$ | $k$ |\n|-----------|-------------|-------------|\n| $1$ | $\\leq 10$ | $\\leq 100$ |\n| $2$ | $\\leq 1000$ | $\\leq 5 \\times 10^5$ |\n| $3$ | $\\leq 10^5$ | $= 1$ |\n| $4$ | $\\leq 10^4$ | $\\leq 10^4$ |\n| $5$ | $\\leq 5 \\times 10^5$ | $\\leq 10^4$ |\n| $6$ | $\\leq 8 \\times 10^4$ | $\\leq 8 \\times 10^4$ |\n| $7$ | $\\leq 10^5$ | $\\leq 10^5$ |\n| $8$ | $\\leq 10^5$ | $\\leq 5 \\times 10^5$ |\n| $9$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ |\n| $10$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ |\n\nAll data satisfy:\n- $-1000 \\leq A_i \\leq 1000$, \n- $1 \\leq L \\leq R \\leq n$, and \n- it is guaranteed that a valid piece of music always exists.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3157, "prompt": "### Problem Description\nLittle R enjoys researching robots.\n\nRecently, Little R has developed two types of robots, named `P`-type robots and `Q`-type robots. He wants to test the mobility of these two types of robots. The test takes place on a row of $n$ pillars, numbered from $1$ to $n$ from left to right. The height of pillar $i$ is represented by a positive integer $h_i$. Robots **can only move between adjacent pillars**, i.e., if a robot is currently on pillar $i$, it can only attempt to move to pillar $i-1$ or pillar $i+1$.\n\nFor each test, Little R selects a starting point $s$ and places both types of robots on pillar $s$. Then, the robots move according to their respective moving rules.\n\nThe `P`-type robot always moves **to the left** but **cannot** move to pillars that are **higher** than the starting pillar $s$. More specifically, the `P`-type robot stops at pillar $l (l \\leq s)$ **if and only if** the following two conditions are simultaneously satisfied:\n\n- $l = 1$ or $h_{l-1} > h_s$.\n- For all $j$ such that $l \\leq j \\leq s$, $h_j \\leq h_s$.\n\nThe `Q`-type robot always moves **to the right** but **can only** move to pillars that are **lower** than the starting pillar $s$. More specifically, the `Q`-type robot stops at pillar $r (r \\geq s)$ **if and only if** the following two conditions are simultaneously satisfied:\n\n- $r = n$ or $h_{r+1} \\geq h_s$.\n- For all $j$ such that $s < j \\leq r$, $h_j < h_s$.\n\nNow, Little R can configure the height of each pillar, and the height of pillar $i$ must be in the range $[A_i, B_i]$, which satisfies $A_i \\leq h_i \\leq B_i$. Little R hopes that **no matter** where the starting point $s$ is selected, the absolute difference in the number of pillars traversed by the two robots is **less than or equal to** $2$. He wants to know how many configurations of pillar heights satisfy this requirement. Little R considers two configurations to be different if there exists some $k$ such that the height of pillar $k$ differs between the two configurations. Please tell him the number of configurations that meet the requirements modulo $10^9 + 7$.\n\n### Input Format\nThe first line contains a positive integer $n$, representing the number of pillars.\n\nThe following $n$ lines each contain two positive integers $A_i, B_i$, representing the minimum and maximum height of pillar $i$.\n\n### Output Format\nA single line that contains an integer\u2014the answer modulo $10^9 + 7$.\n\n### Additional Sample Cases\n\nYou can refer to the attached files for additional sample cases.\n\n#### Sample Case 2\n\nSee the attached files: `robot/robot2.in` and `robot/robot2.ans`.\n\n#### Sample Case 3\n\nSee the attached files: `robot/robot3.in` and `robot/robot3.ans`.\n\n#### Sample Case 4\n\nSee the attached files: `robot/robot4.in` and `robot/robot4.ans`.\n\n### Explanation of Sample Case 1\n\nThere are two possible configurations for the pillar heights:\n\n- Heights: `3 2 3 2 3`. In this case, if the starting point is set at $5$, the `P`-type robot stops at pillar $1$ after traversing $4$ pillars, while the `Q`-type robot stops at pillar $5$ after traversing $0$ pillars. This does not satisfy the condition.\n\n- Heights: `3 2 4 2 3`. In this case, the condition is satisfied regardless of the starting point, as shown in the table below:\n\n| Starting Point | `P`-type Robot | `Q`-type Robot |\n| :------------: | :------------: | :------------: |\n| $1$ | Stops at pillar $1$, traverses $0$ pillars | Stops at pillar $2$, traverses $1$ pillar |\n| $2$ | Stops at pillar $2$, traverses $0$ pillars | Stops at pillar $2$, traverses $0$ pillars |\n| $3$ | Stops at pillar $1$, traverses $2$ pillars | Stops at pillar $5$, traverses $2$ pillars |\n| $4$ | Stops at pillar $4$, traverses $0$ pillars | Stops at pillar $4$, traverses $0$ pillars |\n| $5$ | Stops at pillar $4$, traverses $1$ pillar | Stops at pillar $5$, traverses $0$ pillars |\n\n### Constraints\n\nFor all test data: $1 \\leq n \\leq 300$, $1 \\leq A_i \\leq B_i \\leq 10^9$.\n\nSpecific constraints for each test point are shown in the following table:\n\n| Test Point | $n\\leq$ | Special Property |\n| :--------: | :-----: | :--------------: |\n| $1,2$ | $7$ | $A_i=B_i, B_i\\leq 7$ |\n| $3,4$ | $7$ | $B_i\\leq 7$ |\n| $5,6,7$ | $50$ | $B_i\\leq 100$ |\n| $8,9,10$ | $300$ | $B_i\\leq 10^4$ |\n| $11,12$ | $50$ | $A_i=1, B_i=10^9$ |\n| $13,14,15$ | $50$ | None |\n| $16,17$ | $150$ | None |\n| $18,19$ | $200$ | None |\n| $20$ | $300$ | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2294, "prompt": "### Problem Background\nIn the year $5801$, humans from Earth migrated to the second planet of Alpha Tauri, where they proclaimed the founding declaration of the Galactic Federation. That year was renamed to Year 1 of the Cosmic Calendar, and humanity began expanding toward the depths of the Milky Way galaxy.\n\nIn Year $799$ of the Cosmic Calendar, a war broke out in the Bamilion Starzone between two major military factions of the galaxy. The faction \"Mountain Crushing Alliance\" dispatched a fleet of over one hundred thousand warships led by Fleet Commander Reinhard. Their opponent, \"River Sweeping Alliance,\" sent thirty thousand warships under the command of Yang Wenli to face them.\n\n### Problem Description\nYang Wenli is skilled in strategic warfare and adept at utilizing various tactics to achieve victories against larger forces. Inevitably, he developed some complacency. In this decisive battle, he divided the battlefield in the Bamilion Starzone into $30000$ columns, numbered sequentially as $1, 2, \\ldots, 30000$. He also numbered his warships from $1, 2, \\ldots, 30000$, such that the $i$-th warship was initially positioned in the $i$-th column, forming a \"long snake array\" to lure the enemy into advancing recklessly. This was the initial formation. \n\nWhen the enemy advanced, Yang Wenli issued a series of merge commands to consolidate most of his warships into a few columns in order to launch concentrated attacks. The merge command has the format `M i j`, which means that the entire warship sequence in the same column as Warship $i$ (ordered from front to back) is appended to the end of the warship sequence in the same column as Warship $j$. Naturally, each column consists of one or more warships. The execution of the merge command increases the size of the resulting column. \n\nHowever, Reinhard, with his strategic ingenuity, had already gained an upper hand. During the battle, he utilized an extensive intelligence network to eavesdrop on Yang Wenli's fleet movement commands.\n\nAs Yang Wenli issued commands to maneuver his fleet, Reinhard also issued query commands: `C i j`. Each query asks whether Warship $i$ and Warship $j$ are currently in the same column, and if they are, how many warships are positioned between them.\n\nAs a skilled software developer, you are tasked with writing a program to analyze and process Yang Wenli's commands while responding to Reinhard's queries.\n\n### Input Format\nThe first line contains an integer $T$, denoting the total number of commands.\n\nThe following $T$ lines contain one command per line. Each command follows one of the two formats below:\n\n1. `M i j`: Here, $i$ and $j$ are integers representing warship identifiers. This is a merge command issued by Yang Wenli, and it is guaranteed that Warships $i$ and $j$ are not in the same column.\n2. `C i j`: Here, $i$ and $j$ are integers representing warship identifiers. This is a query command issued by Reinhard.\n\n### Output Format\nFor each command:\n\n- If it is a merge command (`M i j`) issued by Yang Wenli, it indicates that the fleet's arrangement has changed. Your program should process this command, but no output is required.\n- If it is a query command (`C i j`) issued by Reinhard, your program should output a single integer:\n - If Warship $i$ and Warship $j$ are not in the same column, output `-1`.\n - If Warship $i$ and Warship $j$ are in the same column, output the number of warships positioned between them.\n\n### Sample\nThe following illustrates the configuration of the warship positions. Numbers in the table refer to the identifiers of the warships.\n\n| | Column 1 | Column 2 | Column 3 | Column 4 | $\\dots$ |\n| - | - | - | - | - | - |\n| Initial State | $1$ | $2$ | $3$ | $4$ | $\\dots$ |\n| `M 2 3` | $1$ | | $3$
$2$ | $4$ | $\\dots$ |\n| `C 1 2` | Warship $1$ and $2$ are not in the same column, output `-1` |\n| `M 2 4` | $1$ | | | $4$
$3$
$2$ | $\\dots$ |\n| `C 4 2` | Warship $4$ and $2$ are in the same column, and only Warship $3$ is between them. Output `1` |\n\n### Constraints and Notes\nFor $100\\%$ of the test cases:\n- $1 \\leq T \\leq 5 \\times 10^5$\n- $1 \\leq i, j \\leq 30000$\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3534, "prompt": "### Problem Description\n\nCountry C is a prosperous nation consisting of $n$ cities and $m$ directed roads, with cities numbered from $1$ to $n$. If one can travel from city $x$ to city $y$ using a series of roads, we say that city $x$ is reachable to city $y$, denoted as $x \\Rightarrow y$. The roads of Country C have a unique property: for any three cities $x$, $y$, $z$, if $x \\Rightarrow z$ and $y \\Rightarrow z$, then $x \\Rightarrow y$ or $y \\Rightarrow x$.\n\nA month from now is the millennium anniversary of Country C's founding, and its citizens are preparing for a grand parade celebration. Currently, Country C has $q$ parade plans, and for the $i$-th plan, the parade hopes to start at city $s_i$ and end at city $t_i$ after passing through several cities. During the parade, **a city can be visited multiple times**. To make the parade more exciting, each parade will **temporarily** construct $k$ ($0 \\leq k \\leq 2$) directed roads specifically for this parade, meaning other parades cannot use the newly built roads.\n\nNow, Country C wants to know how many cities each parade plan could **possibly pass through**.\n\nNote: The temporarily constructed roads **do not need to satisfy the original properties of Country C's roads**.\n\n### Input Format\n\nThe first line contains four integers $n$, $m$, $q$, $k$, representing the number of cities, number of roads, number of parade plans, and the number of temporarily constructed roads per parade, respectively.\n\nThe next $m$ lines each contain two integers $u, v$, representing a directed road $u \\rightarrow v$.\n\nThe next $q$ lines each begin with two integers $s_i, t_i$, representing the starting city and ending city of the parade. These lines also contain $k$ pairs of integers $a, b$, each pair representing a temporarily added directed road $a \\rightarrow b$.\n\nIt is guaranteed that if the original directed roads of Country C are treated as undirected roads, all cities are mutually reachable.\n\n### Output Format\n\nFor each query, output a single integer on a new line representing the answer. If a parade cannot reach the destination from the starting point, output $0$.\n\n### **Sample Explanation #1**\n\nFor the first parade plan, the starting city is city $1$, the ending city is city $4$, and the temporarily constructed road is $5 \\rightarrow 1$. The cities that can possibly be passed are $\\{1, 2, 4, 5\\}$.\n\nFor the second parade plan, the starting city is city $2$, the ending city is city $3$, and the temporarily constructed road is $5 \\rightarrow 3$. The cities that can possibly be passed are $\\{2, 3, 4, 5\\}$.\n\nFor the third parade plan, the starting city is city $1$, the ending city is city $2$, and the temporarily constructed road is $5 \\rightarrow 2$. The cities that can possibly be passed are $\\{1, 2, 4, 5\\}$.\n\nFor the fourth parade plan, the starting city is city $3$, the ending city is city $4$, and the temporarily constructed road is $5 \\rightarrow 1$. Starting from city $3$, it is not possible to reach city $4$.\n\n### **Sample #2**\n\nSee attachments `celebration/celebration2.in` and `celebration/celebration2.ans`.\n\nThis sample corresponds to the constraints of test cases $5 \\sim 7$.\n\n### **Sample #3**\n\nSee attachments `celebration/celebration3.in` and `celebration/celebration3.ans`.\n\nThis sample corresponds to the constraints of test cases $10 \\sim 11$.\n\n### **Sample #4**\n\nSee attachments `celebration/celebration4.in` and `celebration/celebration4.ans`.\n\nThis sample corresponds to the constraints of test cases $15 \\sim 16$.\n\n### **Sample #5**\n\nSee attachments `celebration/celebration5.in` and `celebration/celebration5.ans`.\n\nThis sample corresponds to the constraints of test cases $20 \\sim 25$.\n\n### **Constraints**\n\nFor all test cases, $1 \\leq n, q \\leq 3 \\times {10}^5$, $n - 1 \\leq m \\leq 6 \\times {10}^5$, $0 \\leq k \\leq 2$.\n\n| Test Case ID | $n, q \\leq$ | $k$ | Special Property |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 4$ | $5$ | $= 0$ | None |\n| $5 \\sim 7$ | $1000$ | $\\leq 2$ | None |\n| $8 \\sim 9$ | $3 \\times {10}^5$ | $= 0$ | $m = n - 1$ |\n| $10 \\sim 11$ | $3 \\times {10}^5$ | $= 1$ | $m = n - 1$ |\n| $12 \\sim 14$ | $3 \\times {10}^5$ | $= 2$ | $m = n - 1$ |\n| $15 \\sim 16$ | $3 \\times {10}^5$ | $= 0$ | None |\n| $17 \\sim 19$ | $3 \\times {10}^5$ | $= 1$ | None |\n| $20 \\sim 25$ | $3 \\times {10}^5$ | $= 2$ | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3340, "prompt": "### Problem Description\n**Hint**: At the end of the problem description, we provide a brief, formal description of the task.\n\nIn the distant future, physicists have finally discovered the natural laws of time and causality. Even before someone is born, we can theoretically analyze their life's outcomes. In other words, physics allows us to \"predict\" someone's \"destiny\" to some extent.\n\nSimply put, a person's destiny is a rooted tree $T$ composed of time points: the root node represents birth, and the leaf nodes represent death. Every non-leaf node $u$ has one or more children $v_1, v_2, \\dots, v_{c_u}$, indicating the $c_u$ different choices the person can make at the time point $u$ that lead to different possibilities. Formally, a **choice** is represented by an edge $(u, v_i)$ in the tree, where $u$ is the parent of $v_i$.\n\nA person's lifetime is a path from birth (the root node) to death (a certain leaf node), and this path includes no repeated nodes. Any subpath on the lifetime path that contains at least one edge is considered a segment of the person's **life experience**. The set of all life experiences this person could possibly have, formed by all possible ways they might live, is called **potential life experiences**. In other words, the set of all potential life experiences consists of all paths $(u, v)$ in the tree $T$, where $u \\neq v$ and $u$ is an ancestor of $v$. Mathematically, these potential life experiences are denoted as ordered pairs $(u, v)$, and the set of all such experiences in the tree $T$ is denoted as $\\mathcal{P}_T$.\n\nPhysics not only allows us to observe the tree representing destiny but also lets us analyze whether certain potential life experiences are \"important.\" Every choice someone makes\u2014i.e., every edge in the tree\u2014can be **important** or **not important**. A potential life experience is considered important if and only if there exists at least one edge in its corresponding path that is labeled as important. We can observe that some potential life experiences are important. In other words, we are given a set $\\mathcal{Q} \\subseteq \\mathcal{P}_T$, where each potential life experience $(u, v) \\in \\mathcal{Q}$ is important.\n\nThe structure of the tree $T$ has already been computed, and the set $\\mathcal{Q}$ has been observed. While the uncertainty in someone's destiny has greatly been reduced, it is still significant. Let's compute it: given the tree $T$ and the set $\\mathcal{Q}$, determine how many different ways there are to assign importance to the edges such that all constraints from the observed set $\\mathcal{Q}$ are satisfied. Specifically, for any $(u, v) \\in \\mathcal{Q}$, there must exist at least one edge on the path from $u$ to $v$ that is marked as important.\n\n**Formal Description**: Given a tree $T = (V, E)$ and a point pair set $\\mathcal{Q} \\subseteq V \\times V$, where for all $(u, v) \\in \\mathcal{Q}$, $u \\neq v$, and $u$ is an ancestor of $v$ in tree $T$. $V$ and $E$ denote the sets of nodes and edges in tree $T$, respectively. Compute how many distinct functions $f: E \\rightarrow \\{0, 1\\}$ (assigning each edge $e \\in E$ a value of either $0$ or $1$) there are, satisfying that for any $(u, v) \\in \\mathcal{Q}$, there exists at least one edge $e$ on the path from $u$ to $v$ such that $f(e) = 1$. Since the result may be very large, output the result modulo $998,244,353$ (a prime number).\n\n### Input Format\nRead data from the file `destiny.in`.\n\n- The first line contains a positive integer $n$, indicating the size of the tree $T$. The nodes in the tree are numbered from $1$ to $n$, with node $1$ being the root.\n- The next $n - 1$ lines each contain two space-separated integers $x_i$ and $y_i$ satisfying $1 \\leq x_i, y_i \\leq n$, indicating that there is an edge between nodes $x_i$ and $y_i$. Note that the edges may not be oriented.\n- The next line contains a non-negative integer $m$, indicating the number of observed pieces of information.\n- The next $m$ lines each contain two space-separated integers $u_i$ and $v_i$, indicating $(u_i, v_i) \\in \\mathcal{Q}$. **Note**: the input data may contain duplicates, meaning there may exist $i \\neq j$ such that $u_i = u_j$ and $v_i = v_j$.\n\nThe input size and constraints are summarized in the table at the end of this document.\n\n### Output Format\nWrite the output to the file `destiny.out`.\n\n- Output contains only one integer, representing the number of valid assignments modulo $998,244,353$.\n\n---\n\n### Example 1\nThere are $16$ possible assignments, of which the following $6$ are invalid:\n\n- $(1, 2), (2, 3), (3, 5)$ are marked as not important, while $(3, 4)$ is marked as important: no constraints in $\\mathcal{Q}$ are satisfied.\n- $(1, 2), (2, 3), (3, 4), (3, 5)$ are all marked as not important: no constraints in $\\mathcal{Q}$ are satisfied.\n- $(1, 2), (2, 3)$ are marked as not important, while $(3, 4), (3, 5)$ are marked as important: the constraint $(1, 3)$ in $\\mathcal{Q}$ is not satisfied.\n- $(1, 2), (2, 3), (3, 4)$ are marked as not important, while $(3, 5)$ is marked as important: the constraint $(1, 3)$ in $\\mathcal{Q}$ is not satisfied.\n- $(2, 3), (3, 5)$ are marked as not important, while $(1, 2), (3, 4)$ are marked as important: the constraint $(2, 5)$ in $\\mathcal{Q}$ is not satisfied.\n- $(2, 3), (3, 4), (3, 5)$ are marked as not important, while $(1, 2)$ is marked as important: the constraint $(2, 5)$ in $\\mathcal{Q}$ is not satisfied.\n\nUnder other assignments, all constraints imposed by $\\mathcal{Q}$ are satisfied.\n\n---\n\n### Example 2\nSee the attached files `destiny3.in` and `destiny3.ans`.\n\n---\n\nSee the attached files `destiny4.in` and `destiny4.ans`.\n\n---\n\n### Data Constraints and Hints\n\n| Test Case ID | $n$ | $m$ | $T$ is a complete binary tree |\n| :----------: | :-----------------: | :-----------------: | :---------------------------: |\n| $1$ | $\\leq 10$ | $\\leq 10$ | No |\n| $2$ | $\\leq 10$ | $\\leq 10$ | No |\n| $3$ | $\\leq 10$ | $\\leq 10$ | No |\n| $4$ | $\\leq 10$ | $\\leq 10$ | No |\n| $5$ | $\\leq 500$ | $\\leq 15$ | No |\n| $6$ | $\\leq 10^4$ | $\\leq 10$ | No |\n| $7$ | $\\leq 10^5$ | $\\leq 16$ | No |\n| $8$ | $\\leq 5 \\times 10^5$ | $\\leq 16$ | No |\n| $9$ | $\\leq 10^5$ | $\\leq 22$ | No |\n| $10$ | $\\leq 5 \\times 10^5$ | $\\leq 22$ | No |\n| $11$ | $\\leq 600$ | $\\leq 600$ | No |\n| $12$ | $\\leq 1000$ | $\\leq 1000$ | No |\n| $13$ | $\\leq 2000$ | $\\leq 5 \\times 10^5$ | No |\n| $14$ | $\\leq 2000$ | $\\leq 5 \\times 10^5$ | No |\n| $15$ | $\\leq 5 \\times 10^5$ | $\\leq 2000$ | No |\n| $16$ | $\\leq 5 \\times 10^5$ | $\\leq 2000$ | No |\n| $17$ | $\\leq 10^5$ | $\\leq 10^5$ | Yes |\n| $18$ | $\\leq 10^5$ | $\\leq 10^5$ | Yes |\n| $19$ | $\\leq 5 \\times 10^4$ | $\\leq 10^5$ | No |\n| $20$ | $\\leq 8 \\times 10^4$ | $\\leq 10^5$ | No |\n| $21$ | $\\leq 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $22$ | $\\leq 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $23$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $24$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ | No |\n| $25$ | $\\leq 5 \\times 10^5$ | $\\leq 5 \\times 10^5$ | No |\n\n**All constraints satisfy**: $n \\leq 5 \\times 10^5$, $m \\leq 5 \\times 10^5$. The input forms a valid tree, and for $1 \\leq i \\leq m$, it is always true that $u_i$ is an ancestor of $v_i$.\n\n**Complete Binary Tree**: In this problem, a complete binary tree is defined as a tree where each non-leaf node has left and right children, and all leaf nodes have the same depth. A tree constructed by numbering the nodes of a full binary tree in top-to-bottom, left-to-right order, and taking the smallest numbered nodes forms a complete binary tree.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2604, "prompt": "### Problem Description\nA and B have decided to travel during their vacation. The cities they want to visit are numbered from $1$ to $N$, where cities with smaller numbers are located west of cities with larger numbers. The altitude of each city is unique, and the altitude of city $i$ is denoted as $H_i$. The distance $d_{i, j}$ between two cities $i$ and $j$ is the absolute difference of their altitudes, i.e., $d_{i, j} = |H_i - H_j|$.\n\nDuring their trip, A and B take turns driving. A drives on the first day, then they alternate each subsequent day. They decide to start their journey from a city $S$ and always head east, traveling at most $X$ kilometers before ending the trip. A and B have different driving styles: B always chooses the nearest city (in terms of distance) in the forward direction as their destination, while A chooses the second nearest city (also in the forward direction) as their destination. **Note:** If two cities are at the same distance from the current city, the city with the lower altitude is considered closer. If either person cannot choose a destination according to their principles, or reaching their chosen destination would exceed the maximum distance $X$, they end the trip. \n\nBefore departing, A wants to know the answers to two questions:\n\n1. For a given $X = X_0$, which city should they start from to minimize the ratio of total distance traveled by A to the total distance traveled by B (if B's total distance is $0$, the ratio is considered infinite, and two infinite values are regarded as equal)? If multiple starting cities result in the same minimum ratio, output the city with the highest altitude.\n2. For any given $X = X_i$ and starting city $S_i$, calculate the total distances traveled by A and B.\n\n---\n\n### Input Format\n\n- The first line contains an integer $N$, denoting the number of cities.\n- The second line contains $N$ integers separated by spaces, representing the altitudes of cities $1$ to $N$, i.e., $H_1, H_2, \\dots, H_N$, where each $H_i$ is unique.\n- The third line contains an integer $X_0$.\n- The fourth line contains an integer $M$, denoting the number of queries regarding $S_i$ and $X_i$.\n- The next $M$ lines each contain two integers $S_i$ and $X_i$, representing the starting city $S_i$ and the maximum distance $X_i$.\n\n---\n\n### Output Format\n\n- The first line contains an integer $S_0$, representing the city index where the ratio of distances traveled by A to B is minimized for $X_0$. If multiple cities lead to the same minimum ratio, choose the city with the highest altitude.\n- The next $M$ lines each contain two integers separated by a space, representing the total distance traveled by A and the total distance traveled by B for the given $S_i$ and $X_i$.\n\n---\n\n### Example 1\n![drive.png](https://img.loj.ac.cn/2021/12/29/5417cef0899f3.png)\n\nThe altitude and distances between cities are as shown in the figure above.\n\n- If starting from city $1$, the reachable cities are $2$, $3$, and $4$, with distances $1$, $1$, and $2$, respectively. Since city $3$ has a lower altitude than city $2$, city $3$ is considered closer to city $1$, and city $2$ is considered the second closest, so A travels to city $2$. From city $2$, the reachable cities are $3$ and $4$, with distances $2$ and $1$, respectively, so B travels to city $4$. From city $4$, no further cities can be reached, and the trip ends.\n- If starting from city $2$, the reachable cities are $3$ and $4$, with distances $2$ and $1$, respectively. Since city $3$ is the second closest, A travels to city $3$. From city $3$, the only remaining city is $4$, but traveling to city $4 would result in a total distance of $2+3=5 > X_0=3$, so B ends the trip at city $3$.\n- If starting from city $3$, the only reachable city is $4$, but since no city is considered second closest to city $3$, the trip ends before it begins.\n- If starting from city $4$, no cities can be reached, and the trip ends before it begins.\n\n---\n\n### Example 2\nWhen $X = 7$:\n- Starting from city $1$, the route is $1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 8 \\rightarrow 9$. A travels a distance of $1 + 2 = 3$, while B travels a distance of $1 + 1 = 2$ (at city $1$, A first chooses city $2 over city $6 since city $2$ has a higher altitude; at city $9$, A cannot make a second choice, ending the trip).\n- Starting from city $2$, the route is $2 \\rightarrow 6 \\rightarrow 7$. A and B travel distances of $2$ and $4$, respectively.\n- Starting from city $3$, the route is $3 \\rightarrow 8 \\rightarrow 9$. A and B travel distances of $2$ and $1$, respectively.\n- Starting from city $4$, the route is $4 \\rightarrow 6 \\rightarrow 7$. A and B travel distances of $2$ and $4$, respectively.\n- Starting from city $5$, the route is $5 \\rightarrow 7 \\rightarrow 8$. A and B travel distances of $5$ and $1$, respectively.\n- Starting from city $6$, the route is $6 \\rightarrow 8 \\rightarrow 9$. A and B travel distances of $5$ and $1$, respectively.\n- Starting from city $7$, the route is $7 \\rightarrow 9 \\rightarrow 10$. A and B travel distances of $2$ and $1$, respectively.\n- Starting from city $8$, the route is $8 \\rightarrow 10$. A and B travel distances of $2$ and $0$, respectively.\n- Starting from city $9$, the route is just $9$. A and B travel distances of $0$ and $0`, respectively (the trip ends before it starts).\n- Starting from city $10$, the route is just $10`. A and B travel distances of $0` and $0`, respectively.\n\nStarting from cities $2$ or $4$, the ratio of A's total distance to B's total distance is minimized. Since city $2$ has a higher altitude, the output for the first line is `2`.\n\n---\n\n### Constraints and Hints\n\n- For 30% of the data: $1 \\leq N \\leq 20$, $1 \\leq M \\leq 20$\n- For 40% of the data: $1 \\leq N \\leq 100$, $1 \\leq M \\leq 100$\n- For 50% of the data: $1 \\leq N \\leq 100$, $1 \\leq M \\leq 1,000$\n- For 70% of the data: $1 \\leq N \\leq 1,000$, $1 \\leq M \\leq 10,000$\n- For 100% of the data: $1 \\leq N \\leq 100,000$, $1 \\leq M \\leq 10,000$, $|H_i| \\leq 10^9$, $0 \\leq X_i \\leq 10^9$ for all $i \\geq 0$, $1 \\leq S_i \\leq N$ for all $i \\geq 1$. It is guaranteed that all $H_i$ are unique.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2498, "prompt": "## Problem Description\n\nRock-Paper-Scissors is a common hand game: rock beats scissors, scissors beats paper, and paper beats rock. If both players use the same gesture, the game ends in a draw. In Season 2, Episode $8$ of *The Big Bang Theory*, an enhanced version of Rock-Paper-Scissors was introduced.\n\nThe enhanced version extends the traditional game by adding two new gestures:\n\n- **Spock**: A character from *Star Trek*. \n- **Lizard**: A villain from *Star Trek*.\n\nThe winning relationships among the five gestures are shown in Table 1, which describes the result of Player A versus Player B.\n\n| A \\ B | Scissors | Rock | Paper | Lizard | Spock |\n|:--------:|:--------:|:-----:|:-----:|:------:|:------:|\n| Scissors | Draw | Lose | Win | Win | Lose |\n| Rock | - | Draw | Lose | Win | Lose |\n| Paper | - | - | Draw | Lose | Win |\n| Lizard | - | - | - | Draw | Win |\n| Spock | - | - | - | - | Draw |\n\nNow, Player A and Player B want to try this enhanced version of the hand game. It is known that both players play according to a periodic pattern, but the cycle lengths of their patterns may differ. For example, if Player A plays with a period of length $6$ as \"Rock - Paper - Rock - Scissors - Lizard - Spock\", Player A's play sequence would be \"Rock - Paper - Rock - Scissors - Lizard - Spock - Rock - Paper - Rock - Scissors - Lizard - Spock - ...\". If Player B plays with a period of length $5$ as \"Scissors - Rock - Paper - Spock - Lizard\", Player B's play sequence would be \"Scissors - Rock - Paper - Spock - Lizard - Scissors - Rock - Paper - Spock - Lizard - ...\".\n\nGiven that Player A and Player B play against each other $N$ times, the winner of each match earns $1$ point, while the loser earns $0$ points. If the match is a draw, neither player earns any points. Your task is to compute the scores of Player A and Player B after $N$ matches.\n\n---\n\n## Input Format\n\nThe first line contains three integers: $N, N_A, N_B$, which represent the total number of matches ($N$), the length of Player A's gesture cycle ($N_A$), and the length of Player B's gesture cycle ($N_B$). The numbers are separated by a single space.\n\nThe second line contains $N_A$ integers, representing the periodic pattern of Player A's gestures. \nThe third line contains $N_B$ integers, representing the periodic pattern of Player B's gestures. \n\nIn both sequences: \n- $0$ represents \"Scissors\", \n- $1$ represents \"Rock\", \n- $2$ represents \"Paper\", \n- $3$ represents \"Lizard\", \n- $4$ represents \"Spock\". \n\nThe numbers are separated by a single space.\n\n---\n\n## Output Format\n\nOutput a single line containing two integers, separated by a single space, representing the scores of Player A and Player B, respectively.\n\n---\n\n## Sample Input 1\n\n```plaintext\n10 3 2\n0 1 2\n3 4\n```## Sample Output 1\n\n```plaintext\n7 3\n```\n\n---\n\n## Sample Input 2\n\n```plaintext\n6 6 6\n0 1 2 3 4 0\n0 1 2 3 4 0\n```\n\n## Sample Output 2\n\n```plaintext\n0 0\n```\n\n---\n\n## Constraints and Notes\n\n- $0 < N \\leq 200$ \n- $0 < N_A \\leq 200$ \n- $0 < N_B \\leq 200$ \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2359, "prompt": "### Problem Description\n\nLittle C finds running very interesting, so he decided to create a game called *\"Run & Fun Everyday\"*. *\"Run & Fun Everyday\"* is a simulation game where players need to log in every day and complete check-in tasks.\n\nThe game map can be represented as a tree with $n$ nodes and $n - 1$ edges. Each edge connects two nodes on the tree, and any two nodes are connected by a unique path. The nodes of the tree are numbered from $1$ to $n$ as consecutive positive integers.\n\nThere are $m$ players, and the $i$-th player's starting point is $S_i$, and their destination is $T_i$. At the start of the daily check-in task at second $0$, all players simultaneously start from their starting points and move at a speed of one edge per second along the shortest path toward their respective destinations. Once a player reaches their destination, the player completes the check-in task. (Since the map is a tree, each player's path is unique.)\n\nLittle C wants to measure the game's activity level by placing an observer at each node. The observer at node $j$ will observe players at the $W_j$ second. A player can be observed by the observer at node $j$ if and only if the player is at node $j$ exactly at the $W_j$ second. Little C wants to know how many players each observer will observe.\n\n**Note:** A player is considered to have finished the game once they reach their destination, and they cannot wait at their destination to be observed. That is, for a player with node $j$ as their destination:\n- If the player arrives at their destination before the $W_j$ second, the observer at node $j$ cannot observe this player.\n- If the player arrives at their destination exactly at the $W_j$ second, the observer at node $j$ can observe this player.\n\n---\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, where $n$ represents the number of nodes in the tree (and also the number of observers), and $m$ represents the number of players.\n\nThe next $n - 1$ lines each contain two integers $u$ and $v$, indicating that there is an edge between node $u$ and node $v$.\n\nThe next line contains $n$ integers, where the $i$-th integer is $W_i$, representing the observation time for the observer at node $i$.\n\nThe following $m$ lines each contain two integers $S_i$ and $T_i$, representing the starting point and destination of a player.\n\nIt is guaranteed that $1 \\leq S_i, T_i \\leq n, 0 \\leq W_j \\leq n$ for all input data.\n\n---\n\n### Output Format\n\nOutput a single line with $n$ integers, where the $j$-th integer represents the number of players the observer at node $j$ can observe.\n\n---\n\n### Sample Input 1\n\n```\n6 3\n1 2\n1 3\n1 4\n4 5\n4 6\n0 2 5 4 4 6\n1 4\n5 1\n6 6\n```### Sample Output 1\n\n```\n2 0 0 1 1 1\n```\n\n**Explanation:**\n\n- For node $1$, $W_1 = 0$. Only players who start at node $1$ can be observed by the observer. Players $1$ and $2$ are observed, so a total of $2$ players are observed.\n- For node $2$, no player is at this node at the $2$-second mark, so $0$ players are observed.\n- For node $3$, no player is at this node at the $5$-second mark, so $0$ players are observed.\n- For node $4$, player $1$ is observed, so $1$ player is observed in total.\n- For node $5$, player $1$ is observed, so $1$ player is observed in total.\n- For node $6$, player $3$ is observed, so $1$ player is observed in total.\n\n---\n\n### Sample Input 2\n\n```\n5 5\n1 2\n2 3\n3 4\n4 5\n0 1 2 3 4\n1 1\n2 2\n3 3\n4 4\n5 5\n```\n\n### Sample Output 2\n\n```\n1 1 1 1 1\n```\n\n---\n\n### Constraints and Hints\n\n- **Test Case $1 \\sim 2$:** $n = m = 991$. All players start at their own destinations, i.e., $S_i = T_i$.\n- **Test Case $3 \\sim 4$:** $n = m = 992$, and $W_j = 0$ for all $j$.\n- **Test Case $5$:** $n = m = 993$.\n- **Test Case $6 \\sim 8$:** $n = m = 99994$, and the tree degenerates into a straight line. For $1 \\leq i < n$, there is an edge between $i$ and $i + 1$.\n- **Test Case $9 \\sim 12$:** $n = m = 99995$, with $S_i = 1$ for all players.\n- **Test Case $13 \\sim 16$:** $n = m = 99996$, with $T_i = 1$ for all players.\n- **Test Case $17 \\sim 19$:** $n = m = 99997$.\n- **Test Case $20$:** $n = m = 299998$.\n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2134, "prompt": "### Problem Description\n\nThe gardener Mr. S is in charge of a field, which can be seen as a two-dimensional plane. There are $n$ wishing trees in the field, numbered as $1, 2, 3, \\ldots, n$. Each tree can be treated as a point in the plane, and the $i$-th tree ($1 \\leq i \\leq n$) is located at coordinates $(x_i, y_i)$. The coordinates of any two trees are distinct.\n\nVeteran driver Mr. P will set off from the origin $(0, 0)$ and perform several rounds of actions. In each round, Mr. P first chooses a direction that satisfies the following conditions:\n\n1. The direction is one of the following five options: left, right, up, 45\u00b0 up-left, or 45\u00b0 up-right.\n2. Moving along this direction allows him to reach a tree that he has not yet made a wish at.\n\nAfter choosing a direction, Mr. P will move along this direction in a straight line and must reach the nearest tree in this direction that he has not wished at. He will make a wish under this tree and move on to the next round. If no valid direction is available, he stops. He will adopt an optimal strategy to make wishes at as many trees as possible. If there are multiple optimal strategies, he can choose any one of them.\n\nUnfortunately, the gardener Mr. S finds that because the soil in the field is soft, Mr. P's car leaves wheel tracks on the field during each round of driving. A wheel track can be treated as a line segment with endpoints at two trees (or the origin and one tree).\n\nIn the future, many other wishing visitors plan to drive to the field to make wishes. These visitors will follow the same type of optimal strategy as Mr. P. Mr. S finds the wheel tracks in non-horizontal directions (i.e., up, 45\u00b0 up-left, 45\u00b0 up-right) visually unappealing. To maintain the appearance of the field, he plans to rent some rollers to flatten all ground that might leave \"non-horizontal wheel tracks\" before these visitors arrive.\n\nThe \"ground that might leave non-horizontal wheel tracks\" refers to some line segments in the field, each of which is included in the travel routes under certain optimal strategies. Each roller operates under the following conditions:\n\n1. It starts from the origin or any tree.\n2. It can only move in one of the following three directions: up, 45\u00b0 up-left, or 45\u00b0 up-right, and can only change direction or stop under a tree.\n3. It can only traverse the ground that might leave \"non-horizontal wheel tracks,\" but the same piece of ground can be traversed by multiple rollers.\n\nNow, Mr. P and Mr. S each have a question for you:\n\n1. For Mr. P, please provide any one optimal route.\n2. For Mr. S, tell him the minimum number of rollers he needs to rent.\n\n---\n\n### Input Format\n\nThe first line of the input file contains a positive integer $n$, representing the number of wishing trees. \nThe following $n$ lines each contain two integers $x_i$ and $y_i$, separated by a single space, representing the coordinates of the $i$-th wishing tree.\n\n---\n\n### Output Format\n\nThe output file consists of three lines: \n\nThe first line contains a single integer $m$, representing the maximum number of trees at which Mr. P can make wishes. \nThe second line contains $m$ integers separated by single spaces, representing the order in which Mr. P should make wishes at the trees. \nThe third line contains a single integer, representing the minimum number of rollers Mr. S needs to rent.\n\n---\n\n### Sample\n\nOptimal paths allow making wishes at three trees: \n$(0,0) \\rightarrow (1,1) \\rightarrow (-1,1) \\rightarrow (-2,2)$ or $(0,0) \\rightarrow (0,8) \\rightarrow (0,9) \\rightarrow (0,10)$.\n\nAt least three rollers are needed: \nRoutes are $(0,0) \\rightarrow (1,1)$, $(-1,1) \\rightarrow (-2,2)$, and $(0,0) \\rightarrow (0,8) \\rightarrow (0,9) \\rightarrow (0,10)$.\n\n---\n\n### Constraints and Hints\n\nFor all test cases, $n \\leq 50000$, $|x_i| \\leq 10^9$, $0 < y_i \\leq 10^9$.\n\nFor each test case:\n\n- If the output of the first line is correct, you will receive $20\\%$ of the points for that test case.\n- If the output of the second line is also correct, you will receive an additional $20\\%$ of the points.\n- If the third line is correct, you will receive the remaining $60\\%$ of the points.\n\nIt should be noted that **even if your program can only earn partial points, you must strictly follow the output format**; otherwise, your program will be judged as scoring $0$ points. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3898, "prompt": "### Problem Description\n\nCountry A and Country B are engaged in an intense war. Country A plans to build several military camps within its territory.\n\nThe territory of Country A consists of $n$ cities connected by $m$ bidirectional roads, such that **any two cities are directly or indirectly reachable** via these roads. Country A plans to select one or more cities (**at least one**) and construct a military camp in each selected city.\n\nIt is well known that communication between military camps is extremely important. However, Country A has received intelligence that Country B will soon attack one of Country A's roads, though the exact target is unknown. If Country B's attack succeeds, this road will be cut off, possibly causing two military camps in Country A to be unable to reach each other, which Country A must avoid at all costs. Therefore, Country A has decided to deploy troops to guard some roads (**one, more than one, or even none**). Country A is confident that the guarded roads will resist any attack from Country B and will not be cut off.\n\nCountry A hopes to devise a plan for constructing military camps and guarding roads such that no matter which road Country B attacks, it will not lead to any two military camps being unable to communicate with each other. Please help Country A calculate the number of such possible plans for constructing military camps and guarding roads. Since the number of plans can be very large, you only need to output the result modulo $1,000,000,007\\left(10^{9} + 7\\right)$. Two plans are considered different if and only if there exists at least one city where a military camp is built in one plan and not in the other, or at least one road where troops are deployed in one plan but not in the other.\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of cities and bidirectional roads.\n\nThe next $m$ lines each contain two positive integers $u_{i}$ and $v_{i}$, describing a bidirectional road connecting $u_{i}$ and $v_{i}$. It is guaranteed that there are no duplicate roads or self-loops.\n\n### Output Format\n\nOutput a single integer, which is the number of plans to construct military camps and guard roads, modulo $1,000,000,007\\left(10^{9} + 7\\right)$.\n\n### Sample Explanation\n\nCountry A has two cities connected by one road. All possible plans are as follows:\n\n- Build a military camp in city $1$, do not guard the road;\n- Build a military camp in city $1$, guard the road;\n- Build a military camp in city $2$, do not guard the road;\n- Build a military camp in city $2$, guard the road;\n- Build military camps in both cities $1$ and $2$, guard the road.\n\n### Constraints\n\nFor all test cases, it is guaranteed that $1 \\leq n \\leq 5 \\times 10^5$, $n - 1 \\leq m \\leq 10^6$, and $1 \\leq u_i, v_i \\leq n$, $u_i \\neq v_i$.\n\nThe details of the test cases' constraints are as follows:\n\n| Test Case ID | $n \\leq$ | $m \\leq$ | Special Condition |\n|:------------:|:--------:|:--------:|:-----------------:|\n| $1 \\sim 3$ | $8$ | $10$ | None |\n| $4 \\sim 7$ | $16$ | $25$ | None |\n| $8 \\sim 9$ | $3000$ | $5000$ | None |\n| $10 \\sim 11$ | $5 \\times 10^5$ | $10^6$ | Special Property $\\mathrm{A}$ |\n| $12 \\sim 14$ | $5 \\times 10^5$ | $10^6$ | $m = n - 1$ |\n| $15 \\sim 16$ | $5 \\times 10^5$ | $10^6$ | $m = n$ |\n| $17 \\sim 20$ | $5 \\times 10^5$ | $10^6$ | None |\n\nSpecial Property $\\mathrm{A}$: It is guaranteed that $m = n - 1$ and the $i$-th road connects city $i$ and city $i+1$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3762, "prompt": "### Problem Description\n\nIn 2010, the World Expo was held in Shanghai, China, attracting tens of millions of domestic and international visitors. During the summer holiday, little Z also visited the Shanghai Expo Park. She had heard of its crowdedness and was well-prepared for situations where it would take hours to queue for some pavilions. To make her Expo trip smoother and more enjoyable, she decided to plan a detailed travel route beforehand.\n\nLittle Z collected a map of the Expo Park and found that, overall, the park was a very narrow rectangular area, with each pavilion occupying a square of roughly the same size. Thus, the entire park can be viewed as a $n \\times m$ matrix ($n \\leq 3$), where each cell represents a themed pavilion.\n\nSince different pavilions vary in popularity, the queuing time differs accordingly. Based on statistical information, little Z marked each pavilion $(x, y)$ with $T_{x,y} = 0$ or $1$: if $T_{x,y} = 1$, the pavilion is highly popular and requires a long time to queue; if $T_{x,y} = 0$, the pavilion is relatively normal and requires little to no queuing. Little Z wants to plan a reasonable route that alternates between popular pavilions and ordinary ones, avoiding long queues caused by continuous visits to popular pavilions and preventing the trip from becoming monotonous by visiting only ordinary ones. Moreover, little Z is efficient and hopes to visit all pavilions without retracing her steps or wasting energy. Therefore, she wants her travel route to meet the following constraints:\n\n1. After visiting the pavilion at $(x, y)$, the next pavilion visited must be an unvisited adjacent pavilion $(x^\\prime, y^\\prime)$ such that $|x-x^\\prime|+|y-y^\\prime|=1$;\n2. The starting point of the route must lie on the boundary of the matrix, i.e., $x = 1$ or $x = n$ or $y = 1$ or $y = m$;\n\nShe has planned a 01 sequence $L$ of length $n \\times m$, where the pavilion $(x,y)$ visited at step $i$ must satisfy $T_{x,y}=L_i$.\n\nLittle Z wants to know how many different travel routes meet her requirements. Since the total number of feasible routes might be large, she only wants to know the count modulo $11,192,869$.\n\n### Input Format\n\nThe first line contains two positive integers $n, m$.\n\nThe next $n$ lines contain $m$ 01 integers each, where the $i$-th row and $j$-th column represents $T_{i,j}$.\n\nThe $(n+2)$-th line contains $n \\times m$ 01 integers, where the $i$-th number represents the value of $L_i$.\n\n### Output Format\n\nOutput a single integer, representing the total number of feasible travel routes modulo $11,192,869$.\n\n### Example\n\nThere are four feasible travel routes:\n\n$$\n\\begin{aligned}\n(1,1) \\to (1,2) \\to (2,2) \\to (2,1)\\\\\n(1,1) \\to (2,1) \\to (2,2) \\to (1,2)\\\\\n(2,2) \\to (1,2) \\to (1,1) \\to (2,1)\\\\\n(2,2) \\to (2,1) \\to (1,1) \\to (1,2)\n\\end{aligned}\n$$\n\n### Constraints and Hints\n\n- For $10\\%$ of the cases: $n=1$;\n- For $30\\%$ of the cases: $n=2$;\n- For $60\\%$ of the cases: $n=3$ and $20\\%$ of the cases have $T_{i,j}$ all equal to $0$;\n- For $100\\%$ of the cases: $m \\leq 50$, $L_i, T_{i,j} = 0$ or $1$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2607, "prompt": "### Problem Description\n\nCountry H has $n$ cities. These $n$ cities are connected by $n-1$ bidirectional roads, forming a tree structure. City $1$ is the capital of the country and also serves as the root node of the tree.\n\nA highly dangerous infectious disease outbreak has occurred in the capital. To control the epidemic and prevent it from spreading to the border cities (the cities represented by the leaf nodes), the authorities have decided to deploy the army to establish checkpoints in certain cities. Checkpoints must be placed such that every path from the capital to a border city goes through at least one checkpoint. Note that border cities are also allowed to have checkpoints, but the capital cannot have a checkpoint.\n\nIn certain cities of Country H, there are already some troops stationed, and a city may have multiple troops. Each troop can move freely between connected cities via the roads and establish a checkpoint in any city except the capital. A troop can only establish a checkpoint in one city. The time required for a troop to move from one city to another is equal to the length of the connecting road (in hours).\n\nYour task is to determine the minimum time (in hours) required to control the epidemic. Note that multiple troops can move simultaneously.\n\n### Input Format\n\nThe input consists of multiple lines:\n\n- The first line contains an integer $n$, representing the number of cities.\n- The next $n-1$ lines each contain three integers $u$, $v$, and $w$, separated by spaces, where $u$ and $v$ are the indices of two cities connected by a road of length $w$. The input guarantees that the given structure forms a tree and that City $1$ is the root node.\n- The following line contains an integer $m$, representing the number of troops.\n- The next line contains $m$ integers, separated by spaces, indicating the city indices where the $m$ troops are stationed.\n\n### Output Format\n\nOutput a single integer, representing the minimum time required to control the epidemic. If it is impossible to control the epidemic, output $-1$.\n\n### Sample Explanation\n\nThe first troop establishes a checkpoint at City $2$, while the second troop moves from City $2$ to City $3$ to establish a checkpoint. The total time required is $3$ hours.\n\n### Constraints and Hints\n\n**It is guaranteed that troops are not stationed in the capital.**\n\n- For $10\\%$ of the test cases, $n \\leq 10$.\n- For $20\\%$ of the test cases, $n \\leq 50$, $w < 10^5$.\n- For $30\\%$ of the test cases, $n \\leq 1,000$, $w < 10^6$.\n- For $40\\%$ of the test cases, $n \\leq 10,000$.\n- For $50\\%$ of the test cases, $n \\leq 50,000$.\n- **For $80\\%$ of the test cases, $n \\leq 100,000$.**\n\n- **For $100\\%$ of the test cases, $2 \\leq m \\leq n \\leq 300,000$, and $0 < w < 10^9$.**\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3159, "prompt": "### Problem Description\n\nThere are $n$ cities in the Kingdom of Fleas, numbered $1$ through $n$, with City $1$ being the capital. All cities are distributed within a $w \\times h$ grid. Each city has a unique integer coordinate $(x, y)$ such that $1 \\leq x \\leq w$ and $1 \\leq y \\leq h$. The coordinates of different cities are unique.\n\nThe Kingdom has $m$ jumping devices, numbered $1$ through $m$. The $i$-th jumping device is located in City $p_i$ and has parameters $t_i, L_i, R_i, D_i, U_i$. Using this jumping device, a flea can spend $t_i\\ (t_i > 0)$ units of time to jump from City $p_i$ to any city within the rectangular region where $L_i \\leq x \\leq R_i$ and $D_i \\leq y \\leq U_i\\ (1 \\leq L_i \\leq R_i \\leq w, 1 \\leq D_i \\leq U_i \\leq h)$. Note that a city may have multiple jumping devices or may not have any jumping devices at all.\n\nSince the distance between cities is large, fleas must rely on jumping devices for their travel. Specifically, a single trip involves passing through several cities, with the sequence of visited city numbers represented by $a_0, a_1, \\ldots, a_k$. The sequence of used jumping devices during the trip is represented by $b_1, b_2, \\ldots, b_k$. In this trip:\n\n- Each city may occur multiple times in the sequence $\\{a_j\\}$.\n- Each jumping device may occur multiple times in the sequence $\\{b_j\\}$.\n- For each $j \\ (1 \\leq j \\leq k)$, the jumping device $b_j$ is located in City $a_{j-1}$, and the flea can use this jumping device to jump to City $a_j$.\n\nThis is referred to as a trip from city $a_0$ to city $a_k$, involving $k$ jumps and costing a total of $\\sum_{i=1}^k t_{b_i}$ units of time.\n\nThe King of Fleas wants to know the minimum time needed to travel from the capital (City $1$) to each of the other cities in the kingdom. The king guarantees that for every city, there is at least one valid trip from the capital to that city.\n\n---\n\n### Input Format\n\nInput is read from the file `jump.in`.\n\nThe first line contains four integers $n, m, w, h$, whose meanings are explained in the problem description.\n\nThe next $n$ lines each contain two integers $x_i, y_i$, representing the coordinates of City $i$.\n\nThe next $m$ lines each contain six integers $p_i, t_i, L_i, R_i, D_i, U_i$, which represent the city where the $i$-th jumping device is located, the time required for the jump, and the rectangular region reachable by this device, respectively. These integers are explained in detail in the problem description.\n\n---\n\n### Output Format\n\nOutput to the file `jump.out`.\n\nThe output should contain $n - 1$ lines. Each line $i$ should consist of a single integer, representing the minimum time required to travel from the capital to City $i+1$.\n\n---\n\n### Example\n\nRefer to the attached files `jump/jump2.in` and `jump/jump2.ans`.\n\nIn this example, the data constraints are $n = 10^4, m = 2\\times 10^4, w = 10^4, h = 1$.\n\nRefer to the attached files `jump/jump3.in` and `jump/jump3.ans`.\n\nIn this example, the data constraints are $n = 10^4, m = 2\\times 10^4, w = 10^4, h = 10^4$.\n\n---\n\n### Constraints and Hints\n\nFor all test points and examples, the constraints satisfy:\n- $1 \\leq n \\leq 7\\times 10^4$\n- $1 \\leq m \\leq 1.5\\times 10^5$\n- $1 \\leq w, h \\leq n$\n- $1 \\leq t_i \\leq 10^4$\n\nDetailed restrictions for each test point are provided in the table below:\n\n| Test Point Number | $1\\leq n\\leq$ | $1\\leq m\\leq$ | Special Restrictions |\n| :---------------: | :--------------------------: | :------------------: | :----------------------------------------------------------------: |\n| $1\\sim 8$ | $100$ | $100$ | None |\n| $9\\sim 13$ | $5\\times 10^4$ | $10^5$ | Each jumping device can reach exactly one city, with $L_i = R_i, D_i = U_i$ |\n| $14\\sim 18$ | $5\\times 10^4$ | $10^5$ | $h=1$ |\n| $19\\sim 22$ | $2.5\\times 10^4$ | $5\\times 10^4$ | None |\n| $23\\sim 25$ | $7\\times 10^4$ | $1.5\\times 10^5$ | None |\n\n**Note: The memory limit for this problem is 128MB.**\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3388, "prompt": "### Problem Description\n\nLittle C is playing a ball-moving game. In front of him, there are $n + 1$ rods numbered from $1$ to $n + 1$. Rods $1$, $2$, ..., $n$ each have $m$ balls on them, stacked from bottom to top. Rod $n + 1$ initially has no balls. These $n \\times m$ balls come in $n$ different colors, with $m$ balls of each color.\n\nInitially, the balls on a rod may be of various colors. Little C's task is to move the balls such that all balls of the same color are grouped onto the same rod. This is the only goal, and there is no restriction on which rod each color ends up on.\n\nLittle C can achieve the goal using several operations. In one operation, he can move one ball from the top of one rod to the top of another rod. More specifically, to move a ball from rod $x$ to rod $y$, the following conditions must be met:\n\n1. Rod $x$ has at least one ball.\n2. Rod $y$ has at most $m - 1$ balls.\n3. Only the topmost ball of rod $x$ can be moved, and it must be placed on top of rod $y$.\n\nThe task itself is not very difficult to accomplish, but Little C has decided to challenge himself: in addition to achieving the objective, the total number of operations must not exceed $820,000$. In other words, Little C needs to achieve the goal in at most $820,000$ operations.\n\nLittle C is stuck with this problem, but he believes you are capable of solving it. Please provide an operation plan to achieve Little C's goal. There may be multiple valid solutions; you only need to provide one. It is guaranteed that at least one valid solution exists.\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, separated by a space, representing the number of ball colors and the number of balls of each color, respectively.\n\nThe next $n$ lines each contain $m$ integers separated by a single space. The integers on the $i$-th line, given in order from bottom to top, represent the colors of the balls on rod $i$.\n\n### Output Format\n\nThis problem uses a custom validator (special judge) for evaluation. \n\nThe first line of your output should contain a single integer $k$, representing the number of operations in your solution. You must ensure $0 \\le k \\le 820000$. \n\nThe next $k$ lines should each contain two integers $x$ and $y$, separated by a single space, indicating an operation where the topmost ball of rod $x$ is moved to the top of rod $y$. You must ensure $1 \\le x, y \\le n + 1$ and $x \\ne y$.\n\n**Example Explanation of Sample #1**\n\nThe contents of the rods are shown as follows, with balls listed from bottom to top:\n\n| Operation | Rod 1 | Rod 2 | Rod 3 |\n|:---------:|:-------------:|:-------------:|:-------------:|\n| Initial | $1\\ 1\\ 2$ | $2\\ 1\\ 2$ | |\n| $1\\ 3$ | $1\\ 1$ | $2\\ 1\\ 2$ | $2$ |\n| $2\\ 3$ | $1\\ 1$ | $2\\ 1$ | $2\\ 2$ |\n| $2\\ 3$ | $1\\ 1$ | $2$ | $2\\ 2\\ 1$ |\n| $3\\ 1$ | $1\\ 1\\ 1$ | $2$ | $2\\ 2$ |\n| $3\\ 2$ | $1\\ 1\\ 1$ | $2\\ 2$ | $2$ |\n| $3\\ 2$ | $1\\ 1\\ 1$ | $2\\ 2\\ 2$ | |\n\n### Constraints\n\n| Test Case | $n \\le$ | $m \\le$ |\n|:---------:|:-------:|:-------:|\n| $1 \\sim 2$| $2$ | $20$ |\n| $3 \\sim 5$| $10$ | $20$ |\n| $6 \\sim 8$| $50$ | $85$ |\n| $9 \\sim 14$| $50$ | $300$ |\n| $15 \\sim 20$| $50$ | $400$ |\n\nFor all test cases, it is guaranteed that $2 \\le n \\le 50$ and $2 \\le m \\le 400$.\n\n### Validator\n\nTo facilitate testing, a `checker.cpp` file is provided in the `ball` directory. You can compile this program and use it to validate your output file. Note that the checker used for local testing is not completely identical to the final evaluation checker. You also do not need to concern yourself with its code implementation.\n\nThe compilation command is: `g++ checker.cpp -o checker -std=c++11`.\n\nThe usage of the `checker` program is: `checker `. The arguments represent the input file and your output file, respectively.\n\nIf your output contains invalid numbers, the validator will give an appropriate error message. If your numbers are within valid ranges but your solution is incorrect, the validator will provide brief error information:\n\n1. `A x`, indicating that the $x$-th operation is invalid.\n2. `B x`, indicating that, after all operations, the balls on rod $x$ are not grouped correctly.\n\nIf your solution is correct, the validator will output `OK`.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2244, "prompt": "### Problem Description\n\nIn the 21st century, many people have developed a strange disorder called \"Getting Out of Bed Difficulty Syndrome.\" Its clinical manifestations include difficulty in getting out of bed and low energy after waking up. As a young and vibrant individual, atm has always been determined to fight against this syndrome. Through studying related literature, he has found the root cause of the disease: in the deep depths of the Pacific Ocean, there is a dragon named `drd` that holds the essence of sleep, allowing it to extend people's sleep indefinitely. It is because of `drd`'s actions that the syndrome has been intensifying and rapidly spreading across the world. To completely eliminate this disease, atm has decided to go underwater to defeat this dragon.\n\nAfter overcoming many challenges, atm finally arrived at the location of `drd` and is preparing for a difficult and arduous battle. The dragon `drd` possesses an extraordinary ability: its defensive mechanism can alter the damage it receives using certain operations. Specifically, the defensive mechanism of `drd` consists of **$n$ defense gates**. Each defense gate has an operation $\\mathrm{op}$ and a parameter $t$. The operation is guaranteed to be one of **OR**, **XOR**, or **AND**, and the parameter is a non-negative integer. If atm's attack power before passing through the gate is $x$, his attack power will become $x \\mathbin{\\mathrm{op}} t$ after passing through the gate. The total damage that `drd` receives is the attack power obtained by atm's initial attack power **after passing sequentially through all $n$ defense gates**.\n\nSince atm's abilities are limited, his initial attack power must be an integer between $0$ and $m$ inclusive (i.e., it must be one of $0, 1, \\dots, m$, though the attack power after passing the gates is not constrained by $m$). In order to conserve his strength, atm wants to choose an initial attack power such that the damage dealt to `drd` is maximized. Can you help him calculate the maximum damage that can be dealt to `drd` in a single attack?\n\n---\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, representing the number of defense gates `drd` has and the range of atm's initial attack power between $0$ and $m$, respectively. \n\nThe next $n$ lines describe each defense gate. Each line contains a string $\\mathrm{op}$ and a non-negative integer $t$, separated by a space. Here $\\mathrm{op}$ indicates the operation corresponding to the defense gate, and $t$ is its associated parameter.\n\n---\n\n### Output Format\n\nOutput a single integer on one line, representing the maximum damage that `drd` can receive in a single attack.\n\n---\n\n### Example\n\nSuppose the initial attack power is $4$, and the final attack power is computed as follows:\n\n- $4 \\ \\mathbin{\\mathrm{AND}} \\ 5 = 4$; \n- $4 \\ \\mathbin{\\mathrm{OR}} \\ 6 = 6$; \n- $6 \\ \\mathbin{\\mathrm{XOR}} \\ 7 = 1$.\n\nSimilarly, we can compute the final attack power for other initial values:\n- For initial attack powers of $1, 3, 5, 7, 9$, the final attack power is $0$.\n- For initial attack powers of $0, 2, 4, 6, 8, 10$, the final attack power is $1$. \n\nThus, the maximum damage dealt to `drd` in a single attack is $1$.\n\n---\n\n### Constraints and Hints\n\n\n\n| Case # | Scale of $n, m$ | Additional Constraints |\n|:-:|:-:|:-:|\n| 1 | $2 \\leq n \\leq 100, m = 0$ | - |\n| 2 | $2 \\leq n \\leq 1000, 1 \\leq m \\leq 1000$ | - |\n| 3 | $2 \\leq n \\leq 1000, 1 \\leq m \\leq 1000$ | - |\n| 4 | $2 \\leq n, m \\leq 10^5$ | One defense gate performs **AND 0** |\n| 5 | $2 \\leq n, m \\leq 10^5$ | All defense gates perform the same operation |\n| 6 | $2 \\leq n, m \\leq 10^5$ | - |\n| 7 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | All defense gates perform the same operation |\n| 8 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | - |\n| 9 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | - |\n| 10 | $2 \\leq n \\leq 10^5, 2 \\leq m \\lt 2^{30}$ | - |\n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2595, "prompt": "### Problem Description\n\n![flow1.jpg](https://img.loj.ac.cn/2024/04/21/2659904243acb.jpg)\n\nIn a distant land, one side is a scenic lake, while the other is an endless desert. The administrative division of this country forms a perfect rectangle with $N$ rows and $M$ columns, as shown in the figure above. Each grid cell represents a city, and every city has an altitude value.\n\nTo ensure that all residents have access to clear lake water, water facilities need to be built in some cities. There are two types of water facilities: **Reservoirs** and **Water Transmission Stations**. The function of a reservoir is to pump lake water into the reservoir in the city it is located. As a result, reservoirs can only be built in cities located in the first row, which are adjacent to the lake. Water transmission stations, on the other hand, can transfer lake water from higher-altitude cities to lower-altitude ones through pipelines. Therefore, for a city to have a water transmission station, there must be an adjacent city (sharing a common edge) at a higher altitude that already has a water facility.\n\nSince the cities in the last row ($N$th row) are near the desert, which is the arid region of the country, it is required that every city in the $N$th row have a water facility. Can this requirement be satisfied? If yes, find the minimum number of reservoirs that need to be built. If not, calculate the number of cities in the arid region that cannot have water facilities.\n\n---\n\n### Input Format\n\nEach line of input contains integers separated by spaces.\n\n- The first line contains two positive integers $N$ and $M$, which specify the dimensions of the rectangle.\n- The next $N$ lines each contain $M$ positive integers, representing the altitude of each city.\n\n---\n\n### Output Format\n\nThe output consists of two lines:\n\n- If the requirement can be satisfied, the first line outputs an integer `1`, and the second line outputs a single integer, representing the minimum number of reservoirs that need to be built.\n- If the requirement cannot be satisfied, the first line outputs an integer `0`, and the second line outputs a single integer, representing the number of cities in the arid region that cannot have water facilities.\n\n---\n\n### Example 1\n\nIn this example, building a reservoir in the city with an altitude of $9$ will satisfy the requirement.\n\n---\n\n### Example 2\n\n![flow2.jpg](https://img.loj.ac.cn/2024/04/21/64305a51c5dd0.jpg)\n\nIn the figure above, building reservoirs in the three cities marked with bold outlines can satisfy the requirement. The water transmission stations originating from these three reservoirs to the arid region cities are marked with three different colors. Note that there may be multiple ways to construct the facilities.\n\n---\n\n### Constraints and Hints\n\nThe problem contains $10$ test cases. The constraints for each test case are given in the table below:\n\n| Test Case ID | Feasibility | $N$ | $M$ | \n| :----------: | :---------: | :-------: | :-------: | \n| 1 | Not Feasible | $\\le 10$ | $\\le 10$ | \n| 2 | Not Feasible | $\\le 100$ | $\\le 100$ | \n| 3 | Not Feasible | $\\le 500$ | $\\le 500$ | \n| 4 | Feasible | $=1$ | $\\le 10$ | \n| 5 | Feasible | $\\le 10$ | $\\le 10$ | \n| 6 | Feasible | $\\le 100$ | $\\le 20$ | \n| 7 | Feasible | $\\le 100$ | $\\le 50$ | \n| 8 | Feasible | $\\le 100$ | $\\le 100$ | \n| 9 | Feasible | $\\le 200$ | $\\le 200$ | \n| 10 | Feasible | $\\le 500$ | $\\le 500$ | \n\nFor all $10$ test cases, the altitude of each city does not exceed $10^6$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3848, "prompt": "### Problem Description\n\nYou are playing a mini-game called \"Remove Stones.\"\n\nThere are $n$ piles of stones arranged in a row, and the $i$-th pile contains $a_i$ stones. Your task is to remove all the stones through the following operations:\n\n- **Operation 1**: Choose one pile of stones and remove at least $2$ stones from it.\n- **Operation 2**: Choose a continuous interval of indices $[l, r]$ ($1 \\le l \\le r \\le n$) such that $r - l \\ge 2$, and remove exactly $1$ stone from each pile in this interval.\n\nYou may perform the above two types of operations in any order and as many times as you wish until no further operations can be performed. If you manage to remove all stones, you win the game.\n\nYou may have already started pondering over questions like \"how many distinct ways to perform the operations?\", but in practice, you always seem to lose the game. Thus, you decide to play a little trick: at the start of the game, you secretly hold $k$ extra stones in your hand. **Before performing any operations, you must distribute and add these $k$ stones into one or more piles of stones.** You hope this might increase your chances of winning, but you also understand that it could potentially make you lose in situations where you might have otherwise won.\n\nNow, you can freely choose an initial game configuration. Specifically, for each pile $a_i$, you can choose its initial number of stones to be any integer within the range $[l_i, r_i]$. You wish to calculate the number of distinct initial configurations where it is possible to have at least one winning strategy. Since the result can be very large, you only need to output the count modulo $({10}^9 + 7)$. **Two initial configurations are considered different if and only if there exists at least one $\\boldsymbol{1 \\le i \\le n}$ such that the two configurations have different values of $\\boldsymbol{a_i}$. Note that an \"initial configuration\" refers to the state before adding the $\\boldsymbol{k}$ stones.**\n\n### Input Format\n\n**There are multiple test cases in this problem.** The first line contains a positive integer $T$ denoting the number of test cases, followed by the descriptions of each test case.\n\nFor each test case:\n- The first line contains two integers $n$ and $k$, representing the number of piles and the number of extra stones to be added.\n- The next $n$ lines each contain two non-negative integers $l_i$ and $r_i$, representing the range of the number of stones in the $i$-th pile.\n\n### Output Format\n\nFor each test case, output a single integer on a separate line, representing the count of possible winning configurations modulo $({10}^9 + 7)$.\n\n### Sample Explanation #1\n\nThere are $2^4 = 16$ possible initial configurations. It can be proven that only the configurations $(0 \\ 0 \\ 0 \\ 0)$ and $(1 \\ 0 \\ 0 \\ 1)$ are unwinnable. In every other configuration, there exists at least one winning strategy. For example, when the initial configuration is $(1 \\ 0 \\ 1 \\ 0)$, you can place the $1$ stone in your hand into the second pile, resulting in the configuration $(1 \\ 1 \\ 1 \\ 0)$. You can then apply Operation 2 on the interval $[1, 3]$ to remove all the stones.\n\n----\n\n**Sample #2**\n\nSee the attached file `stone/stone2.in` and its corresponding answer `stone/stone2.ans`.\n\n----\n\n**Sample #3**\n\nSee the attached file `stone/stone3.in` and its corresponding answer `stone/stone3.ans`.\n\n----\n\n**Sample #4**\n\nSee the attached file `stone/stone4.in` and its corresponding answer `stone/stone4.ans`.\n\n----\n\n### Constraints\n\nFor $100\\%$ of the data, it is guaranteed that:\n\n- $T \\le 10$\n- $3 \\le n \\le 1000$\n- $0 \\le l_i \\le r_i \\le {10}^9$\n- $0 \\le k \\le 100$\n\n| Test Case ID | $n \\le$ | $k \\le$ | Special Conditions |\n|:-:|:-:|:-:|:-:|\n| 1 to 3 | 5 | 2 | $r_i \\le 5$ |\n| 4 to 5 | 1000 | 0 | $l_i = r_i$ |\n| 6 to 8 | 1000 | 100 | $l_i = r_i$ |\n| 9 to 11 | 1000 | 0 | None |\n| 12 to 13 | 1000 | 2 | None |\n| 14 to 15 | 1000 | 100 | $r_i \\le 10$ |\n| 16 to 20 | 1000 | 100 | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2671, "prompt": "### Problem Description\n\nDandan is highly enthusiastic about challenging himself. This summer vacation, he plans to cycle along the Sichuan-Tibet route from Chengdu to Lhasa. The Sichuan-Tibet route offers breathtaking scenery, but it also poses many challenges due to its varied road conditions. Since Dandan's physical stamina is limited, it is crucial for him to set a destination each day and allocate his energy wisely.\n\nThanks to his well-equipped bicycle, we can ignore friction from the bike itself and between the bike and the ground during his rides. Thus, on any given day, it is assumed that Dandan only expends energy overcoming air resistance. On a given day, he plans to ride across $N$ segments, where the road conditions are consistent within each segment. For the $i$-th segment, the road conditions are described by three parameters: $s_i$, $k_i$, and $v_i\u2032$. Here, $s_i$ represents the length of the segment, $k_i$ represents the air resistance coefficient for the segment, and $v_i\u2032$ represents the wind speed for the segment. ($v_i\u2032 > 0$ indicates a tailwind, while $v_i\u2032 < 0$ indicates a headwind).\n\nIf Dandan rides at speed $v$ on the $i$-th segment, the air resistance he experiences is given by $F = k_i (v \u2212 v_i\u2032 )^2$. If he maintains speed $v$ throughout the segment with length $s$, the energy he expends (work done) on this segment is given by $E = k_i (v \u2212 v_i\u2032 )^2 s$.\n\nDandan starts the day with a maximum energy $E_U$. Please help him design a riding strategy to minimize the time $T$ it takes to reach his destination within the provided energy constraints. Output the shortest possible time $T$.\n\n---\n\n### Input Format\n\nThe first line contains a positive integer $N$ and a real number $E_U$, representing the number of road segments and Dandan's maximum energy, respectively.\n\nThe following $N$ lines each describe one segment. Each line contains three real numbers $s_i$, $k_i$, and $v_i\u2032$, representing the segment's length, air resistance coefficient, and wind speed, respectively.\n\n---\n\n### Output Format\n\nOutput a single real number $T$, representing the shortest time it takes for Dandan to reach the destination. The result should be accurate to at least 6 decimal places.\n\n---\n\n### Sample\n\nA possible plan could be: Dandan rides at constant speeds for all three road segments, specifically at $5.12939919$, $8.03515481$, and $6.17837967$.\n\n---\n\n### Constraints and Hints\n\n- **Scoring:** This problem has no partial credits. Your program's output must have an absolute difference of at most $0.000001$ from the standard answer to receive full marks for any test case; otherwise, no points will be awarded.\n\n---\n\n#### Data Constraints:\n\n- For $10\\%$ of the data, $N = 1$;\n- For $40\\%$ of the data, $N \\leq 2$;\n- For $60\\%$ of the data, $N \\leq 100$;\n- For $80\\%$ of the data, $N \\leq 1000$;\n- For all cases, $N \\leq 10000$, $0 \\leq E_U \\leq 10^8$, $0 < s_i \\leq 100000$, $0 < k_i \\leq 15$, $\u2212100 < v_i\u2032 < 100$.\n\nThe data guarantees that the final answer will not exceed $10^5$.\n\n---\n\n#### Hint:\nThere must exist an optimal energy allocation plan where Dandan rides at a **constant speed** on each segment.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3757, "prompt": "### Problem Description\nYT City is a well-planned city, divided into $n \\times n$ areas by east-west and north-south main roads. For simplicity, YT City can be considered as a square, and each area can also be considered as a square. Thus, YT City contains $(n + 1) \\times (n + 1)$ intersections and $2n \\times (n + 1)$ bidirectional roads (referred to as roads). Each bidirectional road connects two adjacent intersections on the main roads. The figure below shows the map of YT City for $n = 2$. The city is divided into $2 \\times 2$ areas, including $3 \\times 3$ intersections and $12$ bidirectional roads.\n\n![](https://img.loj.ac.cn/2022/06/01/9e4fd032418a3.png)\n\nAs the mayor of the city, Mr. Z has gathered statistical data on the traffic flow during rush hour for each direction on every road in YT City. For each road, the numbers represent the number of people passing through the road in both directions during rush hour. Every intersection has a unique elevation value. YT City residents consider uphill climbs to be exhausting. Moving uphill by an elevation of $h$ consumes $h$ units of energy. Conversely, moving downhill does not consume energy. If the difference between the elevation of the endpoint and the starting point of a road is $h$ (note that $h$ may be negative), the energy consumed by one person traveling along this road is $\\max\\{0, h\\}$.\n\nMr. Z also measured the elevation at the northwest intersection, which is $0$, and the southeast intersection, which is $1$ (as shown in the figure above). However, the elevations of all other intersections are unknown. Mr. Z wants to know the minimum total energy consumption during rush hour by all commuters climbing uphill under the most ideal circumstances (i.e., you can assign the elevations of other intersections arbitrarily).\n\n### Input Format\nThe first line contains an integer $n$.\n\nThe next $4n(n + 1)$ lines each contain a non-negative integer. These numbers represent the traffic flow information for each road in both directions.\n\nThe order of input is as follows: $n(n + 1)$ numbers represent traffic flow from west to east, followed by $n(n + 1)$ numbers for traffic flow from north to south, then $n(n + 1)$ numbers for traffic flow from east to west, and finally $n(n + 1)$ numbers for traffic flow from south to north. For each direction, the input order follows the starting intersections from north to south, and if two intersections are at the same north-south position, they are ordered from west to east (see sample input).\n\n### Output Format\nOutput a single number, representing the minimum total energy consumption for all commuters climbing uphill during rush hour under the most ideal circumstances (i.e., the minimum value of the total energy consumption). Round the result to the nearest integer.\n\n### Sample\n![](https://img.loj.ac.cn/2022/06/01/5d669f4600d16.png)\n\n### Data Range and Hints\n- For $20\\%$ of the data: $n \\leq 3$;\n- For $50\\%$ of the data: $n \\leq 15$;\n- For $80\\%$ of the data: $n \\leq 40$;\n- For $100\\%$ of the data: $1 \\leq n \\leq 500$, $0 \\leq \\text{traffic flow} \\leq 10^6$, and all traffic flow values are integers.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3532, "prompt": "### Problem Description\nSmall W has a tree of $n$ nodes, where each edge on the tree can either be a light edge or a heavy edge. You are required to perform $m$ operations on the tree. Initially, all edges on the tree are light edges. The operations are as follows:\n\n1. Given two points $a$ and $b$, first, for every node $x$ on the path from $a$ to $b$ (including $a$ and $b$), you need to change all edges connected to $x$ into light edges. Then, change all edges on the path from $a$ to $b$ into heavy edges.\n2. Given two points $a$ and $b$, calculate how many heavy edges are currently present on the path from $a$ to $b$.\n\n### Input Format\nThe problem contains multiple test cases. The first line of input includes a positive integer $T$, representing the number of test cases. For each test case:\n\nThe first line contains two integers $n$ and $m$, where $n$ represents the number of nodes and $m$ represents the number of operations.\n\nThe next $n - 1$ lines each contain two integers $u\\ v$, representing an edge in the tree.\n\nThe next $m$ lines each contain three integers ${\\mathit{op}}_i\\ a_i\\ b_i$, describing an operation, where ${\\mathit{op}}_i = 1$ denotes the first type of operation, and ${\\mathit{op}}_i = 2$ denotes the second type of operation.\n\nIt is guaranteed that $a_i \\neq b_i$.\n\n### Output Format\nFor each operation of type $2$, output one integer per line representing the result.\n\n**\u3010Sample Explanation #1\u3011**\n\nAfter the first operation, the heavy edges are: $(1, 3)$, $(3, 6)$, $(6, 7)$.\n\nAfter the second operation, the heavy edges include: $(1, 3)$.\n\nAfter the third operation, the heavy edges include: $(1, 3)$, $(3, 6)$, $(6, 7)$.\n\nAfter the fourth operation, edges $(1, 3)$ and $(3, 6)$ become light edges, and edges $(1, 3)$ and $(3, 5)$ become heavy edges.\n\nAfter the fifth operation, the heavy edges include: $(1, 3)$ and $(6, 7)$.\n\nAfter the sixth operation, edge $(1, 3)$ becomes a light edge, and edge $(1, 2)$ becomes a heavy edge.\n\nAfter the seventh operation, the heavy edges include: $(6, 7)$.\n\n**\u3010Sample #2\u3011**\n\nRefer to the files `edge/edge2.in` and `edge/edge2.ans`.\n\nThis sample's constraints are consistent with test points $3 \\sim 6$.\n\n**\u3010Sample #3\u3011**\n\nRefer to the files `edge/edge3.in` and `edge/edge3.ans`.\n\nThis sample's constraints are consistent with test points $9 \\sim 10$.\n\n**\u3010Sample #4\u3011**\n\nRefer to the files `edge/edge4.in` and `edge/edge4.ans`.\n\nThis sample's constraints are consistent with test points $11 \\sim 14$.\n\n**\u3010Sample #5\u3011**\n\nRefer to the files `edge/edge5.in` and `edge/edge5.ans`.\n\nThis sample's constraints are consistent with test points $17 \\sim 20$.\n\n**\u3010Data Constraints\u3011**\n\nFor all test cases: $T \\le 3$, $1 \\le n, m \\le {10}^5$.\n\n| Test Point Index | $n, m \\le $ | Special Properties |\n|:-:|:-:|:-:|\n| $1 \\sim 2$ | $10$ | None |\n| $3 \\sim 6$ | $5000$ | None |\n| $7 \\sim 8$ | ${10}^5$ | A, B |\n| $9 \\sim 10$ | ${10}^5$ | A |\n| $11 \\sim 14$ | ${10}^5$ | B |\n| $15 \\sim 16$ | $2\\times {10}^4$ | None |\n| $17 \\sim 20$ | ${10}^5$ | None |\n\nSpecial Property A: The tree takes the form of a chain.\n\nSpecial Property B: For operations of type $2$, the points $a_i$ and $b_i$ are directly connected by an edge.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2085, "prompt": "### Problem Description\n\nNiuNiu is a high school student passionate about algorithm design. In the algorithms he designs, he often uses numbers with decimal fractions. NiuNiu believes that if the fractional part of a number is **purely periodic** in base $k$, the number is beautiful.\n\nNow, NiuNiu wants to know: given the decimal numbers $n$ and $m$, how many **distinct** purely periodic fractions expressed as $\\frac{x}{y}$ are there in base $k$, where $1 \\leq x \\leq n, 1 \\leq y \\leq m$, and $x$ and $y$ are integers?\n\nA number is purely periodic if and only if it can be written in the following form:\n$$a.\\dot{c_1}c_2c_3 \\ldots c_{p-1}\\dot{c_p}$$\nwhere $a$ is an integer and $p \\geq 1$; for $1 \\leq i \\leq p$, $c_i$ is a single digit in base $k$.\n\nFor example:\n- In decimal (base-10), $0.45454545\\ldots = 0.\\dot{4}\\dot{5}$ is purely periodic. It can be expressed as $\\frac{5}{11}$, $\\frac{10}{22}$, etc.\n- In decimal (base-10), $0.1666666\\ldots = 0.1\\dot{6}$ is not purely periodic. It can be expressed as $\\frac{1}{6}$.\n\nIt is important to note that:\n- We consider integers as purely periodic because their fractional part can be represented as a repetition of $0$ or $k-1$.\n- However, finite decimal fractions with non-zero fractional parts are not purely periodic.\n\n---\n\n### Input Format\nThe input consists of a single line containing three decimal integers $n$, $m$, and $k$, as described above.\n\n---\n\n### Output Format\nOutput a single integer: the number of beautiful numbers that meet the specified conditions.\n\n---\n\n### Sample Case 1\n**Input:**\n```\n2 3 10\n```**Output:**\n```\n4\n```\n\n**Explanation:**\nThe numbers satisfying the conditions are:\n1. $$1/1 = 1.0000 \\ldots$$\n2. $$1/3 = 0.3333 \\ldots$$\n3. $$2/1 = 2.0000 \\ldots$$\n4. $$2/3 = 0.6666 \\ldots$$\n\nAlthough $1/1$ and $2/2$ are both purely periodic fractions, they are considered as the same value, so they are only counted once. Similarly, $1/3$ and $2/6$ are also counted as the same.\n\n---\n\n### Sample Case 2\n**Input:**\n```\n1 1 2\n```\n\n**Output:**\n```\n1\n```\n\n---\n\n### Constraints and Hints\nFor all test cases, the following conditions are satisfied:\n$$1 \\leq n \\leq 10^9, \\quad 1 \\leq m \\leq 10^9, \\quad 2 \\leq k \\leq 2000$$\n\nFor each test case, the constraints are as follows (where blank cells mean no special constraints):\n\n| Test Case ID | $n$ | $m$ | $k$ |\n|:------------:|:-----------------:|:-----------------:|:-----------------:|\n| 1 | $\\leq 10$ | $\\leq 20$ | $=2$ |\n| 2 | $\\leq 100$ | $\\leq 10^4$ | $=2$ |\n| 3 | $\\leq 1000$ | | $=2$ |\n| 4 | $\\leq 10000$ | | $=2$ |\n| 5 | $\\leq 10$ | $\\leq 20$ | $=3$ |\n| 6 | $\\leq 100$ | $\\leq 10^4$ | $=3$ |\n| 7 | $\\leq 1000$ | | $=3$ |\n| 8 | $\\leq 10000$ | | $=3$ |\n| 9 | $\\leq 10$ | $\\leq 20$ | $\\leq 100$ |\n| 10 | $\\leq 100$ | $\\leq 10^4$ | $\\leq 100$ |\n| 11 | $\\leq 1000$ | | $\\leq 1000$ |\n| 12 | $\\leq 10000$ | | |\n| 13 | $\\leq 10^5$ | $\\leq 10^8$ | $\\leq 100$ |\n| 14 | $\\leq 2 \\times 10^5$ | | $\\leq 1000$ |\n| 15 | $\\leq 5 \\times 10^5$ | | |\n| 16 | $\\leq 10^6$ | $\\leq 10^8$ | $\\leq 100$ |\n| 17 | $\\leq 2 \\times 10^6$ | | $\\leq 1000$ |\n| 18 | $\\leq 5 \\times 10^6$ | | |\n| 19 | $\\leq 10^7$ | $\\leq 10^8$ | $\\leq 100$ |\n| 20 | $\\leq 2 \\times 10^7$ | | $\\leq 1000$ |\n| 21 | $\\leq 2 \\times 10^7$ | | |\n| 22 | $\\leq 10^8$ | $\\leq 10^8$ | |\n| 23 | $\\leq 10^8$ | $\\leq 10^8$ | |\n| 24 | | | |\n| 25 | | | |\n\n\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2305, "prompt": "### Problem Statement\n\nLittle L plans to play $n$ games. Each game takes place on a map, where Little L selects a car to complete the game on that map.\n\nLittle L has three racing cars, denoted by the uppercase letters $A$, $B$, and $C$. There are four types of maps, denoted by the lowercase letters $x$, $a$, $b$, and $c$. \n\n- Car $A$ is not suitable for map $a$. \n- Car $B$ is not suitable for map $b$. \n- Car $C$ is not suitable for map $c$. \n- Map $x$ is suitable for all cars.\n\nMaps suitable for all cars are rare, and there are at most $d$ such maps.\n\nThe maps for the $n$ games can be described as a string of lowercase letters. For example, $S=\\texttt{xaabxcbc}$ means Little L plans to play $8$ games. The types of maps are as follows: \n- The $1$st and $5$th games use map $x$, suitable for all cars. \n- The $2$nd and $3$rd games use map $a$, not suitable for car $A$. \n- The $4$th and $7$th games use map $b$, not suitable for car $B$. \n- The $6$th and $8$th games use map $c$, not suitable for car $C$. \n\nLittle L has some specific requirements that can be described using a tuple $(i, h_i, j, h_j)$, indicating that if car model $h_i$ is used in the $i$th game, then car model $h_j$ must be used in the $j$th game.\n\nCan you help Little L choose which car to use for each game? If there are multiple valid solutions, output any one of them.\n\nIf there is no solution, output `-1`.\n\n---\n\n### Input Format\n\nThe first line contains two non-negative integers $n$ and $d$. \n\nThe second line contains a string $S$, where: \n- $S$ is a description of the maps for the $n$ games. \n- $S$ contains $n$ characters, with exactly $d$ of them being the letter $x$. \n\nThe third line contains a positive integer $m$, representing the number of rules related to car usage. \n\nThe next $m$ lines each contain a tuple $i, h_i, j, h_j$, where: \n- $i$ and $j$ are integers. \n- $h_i$ and $h_j$ are characters $A$, $B$, or $C$. \nThe tuple describes the relationship between the car choices for the $i$th and $j$th games.\n\n---\n\n### Output Format\n\nOutput a single line: \n- If there is no solution, output `-1`.\n\n---\n\n### Example\n\nLittle L plans to play $3$ games. \n- The $1$st game's map type is $x$, suitable for all cars. \n- The $2$nd and $3$rd games use map $c$, not suitable for car $C$. \n\nLittle L wants: \n- If car $A$ is used for the $1$st game, then car $B$ must be used for the $2$nd game.\n\nA valid solution could assign cars $A$, $B$, and $A$ to the $3$ games. \n\nAssigning cars $B$, $B$, and $B$ or $B$, $A$, and $A$ is also valid. \n\nAssigning cars $A$, $A$, and $B$ or $A$, $B$, and $C$ is invalid because they do not satisfy all rules.\n\n---\n\n### Constraints & Hints\n\n| Test Case Number | $n$ | $d$ | $m$ | Additional Properties |\n| :--------------: | :----------------: | :-----: | :--------: | :-----------------------------------: |\n| $1$ | $\\le 2$ | $0$ | $\\le 4$ | None |\n| $2$ | $\\le 2$ | $\\le n$ | $\\le 4$ | None |\n| $3$ | $\\le 5$ | $0$ | $\\le 10$ | None |\n| $4$ | $\\le 5$ | $\\le n$ | $\\le 10$ | None |\n| $5$ | $\\le 10$ | $0$ | $\\le 20$ | None |\n| $6$ | $\\le 10$ | $\\le 8$ | $\\le 20$ | None |\n| $7$ | $\\le 20$ | $0$ | $\\le 40$ | $S$ only contains $c$ |\n| $8$ | $\\le 20$ | $0$ | $\\le 40$ | None |\n| $9$ | $\\le 20$ | $\\le 8$ | $\\le 40$ | $S$ only contains $x$ or $c$ |\n| $10$ | $\\le 20$ | $\\le 8$ | $\\le 40$ | None |\n| $11$ | $\\le 100$ | $0$ | $\\le 200$ | $S$ only contains $c$ |\n| $12$ | $\\le 100$ | $0$ | $\\le 200$ | None |\n| $13$ | $\\le 100$ | $\\le 8$ | $\\le 200$ | $S$ only contains $x$ or $c$ |\n| $14$ | $\\le 100$ | $\\le 8$ | $\\le 200$ | None |\n| $15$ | $\\le 5\\times 10^3$ | $0$ | $\\le 10^4$ | None |\n| $16$ | $\\le 5\\times 10^3$ | $\\le 8$ | $\\le 10^4$ | $S$ only contains $x$ or $c$ |\n| $17$ | $\\le 5\\times 10^3$ | $\\le 8$ | $\\le 10^4$ | None |\n| $18$ | $\\le 5\\times 10^4$ | $0$ | $\\le 10^5$ | None |\n| $19$ | $\\le 5\\times 10^4$ | $\\le 8$ | $\\le 10^5$ | $S$ only contains $x$ or $c$ |\n| $20$ | $\\le 5\\times 10^4$ | $\\le 8$ | $\\le 10^5$ | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2086, "prompt": "### Problem Description\n\nOn a number line, there are $n$ closed intervals: $[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$. You need to select $m$ intervals from these such that the selected $m$ intervals collectively include at least one position. In other words, there must exist at least one position $x$ such that for every selected interval $[l_i, r_i]$, $l_i \\leq x \\leq r_i$.\n\nFor a valid selection, the cost is defined as the length of the longest selected interval minus the length of the shortest selected interval. The length of an interval $[l_i, r_i]$ is defined as $r_i - l_i$, i.e., the difference between its right endpoint value and its left endpoint value.\n\nFind the minimum cost among all valid selections. If no valid selection exists, output $-1$.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, separated by a space, as described above. It is guaranteed that $1 \\leq m \\leq n$.\n\nThe next $n$ lines each describe an interval, containing two integers $l_i$ and $r_i$, separated by a space, representing the left and right endpoints of the interval.\n\n---\n\n### Output Format\n\nOutput a single integer: the minimum cost.\n\n---\n\n### Example\n\n![](https://img.loj.ac.cn/2022/09/22/94a95ae0be394.png)\n\nFor $n = 6, m = 3$, the minimum cost selection is to choose the intervals $[3, 5]$, $[3, 4]$, and $[1, 4]$. These intervals collectively include position $4$, making the selection valid. Among the selected intervals, the longest one is $[1, 4]$ and the shortest one is $[3, 4]$. The cost of this selection is $(4 - 1) - (4 - 3) = 2$. \n\n---\n\n### Data Range and Hints\n\nThe range and characteristics of the test data are shown in the table below:\n\n\n\n| Test Case ID | $ n $ | $ m $ | $ l_i, r_i $ |\n|:-:|:-:|:-:|:-:|\n| 1 | $ 20 $ | $ 9 $ | $ 0 \\leq l_i \\leq r_i \\leq 100 $ |\n| 2 | $ 20 $ | $ 10 $ | $ 0 \\leq l_i \\leq r_i \\leq 100 $ |\n| 3 | $ 199 $ | $ 3 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 4 | $ 200 $ | $ 3 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 5 | $ 1000 $ | $ 2 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 6 | $ 2000 $ | $ 2 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 7 | $ 199 $ | $ 60 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 8 | $ 200 $ | $ 50 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 9 | $ 200 $ | $ 50 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 10 | $ 1999 $ | $ 500 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 11 | $ 2000 $ | $ 400 $ | $ 0 \\leq l_i \\leq r_i \\leq 5000 $ |\n| 12 | $ 2000 $ | $ 500 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 13 | $ 30000 $ | $ 2000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 14 | $ 40000 $ | $ 1000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 15 | $ 50000 $ | $ 15000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 16 | $ 100000 $ | $ 20000 $ | $ 0 \\leq l_i \\leq r_i \\leq 100000 $ |\n| 17 | $ 200000 $ | $ 20000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 18 | $ 300000 $ | $ 50000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 19 | $ 400000 $ | $ 90000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n| 20 | $ 500000 $ | $ 200000 $ | $ 0 \\leq l_i \\leq r_i \\leq 10^9 $ |\n\n---\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3008, "prompt": "### Problem Description\n\nA rooted and weighted tree is defined as a **Symmetric Binary Tree** by Xuanxuan if it satisfies the following conditions:\n\n1. It is a binary tree.\n2. After swapping the left and right subtrees of **all** nodes, the resulting tree has the same structure as the original tree, and the corresponding nodes have the same values.\n\nIn the diagram below, the numbers inside the nodes represent the weights, and the `$id$` outside the nodes represents the node identifier.\n\n![](https://uploadfiles.nowcoder.com/images/20181110/306604_1541848852978_E09FB8BAC799B78F2BA4FA809F4F25DE)\n\nGiven a binary tree, your task is to find a subtree of this tree that is a **Symmetric Binary Tree** and has the largest number of nodes. Output the number of nodes in this subtree.\n\n**Note**: A tree with only the root node is also a symmetric binary tree. In this problem, a subtree rooted at node $T$ includes node $T$ and **all** its descendant nodes.\n\n### Input Format\n\nThe input file is named `tree.in`.\n\nThe input consists of:\n\n- The first line contains a positive integer $n$, the number of nodes in the given tree. Nodes are indexed from $1$ to $n$, and node $1$ is the root of the tree.\n- The second line contains $n$ positive integers separated by spaces, where the $i$-th integer $v_i$ represents the weight of node $i$.\n- The next $n$ lines each contain two integers $l_i$ and $r_i$, representing the left and right child of node $i$, respectively. If a node does not have a left or right child, it is denoted by $-1$. Both numbers are separated by a space.\n\n### Output Format\n\nThe output file is named `tree.out`.\n\nThe output contains a single integer, representing the number of nodes in the largest symmetric binary subtree of the given tree.\n\n---\n\n### Example 1\n\n\n\nThe largest symmetric binary subtree is the subtree rooted at node $2$, which has $1$ node.\n\n---\n\n### Example 2\n\n\n\nThe largest symmetric binary subtree is the subtree rooted at node $7$, which has $3$ nodes.\n\n---\n\nRefer to the accompanying `tree3.in` and `tree3.ans` files for further examples.\n\n### Constraints and Hints\n\nThere are $25$ test cases.\n\n- $v_i \\leq 1000$.\n- For test cases $1 \\sim 3$, $n \\leq 10$. In these cases, all nodes in the left subtree of the root do not have right children, and all nodes in the right subtree of the root do not have left children.\n- For test cases $4 \\sim 8$, $n \\leq 10$.\n- For test cases $9 \\sim 12$, $n \\leq 10^5$, and the input tree is guaranteed to be a \"Full Binary Tree\".\n- For test cases $13 \\sim 16$, $n \\leq 10^5$, and the input tree is guaranteed to be a \"Complete Binary Tree\".\n- For test cases $17 \\sim 20$, $n \\leq 10^5$, and all node weights of the input tree are the same ($v_i = 1$).\n- For test cases $21 \\sim 25$, $n \\leq 10^6$.\n\n---\n\n### Definitions\n\n**Level**: The level of a node is its distance from the root. The root is at level $1$, and the children of the root are at level $2$. For any node, its level is equal to the level of its parent plus $1$. \n**Depth of a Tree**: The depth of a tree is defined as the maximum level among all its nodes.\n\n#### Full Binary Tree \nA binary tree is a **Full Binary Tree** if its depth is $h$ and it contains $2^h - 1$ nodes.\n\n![](https://uploadfiles.nowcoder.com/images/20181110/306604_1541859030087_B663B244A48AAD0CE81DCC50E78E1386)\n\n#### Complete Binary Tree \nA binary tree is a **Complete Binary Tree** if all levels except possibly the last level are completely filled, and all the nodes in the last level are aligned to the left.\n\n![](https://uploadfiles.nowcoder.com/images/20181110/306604_1541859056448_08E14E77121B5C0CDDB7A458EF4DC4C3)\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3533, "prompt": "### Problem Description\n\nLittle L has a directed graph where the vertices can be divided into $k$ layers. The $i$-th layer contains $n_i$ vertices. The first layer and the $k$-th layer have the **same number of vertices**, i.e., $n_1 = n_k$, and for the $j$-th layer ($2 \\leq j \\leq k-1$), $n_1 \\leq n_j \\leq 2n_1$. For vertices in the $j$-th layer ($1 \\leq j < k$), edges originating from them are only connected to vertices in the $(j+1)$-th layer. No edges are connected to vertices in the first layer, and vertices in the $k$-th layer do not have outgoing edges.\n\nNow, Little L wants to select $n_1$ paths from the graph, each starting at a vertex in the first layer and ending at a vertex in the $k$-th layer, with the condition that **every vertex in the graph appears in at most one path**. Specifically, each path can be written as a $k$-tuple $(p_1, p_2, \\ldots, p_k)$, where the path sequentially traverses the $p_j$-th vertex of the $j$-th layer ($1 \\leq p_j \\leq n_j$). Additionally, for the $p_j$-th vertex in the $j$-th layer ($1 \\leq j < k$), there is an edge to the $p_{j+1}$-th vertex in the $(j+1)$-th layer.\n\nLittle L drew these paths on paper and noticed that they could produce intersection points. For two paths $P$ and $Q$, assume their edges between the $j$-th and $(j+1)$-th layers are $(P_j, P_{j+1})$ and $(Q_j, Q_{j+1})$, respectively. If,\n\n$$\n(P_j - Q_j) \\times (P_{j+1} - Q_{j+1}) < 0\n$$\n\nthen it is said that the two paths intersect after the $j$-th layer. The number of intersections between two paths is the total number of intersections they produce after the $1, 2, \\ldots, k-1$ layers. For the entire path scheme, the intersection count is the **sum of intersection counts between every pair of distinct paths**. For example, the following figure shows an example with 3 paths and 3 intersections, with the red dots representing intersection points:\n\n![](https://img.loj.ac.cn/2021/07/26/60fe2a7bd4aa0.png)\n\nLittle L wants to know how many more path schemes with an even number of intersections there are than path schemes with an odd number of intersections. Two path schemes are considered identical if and only if the $n_1$ paths, represented as $k$-tuples sorted by the starting vertex's index in the first layer, can correspond to the same scheme. Since the final result may be large, please output the result modulo $998244353$ (a large prime number).\n\n### Input Format\n\nData is read from the file `xpath.in`.\n\nThe input consists of multiple test cases. The first line contains a positive integer $T$, indicating the number of test cases. For each test case:\n\n- The first line contains a positive integer $k$, indicating the number of layers of vertices.\n- The second line contains $k$ integers $n_1, n_2, \\ldots, n_k$, indicating the number of vertices in each layer. It is guaranteed that $n_1 = n_k$, and $n_1 \\leq n_i \\leq 2n_1$ ($2 \\leq i \\leq k-1$).\n- The third line contains $k-1$ integers $m_1, m_2, \\ldots, m_{k-1}$, indicating the number of edges from the $j$-th layer to the $(j+1)$-th layer. It is guaranteed that $m_j \\leq n_j \\times n_{j+1}$.\n- The next $k-1$ segments of input describe the edges between layers. The $j$-th segment ($1 \\leq j < k$) contains $m_j$ lines, each with two integers $u, v$, representing an edge from the $u$-th vertex in the $j$-th layer to the $v$-th vertex in the $(j+1)$-th layer.\n\nIt is guaranteed that there are no duplicate edges in the graph.\n\n### Output Format\n\nWrite the output to the file `xpath.out`.\n\nThe output consists of $T$ lines, each containing a single integer, which represents the answer for the corresponding test case modulo $998244353$.\n\n### Example\n\nPath schemes with an even number of intersections: $2$. \nPath schemes with an odd number of intersections: $1$. \nThus, the result is $1$.\n\nExchanging the schemes of path $1$ and path $2$ results in identical schemes. For instance, a scheme where path $1$ is $(2, 3, 1)$ and path $2$ is $(1, 1, 2)$ is the same as scheme $1$. Such schemes are not counted again in the answer.\n\n| Path Scheme | Path $1$ | Path $2$ | Total Intersections |\n| :----------: | :------: | :------: | :-----------------: |\n| $1$ | $(1,1,2)$ | $(2,3,1)$ | $1$ |\n| $2$ | $(1,2,1)$ | $(2,1,2)$ | $2$ |\n| $3$ | $(1,2,1)$ | $(2,3,2)$ | $0$ |\n\n### Constraints and Hints\n\nFor all test cases: $2 \\leq k \\leq 100$, $2 \\leq n_1 \\leq 100$, $1 \\leq T \\leq 5$. \n\nFor each test case, there is only one input with $n_1 > 10$. \n\n| Test Case ID | $k=$ | $n_1 \\leq$ | Special Properties |\n| :----------: | :---: | :--------: | :----------------: |\n| $1 \\sim 4$ | $2$ | $10$ | None |\n| $5 \\sim 6$ | $10$ | $10$ | A, B |\n| $7 \\sim 8$ | $10$ | $10$ | A |\n| $9 \\sim 10$ | $10$ | $10$ | None |\n| $11 \\sim 13$ | $2$ | $100$ | None |\n| $14 \\sim 15$ | $100$ | $100$ | A, B |\n| $16 \\sim 17$ | $100$ | $100$ | A |\n| $18 \\sim 20$ | $100$ | $100$ | None |\n\nSpecial Property A: For all $i$ ($2 \\leq i \\leq k-1$), $n_i = n_1$. \nSpecial Property B: The total number of path schemes is guaranteed to be at most $1$. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2598, "prompt": "### Problem Description\n\n**Mayan Puzzle** is a recently popular game. The game interface consists of a $7$-row by $5$-column grid populated with blocks. Blocks cannot hover; they must be placed either on the bottommost row or stacked on top of other blocks. The goal of the game is to clear all the blocks within a specified number of moves. The block elimination rules are as follows:\n\n1. Each move allows you to drag a single block one step horizontally, either to the left or right.\n\n * If the target position (the position a block moves to) already contains a block, the dragged block and the block in the target position will switch places (refer to the transition from Diagram $6$ to Diagram $7$ in the input-output example illustration).\n \n * If the target position is empty, the dragged block will be pulled out of its original column and will fall straight down to the target position until it rests on a surface (refer to the transition from Diagram $1$ to Diagram $2$ below).\n\n ![](https://img.loj.ac.cn/2019/09/22/5d87356ada259.png)\n\n2. Blocks are eliminated when there are three or more blocks of the same color consecutively aligned in a row or column. Blocks are removed immediately when this condition is met (refer to the transition from Diagram $1$ to Diagram $3$).\n\n**Important Notes:**\n\na) If multiple sets of blocks meet the elimination criteria simultaneously, all qualifying sets will be eliminated at the same time. For example, in Diagram $4$, three blocks of color $1$ and three blocks of color $2$ will be eliminated simultaneously, leaving only one block of color $2$.\n\nb) If both a row and a column meet the elimination criteria, and they share one or more blocks, all the qualifying blocks in that row and column will be eliminated simultaneously. For example, in the scenario shown in Diagram $5$, $5$ blocks will be eliminated at the same time.\n\n ![](https://img.loj.ac.cn/2019/09/22/5d87356b5e9cf.png)\n\n3. After blocks are eliminated, blocks above the eliminated positions will fall straight down to fill the empty spaces. Further eliminations may occur after blocks have settled. Notably, no blocks are eliminated during the falling process.\n\nThe process of moving a block and the changes to the grid are illustrated in Diagrams $1$ to $3$. The bottom-left corner of the grid is assigned the coordinates $(0,0)$. Starting with the configuration depicted in Diagram $1$, dragging the block at $(3,3)$ to the left transforms the grid into the state shown in Diagram $2$. At this point, a vertical column of three consecutive blocks of color $4$ forms and is eliminated. After elimination, the color $3$ block above them falls downward, resulting in the grid state depicted in Diagram $3$.\n\n---\n\n### Input Format\n\n1. The first line contains a single positive integer $n$, which represents the number of moves required to clear the game.\n2. The following $5$ lines describe the $7 \\times 5$ game grid. Each line contains a set of integers separated by spaces, ending with a $0$. These numbers, read from bottom to top, represent the colors of the blocks in each column (where color types are numbered consecutively starting from $1$ and at most $10$ different colors are used). Blocks with the same number correspond to blocks of the same color.\n\nThe input is guaranteed that, in the initial grid configuration, there are no blocks that can be immediately eliminated.\n\n---\n\n### Output Format\n\nIf a solution exists, output $n$ lines, each containing three integers $x, y, g$, which represent a single move. The integers $x, y$ specify the coordinates of the block to be moved, and $g$ specifies the direction of the move ($1$ for moving to the right and $-1$ for moving to the left). Each pair of integers should be separated by a single space. In case of multiple solutions, output the lexicographically smallest solution, prioritizing $x$ as the primary key, $y$ as the secondary key, and $1$ before $-1$ for the direction.\n\nIf no solution exists, output a single line containing the integer `-1`.\n\nThe game's grid uses $(0,0)$ as the coordinates for the bottom-left corner.\n\n---\n\n### Example\n\nAs shown in the sequence of diagrams labeled $6$ through $11$, the grid's initial configuration is as depicted in the first image. The game is solved in three steps:\n\n1. Move the block at $(2,1)$ to the right.\n2. Move the block at $(3,1)$ to the right.\n3. Move the block at $(3,0)$ to the right.\n\nFollowing these steps, all the blocks on the grid are eliminated.\n\n---\n\n#### Sample Input\n```\n3\n3 4 1 0\n3 4 2 2 0\n3 4 2 1 0\n1 0\n2 3 0\n0\n```#### Sample Output\n```\n2 1 1\n3 1 1\n3 0 1\n```\n\n---\n\n### Constraints and Hints\n\n1. For $30\\%$ of the data, all the blocks in the initial grid are located in the bottommost row.\n2. For $100\\%$ of the data, $0 < n \\leq 5$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2087, "prompt": "### Problem Description\n\nThere are $n$ cities in the Flea Kingdom. The great Flea King resides in the capital city of the Flea Kingdom, which is City $1$.\n\nThe biggest problem in the Flea Kingdom is the water supply issue. Due to the large population in the capital city, the benevolent Flea King allocates his own water to the residents of the Flea Kingdom, often leaving the Flea King without water to drink.\n\nTo address this issue, the Flea Kingdom has built cylindrical water tanks in every city. These tanks are identical and tall enough to hold any amount of water. After a rainy day, City $i$ collected water with a height of $h_i$. Due to geographical and weather factors, the water levels collected by any two cities are distinct.\n\nThe Flea King has also engaged the Ant Artisans to construct an extensive underground connection system. Whenever the Flea King uses this underground system, he can designate any number of cities to connect their water tanks. Upon closing the underground connection system after sufficient time, the water levels in all the connected cities' water tanks will equalize. The final height of water in these connected tanks will be the average of the initial heights of the connected tanks.\n\nDue to the complexity of the underground system, the Flea King can use the system at most $k$ times.\n\nThe Flea King wants you to tell him the maximum water level that can be achieved in the water tank of the capital, City $1$.\n\n---\n\n### Input Format\n\nThe first line contains three positive integers $n$, $k$, and $p$, representing the number of cities in the Flea Kingdom, the maximum number of times the Flea King can use the underground connection system, and the precision required for the output, respectively. The meaning of $p$ will be explained in the output section.\n\nThe second line contains $n$ distinct positive integers, describing the water levels of the cities' water tanks after the rain. The $i$-th integer $h_i$ represents the water level in City $i$'s tank. It is guaranteed that the $h_i$ values are distinct and that $1 \\leq h_i \\leq 10^5$.\n\n---\n\n### Output Format\n\nOutput a single line containing a real number, representing the maximum water level that can be achieved in the water tank of City $1$.\n\nThe real number can only contain a non-negative integer part, a decimal point, and a fractional part. The integer part is mandatory and should not include a sign. If a fractional part exists, it must be separated from the integer part by a decimal point. If there is no fractional part, the decimal point should not be included.\n\nThe output real number must have no more than $2p$ digits after the decimal point, and it is recommended to retain at least $p$ digits. It is guaranteed that the reference answer and the true answer have an absolute error of less than $10^{-2p}$. \n\nYour output will be considered correct if and only if the absolute error between your output and the reference answer is less than $10^{-p}$.\n\nIf the absolute error between your output and the reference answer is not less than $10^{-p}$ but less than $10^{-5}$, you will earn $40\\%$ of the points for that test case.\n\n---\n\n### Example 1\n\n#### Input\n```\n3 1 2\n1 4 2\n```#### Explanation\n\nWith at most one use of the underground connection system, the possible scenarios are:\n1. Not using the connection system: The water level in City $1$ remains $1$.\n2. Using the system once to connect Cities $1$ and $2$: The water level in City $1$ becomes $5/2$.\n3. Using the system once to connect Cities $1$ and $3$: The water level in City $1$ becomes $2/2$.\n4. Using the system once to connect Cities $2$ and $3$: The water level in City $1$ remains $1$.\n5. Using the system once to connect Cities $1$, $2$, and $3$: The water level in City $1$ becomes $8/3$.\n\n#### Output\n```\n2.6667\n```\n\n---\n\n### Example 2\n\n#### Input\n```\n3 2 5\n1 4 2\n```\n\n#### Explanation\n\nThe optimal solution is to use the connection system twice: first connecting Cities $1$ and $3$, and then connecting Cities $1$ and $2$.\n\n#### Output\n```\n3.00000\n```\n\n---\n\n### Notes and Constraints\n\n#### Notes\nTo ensure accuracy, it is generally recommended to maintain greater precision than required during calculations. Specifically, it can be proven that in any reference solution for all subtasks, maintaining at least $\\frac{6}{5}p$ digits of precision throughout the computation process guarantees that the absolute error between the output and the reference answer will always be less than $10^{-p}$.\n\nFor convenience, a fixed-point high-precision decimal class is provided. Contestants may refer to and use this class as needed, or implement their own solution. Details on how to use this class can be found in the attached document `decimal.pdf`.\n\n#### Constraints\n\n\n| Test Case Number | $n$ | $k$ | $p$ |\n|-|-|-|-|\n| 1 | $\\leq 2$ | $\\leq 5$ | $=5$ |\n| 2 | $\\leq 4$ | $\\leq 5$ | $=5$ |\n| 3 | $\\leq 4$ | $\\leq 5$ | $=5$ |\n| 4 | $\\leq 10$ | $=1$ | $=5$ |\n| 5 | $\\leq 10$ | $=10^9$ | $=5$ |\n| 6 | $\\leq 10$ | $\\leq 10$ | $=5$ |\n| 7 | $\\leq 10$ | $\\leq 10$ | $=5$ |\n| 8 | $\\leq 100$ | $=1$ | $=5$ |\n| 9 | $\\leq 100$ | $=10^9$ | $=40$ |\n| 10 | $\\leq 100$ | $\\leq 10^9$ | $=40$ |\n| 11 | $\\leq 100$ | $\\leq 10^9$ | $=40$ |\n| 12 | $\\leq 100$ | $\\leq 10^9$ | $=40$ |\n| 13 | $\\leq 250$ | $\\leq 10^9$ | $=100$ |\n| 14 | $\\leq 500$ | $\\leq 10^9$ | $=200$ |\n| 15 | $\\leq 700$ | $\\leq 10^9$ | $=300$ |\n| 16 | $\\leq 700$ | $\\leq 10^9$ | $=300$ |\n| 17 | $\\leq 700$ | $\\leq 10^9$ | $=300$ |\n| 18 | $\\leq 2500$ | $\\leq 10^9$ | $=1000$ |\n| 19 | $\\leq 4000$ | $\\leq 10^9$ | $=1500$ |\n| 20 | $\\leq 8000$ | $\\leq 10^9$ | $=3000$ |\n\n---\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3339, "prompt": "### Problem Description\n\nAfter repelling the invasion of the Disaster Army, the Elven Kingdom on the continent of Bzeroth has flourished over the past decade, attracting tourists from all directions. Little W, a renowned gourmet who has traveled around the world, is now visiting the Elven Kingdom.\n\nThe Elven Kingdom consists of $n$ cities, numbered from $1$ to $n$. The delicacies in city $i$ can bring $c_i$ happiness points to Little W. The cities are connected by $m$ **one-way roads**, numbered from $1$ to $m$. Road $i$ starts from city $u_i$, ends at city $v_i$, and takes $w_i$ days to traverse. That is, if Little W departs from city $u_i$ along road $i$ on day $d$, he will arrive at city $v_i$ on day $d + w_i$.\n\nLittle W plans to undertake a journey in the Elven Kingdom lasting $T$ days. Specifically:\n- He will start his journey on day $0$ from city $1$.\n- After $T$ days of traveling, he must end his journey **exactly on day $T$** back at city $1$.\n\nAs an avid gourmet, Little W tastes the delicacies of a city every time he arrives (including city $1$ on day $0$ and day $T$), gaining the associated happiness points. If Little W revisits a city multiple times, he gains happiness points multiple times. **Note that Little W cannot stay in a city during his journey**: whenever he arrives at a city without finishing his journey, he must leave immediately for another city on the same day.\n\n![](https://img.loj.ac.cn/2020/08/18/5f3bb2b598679.png)\n\n
Figure 1: Sample 1
\n\nFor the diagram above, one feasible $11$-day travel plan for Little W is $1 \\rightarrow 2 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 1$:\n\n- On day $0$, Little W starts from city $1$, gains happiness points $1$, and departs for city $2$.\n- On day $1$, Little W arrives at city $2$, gains happiness points $3$, and departs for city $1$.\n- On day $4$, Little W arrives at city $1$, gains happiness points $1$, and departs for city $2$.\n- On day $5$, Little W arrives at city $2$, gains happiness points $3$, and departs for city $3$.\n- On day $7$, Little W arrives at city $3$, gains happiness points $4$, and departs for city $1$.\n- On day $11$, Little W arrives at city $1$, gains happiness points $1$, and ends his journey.\n\n- The total happiness points Little W gains from this journey is $13$.\n\nAdditionally, the Elven Kingdom hosts **distinct** food festivals $k$ times at different times. Specifically, the $i$th food festival will be held on day $t_i$ in city $x_i$. If Little W arrives at city $x_i$ exactly on day $t_i$, he gains **additional happiness points** $y_i$. Now, Little W asks you, as the official host representing the Elven Kingdom, to calculate the **maximum total happiness points** he can obtain from his journey.\n\n---\n\n### Input Format\n\nRead the input from the file `delicacy.in`.\n\nThe first line contains four integers $n, m, T, k$, which represent the number of cities, the number of roads, the number of travel days, and the number of food festivals, respectively.\n\nThe second line contains $n$ integers $c_i$, which represent the happiness points provided by the delicacies of each city.\n\nThe next $m$ lines each contain three integers $u_i, v_i, w_i$, which represent the start city, end city, and transit days of each road.\n\nThe final $k$ lines each contain three integers $t_i, x_i, y_i$, which represent the festival day, festival city, and additional happiness points provided by each food festival.\n\nThe problem guarantees:\n- For all $1 \\leq i \\leq m$, $u_i \\neq v_i$. However, there may be duplicate **one-way roads**; that is, it is possible for $1 \\leq i < j \\leq m$, such that $u_i = u_j$ and $v_i = v_j$.\n\n- For every city, there exists at least one one-way road starting from that city.\n\n- Each food festival day $t_i$ is unique.\n\n---\n\n### Output Format\n\nWrite the output to the file `delicacy.out`.\n\nOutput a single integer, which represents the maximum happiness points Little W can achieve through his journey.\n\nIf **Little W cannot return to city $1$ exactly on day $T$, output** $-1$.\n\n---\n\n### Example 1\n\nThis example is from the problem description. The optimal journey plan is shown in the description.\n\n---\n\n### Example 2\n\nThe optimal plan is $1\\rightarrow 3\\rightarrow 4\\rightarrow 2\\rightarrow 3\\rightarrow 4\\rightarrow 1$:\n\n- On day $0$, Little W starts from city $1$, gains happiness points $3$, and travels using road $3$.\n- On day $2$, Little W arrives at city $3$, gains happiness points $2$, and travels using road $4$.\n- On day $5$, Little W arrives at city $4$, gains happiness points due to the food festival $20 + 4$, and travels using road $7$.\n- On day $6$, Little W arrives at city $2$, gains happiness points $1$, and travels using road $5$.\n- On day $8$, Little W arrives at city $3$, gains happiness points $2$, and travels using road $4$.\n- On day $11$, Little W arrives at city $4$, gains happiness points $4$, and travels using road $8$.\n- On day $16$, Little W arrives at city $1$, gains happiness points $3$, and ends his journey.\n\n- The total happiness points Little W gains from this journey is $39$.\n\nRefer to the additional files `delicacy3.in` and `delicacy3.ans` for input and output examples.\n\n---\n\n### Constraints & Hints\n\nFor all test cases:\n\n$1 \\leq n \\leq 50$, $n \\leq m \\leq 501$, $0 \\leq k \\leq 200$, $1 \\leq t_i \\leq T \\leq 10^9$.\n\n$1 \\leq w_i \\leq 5$, $1 \\leq c_i \\leq 52501$, $1 \\leq u_i, v_i, x_i \\leq n$, $1 \\leq y_i \\leq 10^9$.\n\nThe specific constraints for each test case are listed below:\n\n| Test Case ID | $n$ | $m$ | $T$ | Special Constraint |\n| :------------: | :--------: | :--------: | :---------: | :-----------------: |\n| $1\\sim 4$ | $\\leq 5$ | $\\leq 50$ | $\\leq 5$ | |\n| $5\\sim 8$ | $\\leq 50$ | $\\leq 50$ | $\\leq 52501$| |\n| $9\\sim 10$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | A |\n| $11\\sim 13$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | $k=0$ |\n| $14\\sim 15$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | $k\\leq 10$ |\n| $16 \\sim 17$ | $\\leq 50$ | $\\leq 50$ | $\\leq 10^9$ | |\n| $18 \\sim 20$ | $\\leq 50$ | $\\leq 501$ | $\\leq 10^9$ | |\n\nSpecial Constraint A: $n = m$ and $u_i = i$, $v_i = (i \\bmod n) + 1$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3564, "prompt": "### Problem Description\n\nThe counting game is a widely popular casual game. Each participant, in a predetermined order, calls out numbers sequentially. However, if the next number is a multiple of $7$ or contains the digit $7$ in its decimal representation, they must skip that number; otherwise, they lose the game.\n\nOne pleasant afternoon, after finishing the SPC20nn competition, little r and little z decided to play this counting game out of boredom. However, with only two players, the calculations were relatively simple, so they played the game for a long time without determining a winner. At this point, little z had a sudden inspiration and decided to augment the game: for any number that contains the digit $7$ in its decimal representation, all of its multiples also cannot be counted!\n\nFormally, let $p(x)$ indicate whether $x$ contains the digit $7$ in its decimal representation. If so, $p(x) = 1$; otherwise, $p(x) = 0$. A positive integer $x$ cannot be called out if and only if there exist positive integers $y$ and $z$ such that $x = yz$ and $p(y) = 1$.\n\nFor example:\n- If little r calls out $6$, since $7$ cannot be called, little z will need to call out $8$ next.\n- If little r calls out $33$, then $34 = 17 \\times 2$ and $35 = 7 \\times 5$ cannot be called, so little z must call out $36$ next.\n- If little r calls out $69$, since all numbers from $70$ to $79$ contain the digit $7$, little z must call out $80$ next.\n\nNow, given that little r's last number was $x$, little z wants to quickly figure out the next number he needs to call. However, he quickly realizes that this augmented game is much harder to calculate than the original game, so he needs your help. If little r calls out a number $x$ that itself cannot be called, you must also quickly determine that little r has lost the game.\n\nSince little r and little z have played the game for a long time, little z has many such queries that you need to answer.\n\n### Input Format\n\nThe first line contains a positive integer $T$, indicating the number of queries little z makes.\n\nThe next $T$ lines each contain a positive integer $x$, representing the number little r calls out in this round.\n\n### Output Format\n\nOutput $T$ lines. For each query:\n- If little r's number cannot be called, output $-1$.\n- Otherwise, output the next number that little z needs to call.\n\n### Sample Input\n```plaintext\n4\n6\n33\n69\n300\n```### Sample Output\n```plaintext\n8\n36\n80\n-1\n```\n\n### Sample Explanation\n\nThe explanations for the first three queries are already provided in the problem description.\n\nFor the fourth query:\n- Since $300 = 75 \\times 4$, and $75$ contains the digit $7$, little r loses the game.\n\n### Constraints\n\n- For $10\\%$ of the cases: $T \\leq 10$, $x \\leq 100$. \n- For $30\\%$ of the cases: $T \\leq 100$, $x \\leq 1000$. \n- For $50\\%$ of the cases: $T \\leq 1000$, $x \\leq 10000$. \n- For $70\\%$ of the cases: $T \\leq 10000$, $x \\leq 2 \\times 10^5$. \n- For $100\\%$ of the cases: $1 \\leq T \\leq 2 \\times 10^5$, $1 \\leq x \\leq 10^7$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2299, "prompt": "### Problem Description\n\nIn the year 3030, Macsy is deploying a group of robots on Mars.\n\nDuring the 1st second, Macsy transports Robot #1 to Mars. Robot #1 can produce other robots. \nIn the 2nd second, Robot #1 produces its first robot\u2014Robot #2. \nIn the 3rd second, Robot #1 produces another robot\u2014Robot #3.\n\nFrom then on, Robot #1 produces a new robot every second. The robot produced in the $m$-th second is numbered $m$. We can call it Robot #$m$.\n\nOnce a robot is produced, it begins working immediately. Robot #$m$ takes a rest every $m$ seconds. For example, Robot #3 takes a rest in the 6th, 9th, 12th, $\\ldots$ seconds, and works the rest of the time.\n\nWhen a robot takes a rest, its memory is transplanted into the brain of the robot that is born at that moment. For example, when Robot #6 is born, Robots #2 and #3 are both resting, so Robot #6 inherits the memories of Robots #2 and #3. We call Robots #2 and #3 the **teachers** of Robot #6.\n\nIf two robots are neither in a teacher-student relationship nor share any common teachers, they are considered to have **independent knowledge**. **Note:** Robot #1 has independent knowledge with all other robots (because only Robot #1 produces other robots), and it is not the teacher of any robot.\n\nThe **independence count** of a robot is defined as the number of robots with smaller numbers that have independent knowledge from it. For example: \n- The independence count of Robot #1 is $0$. \n- The independence count of Robot #2 is $1$ (Robot #1 is independent of it). \n- The independence count of Robot #6 is $2$ (Robots #1 and #5 are independent of it; Robots #2 and #3 are its teachers, and Robot #4 shares a common teacher\u2014Robot #2\u2014with it).\n\nThere are three different professions for newly created robots: \n- For a robot numbered $m$, if $m$ can be expressed as the product of an **even number of distinct odd prime factors**, then it is a **Politician**, e.g., Robot #15. \n- Otherwise, if $m$ is an odd prime number itself or can be expressed as the product of an **odd number of distinct odd prime factors**, then it is a **Soldier**, e.g., Robot #3 or Robot #165. \n- Robots whose numbers belong to none of the above are **Scholars**, e.g., Robot #2, Robot #6, Robot #9.\n\nRobot #$m$, born in the $m$-th second, wants to know the sum of the independence counts of all **Politicians**, **Soldiers**, and **Scholars** among itself and its teachers. However, Robot #$m$ is too busy working to calculate this, and needs your help.\n\nFor convenience, Macsy has already performed the prime factorization of $m$. To simplify the output, your task is to return all sums **modulo $10000$**.\n\n---\n\n### Input Format\n\nThe first line of the input contains a positive integer $k$, representing the number of distinct prime factors of $m$.\n\nThe following $k$ lines each contain two integers $p_i$ and $e_i$, representing the $i$-th prime factor of $m$ and its exponent $(i=1,2,\\ldots,k)$. \nThe numbers $p_1, p_2, \\ldots, p_k$ are distinct primes where $\\prod_{i=1}^k p_i^{e_i} = m$. \nThe prime factors are given in increasing order: $p_1 < p_2 < \\ldots < p_k$.\n\n---\n\n### Output Format\n\nPrint the output in three lines:\n\n1. The first line contains the sum of the independence counts of all **Politicians** among Robot #$m$ and its teachers, modulo $10000$. \n2. The second line contains the sum of the independence counts of all **Soldiers** among Robot #$m$ and its teachers, modulo $10000$. \n3. The third line contains the sum of the independence counts of all **Scholars** among Robot #$m$ and its teachers, modulo $10000$.\n\n---\n\n### Example\n\nGiven $m = 2 \\times 3^2 \\times 5 = 90$, Robot #90 has 10 teachers, and including itself, there are 11 robots in total: \n- Politicians: Robot #15 \n- Soldiers: Robots #3 and #5 \n- Scholars: Robots #2, #6, #9, #10, #18, #30, #45, and #90.\n\n**Input**: \n```\n3 \n2 1 \n3 2 \n5 1\n```**Output**: \n```\n15 \n16 \n38\n```\n\n---\n\n### Constraints and Notes\n\nFor all test cases: \n- $1 \\leq k \\leq 1000$ \n- $2 \\leq p_i < 10000$ \n- $1 \\leq e_i \\leq 10^6$\n\nYour score for a test case depends on how many of the three outputs you correctly calculate, as shown in the following table:\n\n| $x$ | Score |\n| :--: | :--: |\n| 3 | 10 |\n| 2 | 7 |\n| 1 | 4 |\n| 0 | 0 |\n\n**Note**: Even if you cannot solve a particular case, please make sure to output one number per line (even if it's incorrect), or else the checker will not grade your solution.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2500, "prompt": "### Problem Description\n\nFlappy Bird is a popular casual mobile game in which players must control the frequency of tapping the screen to adjust the bird's flight height, allowing it to pass through the gaps between the pipes on the right side of the screen. If the bird accidentally hits a pipe or falls to the ground, the game ends unsuccessfully. \n\nTo simplify the problem, the game's rules have been simplified and modified as follows:\n\n1. The game is played on a 2D plane with a width of $n$ and a height of $m$, and there are $k$ pipes in the game (pipe width can be ignored). \n2. The bird always moves within the game interface. The bird starts at an arbitrary integer height on the leftmost side of the game interface and finishes the game upon reaching the rightmost side.\n3. At each unit of time, the bird moves 1 unit distance horizontally along the x-axis. Its vertical movement is controlled by the player. If the screen is tapped, the bird rises by a certain height $X$. Multiple taps per unit time are allowed, and their effects are additive. If the screen is not tapped, the bird descends by a certain height $Y$. The rise height $X$ and fall height $Y$ may vary depending on the bird\u2019s x-coordinate position.\n4. The game ends unsuccessfully if the bird\u2019s height becomes $0$ or if it hits a pipe. When the bird's height reaches $m$, it cannot rise further.\n\nYour goal is to determine whether the game can be completed successfully. If it can, output the minimum number of screen taps required; otherwise, output the maximum number of pipe gaps the bird can pass through.\n\n---\n\n### Input Format\n\nThe first line contains 3 integers $n$, $m$, and $k$, representing the length and height of the game interface and the number of pipes, respectively, separated by a space.\n\nThe next $n$ lines each contain 2 integers $X$ and $Y$, separated by a space, representing the height $X$ the bird rises after tapping the screen and the height $Y$ the bird falls if the screen is not tapped, for each x-coordinate position from $0$ to $n-1$. \n\nThe following $k$ lines each contain 3 integers $P$, $L$, and $H$, separated by a space. Each line represents a pipe where $P$ is the x-coordinate of the pipe, $L$ is the lower bound of the pipe gap, and $H$ is the upper bound of the pipe gap (the input guarantees that the $P$ values are distinct but not necessarily sorted in order).\n\n---\n\n### Output Format\n\nThe output consists of two lines:\n\nThe first line contains a single integer. Output $1$ if the game can be successfully completed; otherwise, output $0$. \n\nThe second line contains a single integer. If the first line is $1$, output the minimum number of screen taps required to successfully complete the game; otherwise, output the maximum number of pipe gaps the bird can pass through.\n\n---\n\n### Example 1\n\n```\nInput:\n\n[Example Input]\n\nOutput:\n\n[Example Output]\n```---\n\n### Example 2\n\n```\nInput:\n\n[Example Input]\n\nOutput:\n\n[Example Output]\n```\n\n---\n\n### Constraints and Hints\n\n- For $30\\%$ of the test cases: $5 \\leq n \\leq 10, 5 \\leq m \\leq 10, k = 0$, and it is guaranteed that there exists an optimal solution where the maximum number of screen taps per unit time is $3$. \n- For $50\\%$ of the test cases: $5 \\leq n \\leq 20, 5 \\leq m \\leq 10$, and it is guaranteed that there exists an optimal solution where the maximum number of screen taps per unit time is $3$. \n- For $70\\%$ of the test cases: $5 \\leq n \\leq 1000, 5 \\leq m \\leq 100$. \n- For $100\\%$ of the test cases: $5 \\leq n \\leq 10000$, $5 \\leq m \\leq 1000$, $0 \\leq k < n$, $0 < X < m$, $0 < Y < m$, $0 < P < n$, $0 \\leq L < H \\leq m$, $L + 1 < H$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2588, "prompt": "### Problem Description\n\nCountries R and S are currently at war, with both deploying spies to infiltrate the other side's territory and take action when the opportunity arises. \nAfter a perilous journey, spy C from R successfully uncovered the cipher rules used for military communication in country S:\n\n1. The original message intended to be sent internally by S's military is encrypted before being transmitted on the network. Both the original message and the encrypted message consist of uppercase letters $A-Z$ (no spaces or other characters).\n2. Each letter has a corresponding \"cipher letter\" defined by S's military. The encryption process replaces every letter in the original message with its corresponding \"cipher letter.\"\n3. Each letter has a unique corresponding cipher letter, and different letters correspond to different cipher letters. A cipher letter may be the same as the original letter.\n\nFor example, if $\\texttt{A}$ is encrypted to $\\texttt{A}$, and $\\texttt{B}$ is encrypted to $\\texttt{C}$ (other letters and their cipher letters omitted), then the original message $\\texttt{ABA}$ is encrypted to $\\texttt{ACA}$.\n\nWith access to one encrypted message along with its corresponding original message, spy C hopes to decode the military cipher rules used by S. Spy C's deciphering process involves scanning the original message, identifying each letter $x$ (any uppercase letter) in the original message, and mapping it to its corresponding letter $y$ in the encrypted message. Thus, $y$ is considered the cipher letter for $x$. The process stops when the deciphering results in one of the following states:\n\n1. The entire message has been scanned, and all $26$ letters $\\texttt{A,B,...,Z}$ in the original message have been successfully mapped to their corresponding \"cipher letters.\"\n2. The entire message has been scanned, but some letters do not appear in the original message.\n3. Contradictions or errors are identified in the scanned information that violate the cipher rules of country S. For example, an encrypted message $\\texttt{XYZ}$ translated into $\\texttt{ABA}$ violates the rule that \"different letters correspond to different cipher letters.\"\n\nAmidst the hectic deciphering process, R's headquarters sent a telegram to Spy C asking him to translate another newly intercepted encrypted message from S. \nPlease help Spy C: Decode the cipher using the intercepted information and use it to translate the encrypted message.\n\n---\n\n### Input Format\n\nThe input consists of $3$ lines, each containing a string. \n- The $1^\\text{st}$ line is the encrypted message intercepted by Spy C.\n- The $2^\\text{nd}$ line is the original message corresponding to the encrypted message from the $1^\\text{st}$ line.\n- The $3^\\text{rd}$ line is the encrypted message to be translated, as requested by R's headquarters.\n\n---\n\n### Output Format\n\nThe output contains $1$ line. \nIf the decoding process stops at states $2$ or $3$, output `Failed` (note: the first letter must be uppercase, and the rest must be lowercase). \nOtherwise, output the translated original message of the encrypted message specified in the $3^\\text{rd}$ line.\n\n---\n\n### Sample\n\n#### Sample Input 1 \n```plain\nAA\nAB\nEOWIE\n```#### Sample Output 1 \n```plain\nFailed\n```\n\n#### Explanation for Sample 1\n\nIn the original message, letters $\\texttt{A}$ and $\\texttt{B}$ correspond to the same cipher letter, violating the rules. Hence, the output is `Failed`.\n\n---\n\n#### Sample Input 2\n```plain\nQWERTYUIOPLKJHGFDSAZXCVBN\nABCDEFGHIJKLMNOPQRSTUVWXY\nDSLIEWO\n```\n\n#### Sample Output 2\n```plain\nFailed\n```\n\n#### Explanation for Sample 2\n\nThe letter $\\texttt{Z}$ does not appear in the original message. Hence, the output is `Failed`.\n\n---\n\n#### Sample Input 3\n```plain\nMSRTZCJKPFLQYVAWBINXUEDGHOOILSMIJFRCOPPQCEUNYDUMPP\nYIZSDWAHLNOVFUCERKJXQMGTBPPKOIYKANZWPLLVWMQJFGQYLL\nFLSO\n```\n\n#### Sample Output 3\n```plain\nNOIP\n```\n\n---\n\n### Constraints and Notes\n\nFor all test cases:\n- All strings consist only of uppercase English letters.\n- The length of each string is between $1$ and $100$.\n- The lengths of the strings in the $1^\\text{st}$ and $2^\\text{nd}$ lines are guaranteed to be equal.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 2357, "prompt": "### Problem Description\nIn the Magic Land, a notorious thief named Frank has surfaced, stealing confidential documents from government agencies across the kingdom. Some suspect that Frank might be an enemy spy. \nTo apprehend Frank, Magic Land's Security Bureau has launched a decisive operation!\n\nMagic Land consists of $N$ cities connected exactly by $N-1$ roads, ensuring that any two cities can be reached via the roads. From a data structure perspective, the $N$ cities and $N-1$ roads form a **tree**. \nFor instance, the diagram below shows a possible layout of Magic Land (4 cities denoted by numbers, connected by 3 roads denoted by letters):\n\n![Capture.JPG](https://i.loli.net/2018/02/12/5a8151a539c8f.jpg)\n\nFrank can move along the roads at any speed he desires. \nFor example, in the layout above, Frank can travel from city $1$ to city $4$ via city $2$ in $0.00001$ seconds (or within any arbitrarily small time), traversing two roads.\n\nCapturing Frank alive is a daunting task, so the Security Bureau has dispatched highly skilled detectives with extraordinary tracking abilities:\n- If a detective and Frank are in the same city, the detective will immediately detect and capture Frank.\n- Although Frank can move quickly along the roads, a detective will still detect and capture Frank if they encounter him while traveling on the same road.\n\nThe Security Bureau has no information about Frank's exact location\u2014he could be hiding in any city or traveling along any road. Therefore, a detailed capture plan must be devised consisting of several steps. During each step, you can perform one of the following actions:\n- **Deploy a detective at a city.** A detective can directly parachute into any city in Magic Land from headquarters. This operation is denoted by ```L x```, meaning a detective is deployed to city $x$. This takes $1$ second.\n- **Recall a detective from a city.** A detective stationed at a city can be summoned back to headquarters for re-deployment later. This operation is denoted by ```B x```, meaning a detective is recalled from city $x$. This takes $1$ second.\n- **Move a detective along a road.** A detective stationed at city $x$ can move along a connected road to city $y$. This operation is denoted by ```M x y```, meaning the detective moves from city $x$ to city $y$. This takes $1$ second. If Frank happens to be traveling along the same road at the same time, he will be captured.\n\nYour task is to devise a capture plan comprising several steps, ensuring that:\nNo matter where Frank initially hides or how cleverly he moves (Frank may even acquire the capture plan, so he will try his best to evade capture), he will inevitably be captured. \nThe number of involved detectives should be minimized because experienced detectives are scarce.\n\nFor instance, consider the example layout above. A possible valid capture plan:\n1. ```L 2```: Deploy a detective to city $2$. After this step, Frank cannot be hiding in city $2$, or he would already have been captured.\n2. ```L 2```: Deploy another detective to city $2$.\n3. ```M 2 1```: Have one detective from city $2$ move to city $1$. Note that one detective still remains in city $2$. After this step, Frank cannot be hiding in city $1$ or traveling along road $A$. Thus, if Frank has not been captured yet, he must be hiding in city $3$ or city $4$, or traveling along road $B$ or road $C$.\n4. ```B 1```: Recall a detective from city $1$. Although the detective has been recalled, one detective stationed at city $2$ ensures Frank cannot travel to city $1$ or road $A$.\n5. ```L 3```: Deploy a detective to city $3$. This could be the detective recalled earlier. After this step, Frank cannot be hiding in city $3$, or he would already have been captured.\n6. ```M 3 2```: Have one detective from city $3$ move back to city $2$. After this step, if Frank has not been captured yet, he must be traveling along road $C$ or hiding in city $4$. Note that after this step, two detectives are stationed at city $2$.\n7. ```M 2 4```: Have one detective from city $2$ move to city $4$. After this step, Frank will surely be captured, unless he was never in Magic Land to begin with. \nThis plan involves a total of $2$ detectives and guarantees capturing Frank. It can be proven that using $1$ or fewer detectives is insufficient for capturing Frank.\n\nYour simple mission: Given an input representing Magic Land's layout, determine $S$, the minimum number of detectives required to apprehend Frank, and provide the detailed steps for the capture plan.\n\n---\n\n### Input Format\nThe input describes the layout of Magic Land: \nThe first line contains an integer $N$, representing the number of cities, numbered $1, 2, \\dots, N$. \nThe next $N-1$ lines each contain two integers $x_i, y_i$, indicating that cities $x_i$ and $y_i$ are connected by a road. It is guaranteed that $1 \\leqslant x_i, y_i \\leqslant N$.\n\n---\n\n### Output Format\nOutput the devised capture plan as follows: \nThe first line should contain an integer $S$, representing the minimum number of detectives required. \nThe second line should contain an integer $T$, representing the total number of steps in the capture plan. \nThe next $T$ lines should describe the steps in the plan, where each line will be one of the following:\n- ```L x```, where ```L``` is a capital letter followed by a space and then an integer $x$, indicating a detective being deployed to city $x$. Ensure $1 \\le x \\le N$.\n- ```B x```, where ```B``` is a capital letter followed by a space and then an integer $x$, indicating a detective being recalled from city $x$. Ensure $1 \\le x \\le N$, and ensure city $x$ has at least one detective present before this step.\n- ```M x y```, where ```M``` is a capital letter followed by a space, an integer $x$, another space, and an integer $y$, indicating a detective moving from city $x$ to city $y$. Ensure $1 \\leq x, y \\leq N$, and ensure city $x$ has at least one detective before this step, and that cities $x$ and $y$ are directly connected by a road.\n\nOutput must ensure that $S$ matches the actual number of detectives involved in the capture plan.\n\n---\n\n### Example \n\n#### Input\n```\n4\n1 2\n2 3\n2 4\n```#### Output\n```\n2\n7\nL 2\nL 2\nM 2 1\nB 1\nL 3\nM 3 2\nM 2 4\n```\n\n---\n\n### Constraints and Hints \n#### Data Constraints\nThe input is guaranteed to represent a connected tree with $N$ nodes, $1 \\le N \\le 1000$. \n\n#### Scoring Standards\nFor each test case:\n- If the output plan is invalid, the total number of steps $T$ exceeds $20000$, or the plan fails to guarantee Frank's capture, the case scores $0$. \n- Otherwise, compare your output $S$ with the known optimal solution $S^*$:\n - If $S < S^*$: **100% of points**.\n - If $S = S^*$: **100% of points**.\n - If $S^* < S \\leq S^* + 2$: **60% of points**.\n - If $S^* + 2 < S \\leq S^* + 4$: **40% of points**.\n - If $S^* + 4 < S \\leq S^* + 8$: **20% of points**.\n - If $S > S^* + 8$: **10% of points**.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3850, "prompt": "### Problem Description\n\nZhu Youyang is a laid-back university student who still dreams of solving NPC problems in polynomial time every day.\n\nIn class, Zhu Youyang learned that the subgraph isomorphism problem is an NPC problem. He plans to present a polynomial-time decision algorithm for the subgraph isomorphism problem as indirect evidence to prove \\( P = NP \\). If successful, he could win the prestigious Turing Award for this groundbreaking work! Unfortunately, Zhu Youyang\u2019s knowledge is limited, and he hasn\u2019t even figured out why the subgraph isomorphism problem belongs to NPC. Thus, he decided to settle for solving a simpler problem:\n\nGiven two rooted trees \\( G \\) and \\( H \\), where \\( \\lvert G \\rvert \\) represents the number of nodes in tree \\( G \\). These two trees satisfy the following constraints: \\( 1 \\leq \\lvert H \\rvert \\leq \\lvert G \\rvert \\leq \\lvert H \\rvert + k \\). Here \\( k \\) is guaranteed by Zhu Youyang to be a small constant.\n\nZhu Youyang can delete any nodes from \\( G \\), resulting in a subgraph \\( G' \\). He wants to know whether there exists a way of deleting nodes such that the resulting subgraph \\( G' \\) meets the following conditions:\n\n- \\( G' \\) is connected.\n- \\( G' \\) includes the root node of \\( G \\) (i.e., the root node of \\( G \\) is not deleted).\n- \\( G' \\) is isomorphic to \\( H \\) (i.e., there exists a way to relabel the nodes of \\( G' \\) such that the relabeled graph is identical to \\( H \\), and the root node of \\( G \\) maps to the root node of \\( H \\)).\n\n---\n\n### Input Format\n\nRead input data from the file `iso.in`.\n\nThe problem contains multiple test cases.\n\nThe first line of input contains two positive integers \\( C, T \\) and one non-negative integer \\( k \\). These three numbers represent the test point number, the number of test data cases, and a given constant in the problem. If the current test case is a sample, then \\( C = 0 \\). It is guaranteed that \\( T \\leq 500 \\) and \\( k \\leq 5 \\).\n\nFor each test case:\n\n- The first line contains a positive integer \\( n_1 \\), representing the number of nodes in tree \\( G \\). It is guaranteed that \\( 1 \\leq n_1 \\leq 10^5 \\), and \\( \\sum n_1 \\leq 5 \\times 10^5 \\).\n- The second line contains \\( n_1 \\) integers describing the structure of tree \\( G \\). Specifically, the \\( i \\)-th (\\( 1 \\leq i \\leq n_1 \\)) integer \\( a_i \\) represents the parent node of node \\( i \\) in \\( G \\). If the node is the root, then \\( a_i = -1 \\). It is guaranteed that under these rules, the input forms a connected rooted tree.\n- The third line contains a positive integer \\( n_2 \\), representing the number of nodes in tree \\( H \\). For all test cases, it is guaranteed that \\( \\max(1, n_1 - k) \\leq n_2 \\leq n_1 \\).\n- The fourth line contains \\( n_2 \\) integers describing the structure of tree \\( H \\). Specifically, the \\( i \\)-th (\\( 1 \\leq i \\leq n_2 \\)) integer \\( b_i \\) represents the parent node of node \\( i \\) in \\( H \\). If the node is the root, then \\( b_i = -1 \\). It is guaranteed that under these rules, the input forms a connected rooted tree.\n\n---\n\n### Output Format\n\nWrite output data to the file `iso.out`.\n\nFor each test case:\n\nOutput a single string. If there exists a way to delete nodes from \\( G \\) such that the three conditions above are simultaneously satisfied, output `Yes`; otherwise, output `No`.\n\n---\n\n### Sample 1\n\nIn the first test point, we delete node \\( 1 \\) from the first tree. The remaining tree is isomorphic to the second tree, both being rooted trees with two nodes; hence the output is `Yes`.\n\n![iso1.png](https://img.loj.ac.cn/2022/08/30/110da22a49785.png)\n\nIn the second test point, the depth of the first input tree is \\( 1 \\), but the depth of the second input tree is \\( 2 \\). Thus, no matter how we delete nodes from the first tree, its depth will not increase to \\( 2 \\). Therefore, the output is `No`.\n\n![iso2.png](https://img.loj.ac.cn/2022/08/30/5ad431b49689b.png)\n\nIn the third test point, both input trees are isomorphic to the tree shown below; hence the output is `Yes`.\n\n![iso3.png](https://img.loj.ac.cn/2022/08/30/58fdaeb100c53.png)\n\n---\n\n### Sample 2\n\nSee the files `iso/iso2.in` and `iso/iso2.ans` provided in the attachment. This sample data corresponds to test points \\( 7 \\sim 8 \\).\n\n---\n\n### Sample 3\n\nSee the files `iso/iso3.in` and `iso/iso3.ans` provided in the attachment. This sample data corresponds to test points \\( 9 \\sim 10 \\).\n\n---\n\n### Sample 4\n\nSee the files `iso/iso4.in` and `iso/iso4.ans` provided in the attachment. This sample data corresponds to test point \\( 13 \\).\n\n---\n\n### Constraints and Notes\n\nFor all test cases, \\( 1 \\leq T \\leq 500 \\), \\( 1 \\le n_2 \\leq n_1 \\leq 10^5 \\), \\( \\sum n_1 \\leq 5 \\times 10^5 \\), \\( 0 \\leq k \\leq 5 \\).\n\nThe data has no **targeted adversarial construction against any reasonable hash algorithm**, meaning that you don\u2019t need to worry excessively about losing points due to hash collisions.\n\nThe additional constraints for specific test points are as follows:\n\n| \\( n_1, n_2 \\) | \\( \\sum n_1 \\) | Test Points | \\( k \\) | Special Properties |\n|:----------------:|:-----------------------:|:---------------------:|:------------:|:---------------------------:|\n| \\( \\leq 8 \\) | \\( \\leq 500 \\) | \\( 1 \\sim 3 \\) | \\( \\leq 0 \\) | None |\n| \\( \\leq 8 \\) | \\( \\leq 500 \\) | \\( 4 \\sim 6 \\) | \\( \\leq 5 \\) | None |\n| \\( \\leq 16 \\) | \\( \\leq 10^3 \\) | \\( 7 \\sim 8 \\) | \\( \\leq 0 \\) | None |\n| \\( \\leq 16 \\) | \\( \\leq 10^3 \\) | \\( 9 \\sim 10 \\) | \\( \\leq 5 \\) | None |\n| \\( \\leq 150 \\) | \\( \\leq 10^4 \\) | \\( 11 \\) | \\( \\leq 0 \\) | None |\n| \\( \\leq 150 \\) | \\( \\leq 10^4 \\) | \\( 12 \\) | \\( \\leq 1 \\) | None |\n| \\( \\leq 150 \\) | \\( \\leq 10^4 \\) | \\( 13 \\) | \\( \\leq 5 \\) | None |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 14 \\sim 16 \\) | \\( \\leq 0 \\) | A |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 17 \\sim 20 \\) | \\( \\leq 0 \\) | B |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 21 \\) | \\( \\leq 1 \\) | None |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 22 \\sim 23 \\) | \\( \\leq 3 \\) | None |\n| \\( \\leq 10^5 \\) | \\( \\leq 5 \\times 10^5 \\) | \\( 24 \\sim 25 \\) | \\( \\leq 5 \\) | None |\n\nThe special properties mentioned above are described as follows:\n\n- **Special Property A**: The rooted tree \\( G \\) ensures that each node is either a leaf node or has exactly \\( 1 \\) child node; equivalently, \\( G \\) forms a chain, and the root node is one end of the chain.\n- **Special Property B**: The rooted tree \\( G \\) ensures that each node is either a leaf node or has exactly \\( 2 \\) child nodes, and all leaf nodes have the same depth; equivalently, \\( G \\) forms a complete binary tree, and the root node is the root of the complete binary tree.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3536, "prompt": "### Problem Description\n\nYelekastee is a renowned archaeologist in the country U. During his recent archaeological expedition, he unearthed an ancient safe. After meticulous research, Yelekastee discovered that the password to the safe is associated with a sequence $\\{ a_n \\}$. The sequence $\\{ a_n \\}$ can be constructed as follows:\n\n1. Initially, the sequence has a length of $2$, with $a_0 = 0$ and $a_1 = 1$.\n2. The sequence undergoes a series of operations, where each operation is one of the following two types:\n - `W` type: Add $1$ to the **last element** of the sequence.\n - `E` type: If the **last element** of the sequence is $1$, add $1$ to the second-to-last element. Otherwise, subtract $1$ from the **last element**, then append two elements to the sequence, both with a value of $1$.\n\nDue to technical constraints, the safe cannot examine the entire sequence. Instead, the password is determined by applying a function $f$ to the sequence $\\{ a_n \\}$, where $f$ is defined as follows:\n\n$$ f(a_0, \\ldots , a_{k - 1}, a_k) = \\begin{cases} a_0, & k = 0 \\\\ f \\! \\left( a_0, a_1, \\ldots , a_{k - 2}, a_{k - 1} + \\frac{1}{a_k} \\right) \\! , & k \\ge 1 \\end{cases} $$\n\nYelekastee is not skilled in calculations, so he sought your help to compute the password of the safe based on a sequence of operations he provides. Unfortunately, his memory is not very reliable, and he may change the operation sequence at any time. These changes are of the following three types:\n\n- `APPEND c`: Append an operation of type `c` to the end of the current sequence, where `c` is a character `W` or `E`.\n- `FLIP l r`: Reverse the type of every operation from the $l$-th to the $r$-th (inclusive, 1-based index) in the current sequence \u2014 in other words, change all `W` to `E` and all `E` to `W`.\n- `REVERSE l r`: Reverse the order of operations from the $l$-th to the $r$-th (inclusive, 1-based index) in the current sequence.\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $q$, representing the initial length of the operation sequence and the number of modifications.\n\nThe second line contains a string of length $n$ consisting only of uppercase letters `W` and `E`, representing the initial operation sequence.\n\nThe following $q$ lines each describe one modification, formatted as described in the problem description.\n\n### Output Format\n\nOutput a total of $q + 1$ lines. The first line contains two integers representing the password of the safe for the initial operation sequence. The next $q$ lines each contain two integers, representing the password of the safe after each modification.\n\nThe password is guaranteed to be a positive rational number. If the actual password is $\\frac{a}{b}$, where $a, b > 0$ and $\\gcd(a, b) = 1$, then you must output $a$ and $b$ modulo $998244353$ on the corresponding line.\n\n**Explanation of Sample #1**\n\n| | Operation Sequence | Sequence $\\{ a_n \\}$ | Password |\n|:-:|:-:|:-:|:-:|\n| Initial | `WE` | $(0, 1, 1, 1)$ | $\\frac{2}{3}$ |\n| After 1st modification | `WEE` | $(0, 1, 2, 1)$ | $\\frac{3}{4}$ |\n| After 2nd modification | `EWE` | $(1, 1, 1, 1)$ | $\\frac{5}{3}$ |\n| After 3rd modification | `EEW` | $(2, 2)$ | $\\frac{5}{2}$ |\n\n**Sample #2**\n\nSee the file `code/code2.in` and `code/code2.ans`.\n\nThis sample satisfies the same constraints as test cases $1 \\sim 4$.\n\n**Sample #3**\n\nSee the file `code/code3.in` and `code/code3.ans`.\n\nThis sample satisfies the same constraints as test cases $5 \\sim 7$.\n\n**Sample #4**\n\nSee the file `code/code4.in` and `code/code4.ans`.\n\nThis sample satisfies the same constraints as test cases $8 \\sim 10$.\n\n**Sample #5**\n\nSee the file `code/code5.in` and `code/code5.ans`.\n\nThis sample satisfies the same constraints as test cases $15 \\sim 20$.\n\n---\n\n### Constraints\n\nFor all test cases: $1 \\le n \\le {10}^5$, $1 \\le q \\le {10}^5$.\n\nFor the `APPEND` operation, it is guaranteed that `c` is either the uppercase English letter `W` or `E`.\n\nFor the `FLIP` and `REVERSE` operations, it is guaranteed that $1 \\le l \\le r \\le L$ where $L$ is the current length of the operation sequence.\n\nNote that due to the `APPEND` operation, the length of the operation sequence can grow up to a maximum of $2 \\times {10}^5$.\n\n| Test Case Range | $n, q \\le$ | Special Constraints |\n|:-:|:-:|:-:|\n| $1 \\sim 4$ | $2000$ | None |\n| $5 \\sim 7$ | ${10}^5$ | A |\n| $8 \\sim 10$ | ${10}^5$ | B, C |\n| $11 \\sim 14$ | ${10}^5$ | C |\n| $15 \\sim 20$ | ${10}^5$ | None |\n\nSpecial Constraint A: The operation sequence never contains two consecutive identical characters at any time.\n\nSpecial Constraint B: No `FLIP` modification occurs in this case.\n\nSpecial Constraint C: No `REVERSE` modification occurs in this case.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2590, "prompt": "### Problem Description\nCountry C has $n$ major cities and $m$ roads, where each road connects two of these cities. There is at most one road directly connecting any pair of cities. Among these $m$ roads, some are one-way roads, while others are two-way roads. Note that a two-way road is also counted as one road in the total count.\n\nCountry C spans a vast territory, with resources distributed unevenly across different regions. This results in the price of a particular commodity not necessarily being the same in different cities. However, the buying and selling price of the same commodity in the same city is always the same.\n\nA merchant, Alon, is visiting Country C for tourism. Upon learning that the price of the same commodity can differ among cities, he decides to make some extra money to cover his travel expenses by taking advantage of the price differences while traveling. Suppose the cities in Country C are numbered from $1$ to $n$. Alon plans to start his journey in City $1$ and end it at City $n$. During his journey, he may visit any city multiple times but is not required to visit all $n$ cities.\n\nAlon earns travel expenses by trading in his favorite commodity\u2014a crystal ball. He will select a city that he passes through to purchase the crystal ball and then sell it in a subsequent city he visits, making a profit from the price difference. Since Alon\u2019s primary purpose is tourism, he decides to perform this trade at most once. If he cannot make a profit, he will opt not to trade.\n\nConsider an example where Country C has $5$ cities, and the roads connecting them are depicted in the diagram below. A unidirectional arrow represents a one-way road, while a bidirectional arrow represents a two-way road.\n\n![27.png](https://i.loli.net/2018/05/22/5b03da6422dfe.png)\n\nSuppose the crystal ball prices for Cities $1$ through $n$ are $4,3,5,6,1$ respectively.\n\nAlon can choose the route $1 \\to 2 \\to 3 \\to 5$, where he buys a crystal ball in City $2$ at a price of $3$ and sells it in City $3$ at a price of $5$, earning a profit of $2$.\n\nAlternatively, Alon could choose the route $1 \\to 4 \\to 5 \\to 4 \\to 5$. In this case, he buys the crystal ball at City $5$ for $1$ upon his first visit there and sells it at City $4$ for $6$ during his second visit, earning a profit of $5$.\n\nGiven the crystal ball prices in all $n$ cities and the information about the $m$ roads (the cities they connect and their transport direction), your task is to determine the maximum profit Alon can earn. If no profit can be made, output $0$.\n\n---\n\n### Input Format\nThe first line contains two positive integers $n$ and $m$, separated by a space, representing the number of cities and the number of roads, respectively.\n\nThe second line contains $n$ positive integers, separated by spaces, representing the commodity prices in the $n$ cities in order of their city numbers.\n\nThe next $m$ lines each contain three positive integers $x, y, z$, separated by spaces:\n- If $z=1$, it indicates a one-way road from City $x$ to City $y$.\n- If $z=2$, it indicates a two-way road between City $x$ and City $y$.\n\n---\n\n### Output Format\nOutput a single integer: the maximum profit Alon can earn. If no profitable trade can be made, output $0$.\n\n---\n\n### Sample Input\n```plain\n5 5\n4 3 5 6 1\n1 2 1\n1 4 1\n2 3 2\n3 5 1\n4 5 2\n```### Sample Output\n```plain\n5\n```\n\n---\n\n### Constraints and Hints\n- The input guarantees that City $1$ can reach City $n$.\n- For $10\\%$ of the cases, $n \\leq 6$.\n- For $30\\%$ of the cases, $n \\leq 100$.\n- For $50\\%$ of the cases, it is guaranteed that there does not exist a travel route that starts and ends at the same city.\n- For $100\\%$ of the cases:\n - $1 \\leq n \\leq 100,000$\n - $1 \\leq m \\leq 500,000$\n - $1 \\leq x, y \\leq n$\n - $1 \\leq z \\leq 2$\n - $1 \\leq$ price of crystal balls in each city $\\leq 100$\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2362, "prompt": "### Problem Description\n> Cricket Kingdom is currently suffering from a rampant outbreak of earthworms! The fleas from Flea Kingdom next door are also helpless against the earthworms, so the King of Cricket Kingdom decided to enlist the help of the Divine Sword Master to eliminate the earthworms.\n\nIn this problem, the symbol $ \\lfloor c \\rfloor $ is used to denote the floor function, which rounds $ c $ down to the nearest integer. For example: $ \\lfloor 3.0 \\rfloor = \\lfloor 3.1 \\rfloor = \\lfloor 3.9 \\rfloor = 3 $.\n\nThere are a total of $ n $ earthworms in Cricket Kingdom (where $ n $ is a positive integer). Each earthworm has a length, and the $ i $-th earthworm's length is denoted by $ a_i $ ($ i = 1, 2, \\ldots, n $). All lengths are guaranteed to be non-negative integers (i.e., an earthworm with a length of $ 0 $ is possible).\n\nEvery second, the Divine Sword Master will find the longest earthworm among all the earthworms (if there are ties, any one of the longest earthworms may be chosen) and cut it into two pieces. The position where the worm is cut is determined by a constant $ p $ (a rational number satisfying $ 0 < p < 1 $). If the worm's length is $ x $, it will be split into two new worms with lengths $ \\lfloor px \\rfloor $ and $ x - \\lfloor px \\rfloor $, respectively. Notably, if either of these two numbers equals $ 0 $, the new worm of length $ 0 $ will also be retained. Additionally, all other earthworms grow in length by $ q $ (a non-negative constant) every second except for the two newly generated worms.\n\nThe King of Cricket Kingdom knows that this situation cannot be sustained indefinitely because the number of worms and their lengths will only increase. He plans to seek aid from a mysterious figure with mystical powers, but the help will arrive only after $ m $ seconds\u2026\u2026 (where $ m $ is a non-negative integer).\n\nThe King of Cricket Kingdom wants to know what will happen during the $ m $ seconds before help arrives. Specifically, he wants the following information:\n\n* The lengths of the earthworms that were cut at each second during the $ m $ seconds (a total of $ m $ numbers).\n* The lengths of all the earthworms $ m $ seconds later (a total of $ n + m $ numbers).\n\nThe King of Cricket Kingdom obviously knows how to figure this out! But he wants to test your skills\u2026\n\n---\n\n### Input Format\nThe first line consists of six integers: $ n $, $ m $, $ q $, $ u $, $ v $, $ t $. Here:\n\n- $ n $, $ m $, and $ q $ have the same meaning as described in the \"Problem Description\".\n- $ u $ and $ v $ are both positive integers. You need to calculate $ p = \\frac{u}{v} $ (it is guaranteed that $ 0 < u < v $).\n- $ t $ is a positive integer, and its meaning will be explained in the \"Output Format\" section.\n\nThe second line contains $ n $ non-negative integers, representing the initial lengths of the $ n $ earthworms: $ a_1, a_2, \\ldots, a_n $.\n\nThe integers on the same line are separated by a single space.\n\nIt is guaranteed that:\n- $ 1 \\leq n \\leq 10 ^ 5$\n- $ 0 < m < 7 \\times 10 ^ 6 $\n- $ 0 < u < v < 10 ^ 9 $\n- $ 0 \\leq q \\leq 200 $\n- $ 1 < t < 71 $\n- $ 0 < a_i < 10 ^ 8 $\n\n---\n\n### Output Format\nThe first line should output $ \\lfloor \\frac{m}{t} \\rfloor $ integers. These integers represent the lengths of the earthworms that were cut at the $ t $-th second, $ 2t $-th second, $ 3t $-th second, and so on, in chronological order.\n\nThe second line should output $ \\lfloor \\frac{(n+m)}{t} \\rfloor $ integers. These integers represent the lengths of the earthworms after $ m $ seconds, sorted in descending order, and correspond to the $ t $-th largest length, $ 2t $-th largest length, $ 3t $-th largest length, and so on.\n\nThe integers on the same line should be separated by a single space. Even if a specific line contains no integers to output, you must still output an empty line.\n\nPlease refer to the examples below for a better understanding of the format.\n\n---\n\n### Sample 1\nBefore the Divine Sword Master arrives, the lengths of the 3 earthworms are $ 3, 3, 2 $.\n\n- After 1 second: One earthworm of length $ 3 $ is cut into two new earthworms of lengths $ 1 $ and $ 2 $. The remaining earthworms' lengths increase by $ 1 $. The final lengths of the 4 earthworms are $ (1, 2), 4, 3 $, where parentheses indicate the newly generated worms.\n \n- After 2 seconds: One earthworm of length $ 4 $ is cut into $ 1 $ and $ 3 $. The lengths of the resulting 5 earthworms are: $ 2, 3, (1, 3), 4 $.\n\n- After 3 seconds: One earthworm of length $ 4 $ is cut. The lengths of the resulting 6 earthworms are: $ 3, 4, 2, 4, (1, 3) $.\n\n- After 4 seconds: One earthworm of length $ 4 $ is cut. The lengths of the resulting 7 earthworms are: $ 4, (1, 3), 3, 5, 2, 4 $.\n\n- After 5 seconds: One earthworm of length $ 5 $ is cut. The lengths of the resulting 8 earthworms are: $ 5, 2, 4, 4, (1, 4), 3, 5 $.\n\n- After 6 seconds: One earthworm of length $ 5 $ is cut. The lengths of the resulting 9 earthworms are: $ (1, 4), 3, 5, 5, 2, 5, 4, 6 $.\n\n- After 7 seconds: One earthworm of length $ 6 $ is cut. The lengths of the resulting 10 earthworms are: $ 2, 5, 4, 6, 6, 3, 6, 5, (2, 4) $.\n\nThus, during these 7 seconds, the lengths of the earthworms that were cut are $ 3, 4, 4, 4, 5, 5, 6 $. After 7 seconds, the lengths of all the earthworms sorted in descending order are $ 6, 6, 6, 5, 5, 4, 4, 3, 2, 2 $.\n\n---\n\n### Sample 2\nIn this test case, only $ t = 2 $ differs from the previous test case. The output will include numbers at intervals of every two seconds instead of one.\n\nEven if the first line's last number $ 6 $ is not output, the second line must recompute and output the results starting from the second number onward.\n\n---\n\n### Sample 3\nIn this test case, only $ t = 9 $ differs from the previous test case.\n\nNote that the first line may have no numbers to output, but an empty line must still be printed.\n\n---\n\n### Constraints and Hints\n- $ 1 \\leq n \\leq 10 ^ 5 $\n- $ 0 \\leq m \\leq 7 \\times 10 ^ 6 $\n- $ 1 \\leq t \\leq 71 $\n- $ 0 \\leq a_i \\leq 10 ^ 8 $\n- $ 1 \\leq v \\leq 10 ^ 9 $\n- $ 0 \\leq q \\leq 200 $\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 4002, "prompt": "### Problem Description\n\nToday, Little L learned Kleene's three-valued logic.\n\nIn three-valued logic, the value of a variable can be: true ($\\mathit{True}$, abbreviated as $\\mathit{T}$), false ($\\mathit{False}$, abbreviated as $\\mathit{F}$), or unknown ($\\mathit{Unknown}$, abbreviated as $\\mathit{U}$).\n\nLogical operations can also be defined in three-valued logic. Since Little L learned at a slow pace, he only grasped the logic NOT operation $\\lnot$. Its rules of execution are:\n$$\\lnot \\mathit{T} = \\mathit{F}, \\lnot \\mathit{F} = \\mathit{T}, \\lnot\\mathit{U} = \\mathit{U}.$$\n\nNow, Little L has $n$ three-valued logic variables $x_1,\\cdots, x_n$. Little L decided to conduct some interesting experiments, so he wrote $m$ statements. The statements take the following three forms, where $\\leftarrow$ represents assignment:\n\n1. $x_i \\leftarrow v$, where $v$ is one of $\\mathit{T}, \\mathit{F}, \\mathit{U}$;\n2. $x_i \\leftarrow x_j$;\n3. $x_i \\leftarrow \\lnot x_j$.\n\nInitially, Little L will assign initial values to these variables, and then execute these $m$ statements sequentially.\n\nLittle L hopes that after all the statements are executed, the final values of all variables are the same as their initial values. Under this premise, Little L hopes to minimize the number of variables with $\\mathit{Unknown}$ initial values.\n\nIn this problem, you need to help Little L find an initial assignment scheme with the minimum number of $\\mathit{Unknown}$ variables, such that after executing all the statements, all variables\u2019 final values are the same as their initial values. Little L guarantees that for all the test cases in this problem, such an assignment scheme always exists.\n\n### Input Format\n\n**This problem\u2019s test cases include multiple groups of test data.**\n\nThe first line of input contains two integers $c$ and $t$, representing the test point ID and the number of test data groups respectively. In the samples, $c$ indicates that this sample has the same constraints as test point $c$.\n\nFor each group of test data:\n\n- The first line contains two integers $n$ and $m$, representing the number of variables and the number of statements respectively.\n- The next $m$ lines describe each statement in execution order:\n - The first character $v$ specifies the type of the statement. It is guaranteed that $v$ is one of `TFU+-`.\n - If $v$ is one of `TFU`, one integer $i$ follows, indicating the statement $x_i \\leftarrow v$;\n - If $v$ is `+`, two integers $i, j` follow, indicating the statement $x_i \\leftarrow x_j$;\n - If $v$ is `-`, two integers $i, j` follow, indicating the statement $x_i \\leftarrow \\lnot x_j$.\n\n### Output Format\n\nFor each test data group, output one integer on a separate line, representing the minimum number of $\\mathit{Unknown}$ variables in all valid initial assignment schemes.\n\n**\u3010Sample Explanation #1\u3011**\n\nIn the first group of test data, the $m$ statements are:\n\n- $x_2 \\leftarrow \\lnot x_1$;\n- $x_3 \\leftarrow \\lnot x_2$;\n- $x_1 \\leftarrow x_3$.\n\nA valid initial assignment scheme is $x_1 = \\mathit{T}, x_2 = \\mathit{F}, x_3 = \\mathit{T}$, with $0$ $\\mathit{Unknown}$ variables. Since no scheme has fewer than $0$ $\\mathit{Unknown}$ variables, the output is $0$.\n\nIn the second group of test data, the $m$ statements are:\n\n- $x_2 \\leftarrow \\lnot x_1$;\n- $x_3 \\leftarrow \\lnot x_2$;\n- $x_1 \\leftarrow \\lnot x_3$.\n\nThe only valid initial assignment scheme is $x_1 = x_2 = x_3 = \\mathit{U}$, with $3$ $\\mathit{Unknown}$ variables. Therefore, the output is $3$.\n\nIn the third group of test data, the $m$ statements are:\n\n- $x_2 \\leftarrow \\mathit{T}$;\n- $x_2 \\leftarrow \\mathit{U}$;\n\nOne valid assignment scheme minimizing the number of $\\mathit{Unknown}$ variables is $x_1 = \\mathit{T}, x_2 = \\mathit{U}$. $x_1 = x_2 = \\mathit{U}$ is also valid but does not minimize the number of $\\mathit{Unknown}$ variables.\n\n**\u3010Sample Explanation #2\u3011**\n\nThis sample satisfies the constraints of test point $2$.\n\n**\u3010Sample Explanation #3\u3011**\n\nThis sample satisfies the constraints of test point $5$.\n\n**\u3010Sample Explanation #4\u3011**\n\nThis sample satisfies the constraints of test point $8$.\n\n### Constraints\n\nFor all test data, it is guaranteed that:\n\n- $1 \\le t \\le 6$, $1 \\le n,m \\le 10 ^ 5$;\n- For each operation, $v$ is one of `TFU+-`, $1 \\le i,j \\le n$.\n\n| Test Point ID | $n,m\\leq$ | Possible Values of $v$ |\n| :------------: | :-------: | :--------------------: |\n| $1,2$ | $10$ | $\\mathit{TFU+-}$ |\n| $3$ | $10^3$ | $\\mathit{TFU}$ |\n| $4$ | $10^5$ | $\\mathit{TFU}$ |\n| $5$ | $10^3$ | $\\mathit{U+}$ |\n| $6$ | $10^5$ | $\\mathit{U+}$ |\n| $7$ | $10^3$ | $\\mathit{+-}$ |\n| $8$ | $10^5$ | $\\mathit{+-}$ |\n| $9$ | $10^3$ | $\\mathit{TFU+-}$ |\n| $10$ | $10^5$ | $\\mathit{TFU+-}$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3980, "prompt": "### Problem Description\n\nEight years ago, Xiao B saw an osmanthus tree which was a tree $T$ with $n$ nodes, where **it is guaranteed that the parent node of any non-root node has a smaller ID than that node itself**. Given an integer $k$, a tree $T^{\\prime}$ with $(n+m)$ nodes is called *prosperous* if and only if it satisfies all the following conditions:\n\n1. For any pair $(i, j)$ satisfying $1 \\le i, j \\le n$, the lowest common ancestor (LCA) of nodes $i$ and $j$ in both $T$ and $T^{\\prime}$ must have the same ID.\n2. For any pair $(i, j)$ satisfying $1 \\le i, j \\le n+m$, the LCA of nodes $i$ and $j$ in $T^{\\prime}$ must not exceed $\\max(i, j) + k$.\n\n**Note:** All tree nodes in this problem use 1-based indexing, and the root node is indexed as 1. Tree $T^{\\prime}$ is not required to satisfy the condition where the parent ID of a non-root node is smaller than its own ID.\n\nXiao B wants to know how many different trees with $(n+m)$ nodes are prosperous. Two trees are considered different if and only if there exists a node whose parent ID in the two trees is different. You should output the number of such prosperous trees modulo $(10^9 + 7)$.\n\n---\n\n### Input Format\n\n**This problem contains multiple test cases.**\n\nThe first line contains two integers $c, t$, indicating the test point index and the number of test cases respectively. If $c = 0$, the test point corresponds to the stated examples.\n\nFor each test case, the input is formatted as follows:\n\n- The first line of each test case contains three integers $n, m, k$.\n- The second line contains $(n-1)$ integers $f_2, f_3, \\dots, f_n$, where $f_i$ indicates the parent ID of node $i$ in $T$.\n\n---\n\n### Output Format\n\nFor each test case, output a single line containing one integer, which is the number of prosperous trees modulo $(10^9 + 7)$.\n\n---\n\n### **Sample Explanation #1**\n\nFor the first test case in the sample, there are three prosperous trees. The sequences of parent IDs $\\{f_2, f_3\\}$ for these trees are $\\{1,1\\}$, $\\{3,1\\}$, and $\\{1,2\\}$. Note that the second line of the input for this test case is empty.\n\nFor the second and third test cases in the sample, there are a total of $16$ prosperous trees that satisfy the first condition, but only those with a parent sequence $\\{4,4,1\\}$ fail to satisfy the second condition in the third test case.\n\n---\n\n### **Sample Explanation #2**\n\nFor this sample, $n \\leq 100$. Across the five test cases, the value of $m$ does not exceed $0, 1, 1, 2, 2$, respectively.\n\n---\n\n### **Sample Explanation #3**\n\nFor this group of test cases, $k = 0$. In the five test cases, both the first and second test cases satisfy $n = 1$, while the first, third, and fourth test cases satisfy $n, m \\leq 100$.\n\n---\n\n### **Sample Explanation #4**\n\nFor this group of test cases, the first two test cases satisfy $n = 1$, while the first, third, and fourth test cases satisfy $n, m \\leq 100$.\n\n---\n\n### **Constraints**\n\nFor all test data, the following conditions are guaranteed to hold: \n$1 \\le t \\le 15$, $1 \\le n \\le 3 \\times 10^4$, $0 \\le m \\le 3000$, $0 \\le k \\le 10$, $1 \\le f_i \\le i - 1$.\n\n| Test Point Index | $n \\leq$ | $m \\leq$ | $k \\leq$ |\n| :---: | :---: | :---: | :---: |\n| $1,2$ | $4$ | $4$ | $10$ |\n| $3$ | $3 \\times 10^4$ | $0$ | $10$ |\n| $4$ | $10^2$ | $1$ | $10$ |\n| $5$ | $3 \\times 10^4$ | $1$ | $10$ |\n| $6$ | $10^2$ | $2$ | $10$ |\n| $7$ | $3 \\times 10^4$ | $2$ | $10$ |\n| $8,9$ | $1$ | $10^2$ | $0$ |\n| $10$ | $1$ | $3,000$ | $0$ |\n| $11$ | $1$ | $10^2$ | $10$ |\n| $12$ | $1$ | $3,000$ | $10$ |\n| $13,14$ | $10^2$ | $10^2$ | $0$ |\n| $15,16$ | $3 \\times 10^4$ | $3,000$ | $0$ |\n| $17,18$ | $10^2$ | $10^2$ | $10$ |\n| $19,20$ | $3 \\times 10^4$ | $3,000$ | $10$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2952, "prompt": "### Problem Description\nCity C is planning to host a series of racing events. Before the events, it is necessary to construct $m$ tracks in the city.\n\nCity C consists of $n$ intersections, numbered as $1, 2, \\cdots, n$, connected by $n-1$ bidirectional roads that are suitable for track construction. Each road connects two intersections. Specifically, the $i$-th road connects intersections $a_i$ and $b_i$, and the length of the road is $l_i$. With the help of these $n-1$ roads, it is possible to travel between any two intersections.\n\nA track is defined as a sequence of distinct roads $e_1, e_2, \\cdots, e_k$ that allows one to start from a certain intersection and travel along roads $e_1, e_2, \\cdots, e_k$ (visiting each road once, without reversing direction) to reach another intersection. The length of a track is the total sum of the lengths of all roads it traverses. To ensure safety, each road can belong to at most one track.\n\nThe specific track construction plan has not yet been finalized. Your task is to design a plan to construct $m$ tracks such that the length of the shortest track among the $m$ tracks is maximized.\n\n---\n\n### Input Format\nThe name of the input file is `track.in`.\n\nThe first line of the input contains two space-separated positive integers $n$ and $m$, representing the number of intersections and the number of tracks to be constructed, respectively. \n\nThe next $n-1$ lines each contain three positive integers $a_i$, $b_i$, and $l_i$, representing that the $i$-th road connects intersections $a_i$ and $b_i$, and the length of the road is $l_i$. It is guaranteed that any two intersections can be reached from one another through these $n-1$ roads. Each line contains space-separated integers.\n\n---\n\n### Output Format\nThe name of the output file is `track.out`.\n\nThe output contains a single integer, representing the maximum value of the minimum track length among the constructed tracks.\n\n---\n\n### Sample 1\nAll intersections and roads suitable for track construction are shown in the following figure:\n\n![track1.png](https://i.loli.net/2018/11/25/5bfa35d26f803.png)\n\nThe numbers in parentheses indicate the road's index, and the other numbers represent the road's length.\n\nOne track needs to be constructed. A possible solution is constructing a track passing through roads $3, 1, 2, 6$ (from intersection $4$ to intersection $7$). The length of this track is $9 + 10 + 5 + 7 = 31$, which is the maximum value among all possible solutions.\n\n---\n\n### Sample 2\nAll intersections and roads suitable for track construction are shown in the following figure:\n\n![track2.png](https://i.loli.net/2018/11/25/5bfa35d282f80.png)\n\nThree tracks need to be constructed. A possible solution is constructing the following three tracks:\n1. A track passing through roads $1$ and $6$ (from intersection $1$ to intersection $7$) with a length of $6 + 9 = 15$;\n2. A track passing through roads $5, 2, 3, 8$ (from intersection $6$ to intersection $9$) with a length of $4 + 3 + 5 + 4 = 16$;\n3. A track passing through roads $7$ and $4$ (from intersection $8$ to intersection $5$) with a length of $7 + 10 = 17$.\n\nThe shortest track among the above three tracks has a length of $15$, which is the maximum possible value for the smallest track length.\n\n---\n\n### Constraints and Hints\nThe constraints and characteristics of the input data across all test cases are summarized in the following table:\n\n\n\n| Test Case ID | $n$ | $m$ | $a_i=1$ | $b_i=a_i+1$ | Branch Count $\\leq 3$ |\n|:-:|:-:|:-:|:-:|:-:|:-:|\n| $1$ | $\\leq 5$ | $=1$ | No | No | Yes |\n| $2$ | $\\leq 10$ | $\\leq n-1$ | No | Yes | Yes |\n| $3$ | $\\leq 15$ | $\\leq n-1$ | Yes | No | No |\n| $4$ | $\\leq 10^3$ | $=1$ | No | No | Yes |\n| $5$ | $\\leq 3\\times 10^4$ | $=1$ | Yes | No | No |\n| $6$ | $\\leq 3\\times 10^4$ | $=1$ | No | No | No |\n| $7$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | Yes | No | No |\n| $8$ | $\\leq 5\\times 10^4$ | $\\leq n-1$ | Yes | No | No |\n| $9$ | $\\leq 10^3$ | $\\leq n-1$ | No | Yes | Yes |\n| $10$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | No | Yes | Yes |\n| $11$ | $\\leq 5\\times 10^4$ | $\\leq n-1$ | No | Yes | Yes |\n| $12$ | $\\leq 50$ | $\\leq n-1$ | No | No | Yes |\n| $13$ | $\\leq 50$ | $\\leq n-1$ | No | No | Yes |\n| $14$ | $\\leq 200$ | $\\leq n-1$ | No | No | Yes |\n| $15$ | $\\leq 200$ | $\\leq n-1$ | No | No | Yes |\n| $16$ | $\\leq 10^3$ | $\\leq n-1$ | No | No | Yes |\n| $17$ | $\\leq 10^3$ | $\\leq n-1$ | No | No | No |\n| $18$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | No | No | No |\n| $19$ | $\\leq 3\\times 10^4$ | $\\leq n-1$ | No | No | No |\n| $20$ | $\\leq 5\\times 10^4$ | $\\leq n-1$ | No | No | No |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3156, "prompt": "### Problem Description\n\nIn the Cat Kingdom's railway system, there are $n$ stations, numbered from $1$ to $n$. Little Cat plans to depart from Station $1$ and take a train back to Cat Home at Station $n$. She has queried the train schedule, which includes $m$ trains numbered from $1$ to $m$. Little Cat will arrive at Station $1$ at time $0$. For Train $i$, it departs from Station $x_i$ at time $p_i$ and directly arrives at Station $y_i$ at time $q_i$. Little Cat can only board Train $i$ precisely at time $p_i$ and disembark at time $q_i$. She can reach Station $n$ by making multiple transfers between trains. \n\nA transfer between trains is defined as follows: For two trains $u$ and $v$, if $y_u = x_v$ and $q_u \\leq p_v$, then Little Cat can disembark from Train $u$ at Station $y_u$, wait for $p_v - q_u$ units of time at Station $y_u$, and then board Train $v$ at time $p_v$.\n\nLittle Cat wishes to minimize the hassle during her journey, which is measured using \"irritation value\".\n\n- Waiting at a station increases irritation value. For a waiting period of $t$ ($t \\geq 0$) units of time, the irritation value increases by $At^2 + Bt + C$, where $A, B, C$ are given constants. Note that waiting at Station $1$ from time $0$ until boarding the first train also counts as a waiting period.\n\n- If Little Cat finally reaches Station $n$ at time $z$, her irritation value further increases by $z$.\n\nFormally, if she takes a total of $k$ trains in sequential order specified by the sequence $s_1, s_2, \\cdots, s_k$, then this sequence is called a feasible route back home if and only if it satisfies the following two conditions:\n\n1. $x_{s1} = 1$, $y_{sk} = n$\n2. For all $j$ ($1 \\leq j < k$), $y_{sj} = x_{s_{j+1}}$ and $q_{sj} \\leq p_{s_{j+1}}$\n\nThe irritation value for such a route can be calculated as:\n\n$$q_{s_k}+(A \\times p_{s_1}^2 + B \\times p_{s_1} + C)+\\sum_{j=1}^{k-1}(A(p_{s_{j+1}} - q_{s_j})^2 + B(p_{s_{j+1}} - q_{s_j}) + C)$$\n\nLittle Cat wants to minimize her irritation value among all feasible routes back home. You are guaranteed that at least one feasible route exists.\n\n### Input Format\n\nThe first line contains five integers $n, m, A, B, C$, whose meanings are described in the problem statement.\n\nThe next $m$ lines each contain four integers $x_i, y_i, p_i, q_i$, indicating the starting station, destination station, departure time, and arrival time of the $i$-th train, respectively.\n\n### Output Format\n\nOutput a single integer, representing the minimum irritation value among all feasible routes.\n\n### Additional Samples\n\nYou can find extra samples through the accompanying files.\n\n#### Sample 3\n\nSee the attached file `route/route3.in` and its output `route/route3.ans`.\n\nThis sample has the same data types as final test cases $5 \\sim 8$.\n\n#### Sample 4\n\nSee the attached file `route/route4.in` and its output `route/route4.ans`.\n\nThis sample has the same data types as final test cases $11 \\sim 14$.\n\n#### Sample 5\n\nSee the attached file `route/route5.in` and its output `route/route5.ans`.\n\nThis sample has the same data types as final test cases $18 \\sim 20$.\n\n### Sample 1 Explanation\n\nThere are three feasible routes back home:\n\n- Take trains 1 and 4 in sequence, resulting in an irritation value of: $10 + (1 \\times 3^2 + 5 \\times 3 + 10) + (1 \\times (9 - 4)^2 + 5 \\times (9 - 4) + 10) = 104$\n- Take trains 2 and 4 in sequence, resulting in an irritation value of: $10 + (1 \\times 5^2 + 5 \\times 5 + 10) + (1 \\times (9 - 7)^2 + 5 \\times (9 - 7) + 10) = 94$\n- Take trains 3 and 4 in sequence, resulting in an irritation value of: $10 + (1 \\times 6^2 + 5 \\times 6 + 10) + (1 \\times (9 - 8)^2 + 5 \\times (9 - 8) + 10) = 102$\n\nThe second route produces the smallest irritation value, which is $94$.\n\n### Constraints\n\nFor all test cases: $2 \\leq n \\leq 10^5, 1 \\leq m \\leq 2 \\times 10^5, 0 \\leq A \\leq 10, 0 \\leq B, C \\leq 10^6, 1 \\leq x_i, y_i \\leq n, x_i \\neq y_i, 0 \\leq p_i < q_i \\leq 10^3$.\n\nSpecific constraints for each test case are as follows:\n\n| Test Case ID | $n$ | $m$ | Special Conditions for $A, B, C$ | Other Conditions |\n| :----------: | :-------------------: | :-------------------: | :-----------------------------: | :-------------------: |\n| $1 \\sim 2$ | $\\leq 100$ | $= n - 1$ | None | $y_i = x_i + 1$ |\n| $3 \\sim 4$ | $\\leq 100$ | $\\leq 100$ | $A = B = C = 0$ | $y_i = x_i + 1$ |\n| $5 \\sim 8$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | $A = B = C = 0$ | $x_i < y_i$ |\n| $9$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | $A = B = 0$ | $x_i < y_i$ |\n| $10$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | $A = 0$ | $x_i < y_i$ |\n| $11 \\sim 14$ | $\\leq 2 \\times 10^3$ | $\\leq 4 \\times 10^3$ | None | None |\n| $15$ | $\\leq 10^5$ | $\\leq 2 \\times 10^5$ | $A = B = 0$ | None |\n| $16 \\sim 17$ | $\\leq 10^5$ | $\\leq 2 \\times 10^5$ | $A = 0$ | None |\n| $18 \\sim 20$ | $\\leq 10^5$ | $\\leq 2 \\times 10^5$ | None | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 4003, "prompt": "### Problem Description\nWe say that a sequence $B = \\{b_1,b_2,\\cdots,b_n\\}$ is an **expansion** of another sequence $A = \\{a_1,a_2,\\cdots,a_m\\}$ if and only if a sequence of **positive integers** $L = \\{l_1,l_2,\\cdots,l_m\\}$ exists, such that replacing $a_i$ with $l_i$ copies of $a_i$ results in sequence $B$. For example:\n\n- $\\{1,3,3,3,2,2,2\\}$ is an expansion of $\\{1,3,3,2\\}$, with $L = \\{1,1,2,3\\}$ or $L = \\{1,2,1,3\\}$;\n- However, $\\{1,3,3,2\\}$ is not an expansion of $\\{1,3,3,3,2\\}$, and $\\{1,2,3\\}$ is not an expansion of $\\{1,3,2\\}$.\n\nLittle R gives you two sequences $X$ and $Y$, and he hopes that you can find an expansion $F = \\{f_i\\}$ of $X$ with length $l_0 = 10^{100}$ and an expansion $G = \\{g_i\\}$ of $Y$ with length $l_0$, such that for any $1 \\le i, j \\le l_0$, the following condition is satisfied: $(f_i - g_i)(f_j - g_j) > 0$. Given how long these sequences are, you only need to tell Little R whether such sequences exist.\n\nTo prevent coin-flipping or random guessing, Little R has provided $q$ additional queries. In each query, Little R modifies a certain number of elements in $X$ and $Y$. You need to make the determination described above for each modified $X$ and $Y$.\n\n**The queries are independent, and all modifications in each query are applied to the original sequence.**\n\n### Input Format\nThe first line contains four integers $c, n, m, q$, which represent the sample ID, the length of sequence $X$, the length of sequence $Y$, and the number of additional queries. Here, $c$ indicates that the sample has the same constraints as test case $c$.\n\nThe second line contains $n$ integers $x_1,x_2,\\cdots,x_n$, describing sequence $X$.\n\nThe third line contains $m$ integers $y_1,y_2,\\cdots,y_m$, describing sequence $Y$.\n\nThe next $q$ groups describe the additional queries. For each query:\n\n- The first line contains two integers $k_x$ and $k_y$, representing the number of modifications made to sequences $X$ and $Y$, respectively.\n- The next $k_x$ lines each contain two integers $p_x$ and $v_x$, indicating that $x_{p_x}$ is modified to $v_x$.\n- The next $k_y$ lines each contain two integers $p_y$ and $v_y$, indicating that $y_{p_y}$ is modified to $v_y$.\n\n### Output Format\nOutput a single line containing a binary sequence of length $(q+1)$. The first element of the sequence corresponds to the answer for the initial inquiry, and the subsequent $q$ elements correspond to the answers for each additional query in order. For each inquiry, output `1` if the required sequences $F$ and $G$ exist, and `0` otherwise.\n\n**Example Explanation #1** \n\nBecause $F$ and $G$ are very long, their repeated elements are represented using ellipses. For example, $\\{1,2,3,3,\\cdots\\}$ means that the sequence repeats the last element starting from the third position to reach length $l_0$. \n\nThe following describes the four inquiries, including the initial one and three additional ones:\n\n1. $A = \\{8,6,9\\}$, $B = \\{1,7,4\\}$, taking $F = \\{8,8,6,9,\\cdots\\}, G = \\{1,7,4,4,\\cdots\\}$;\n2. $A = \\{8,6,0\\}$, $B = \\{1,7,4\\}$, it can be proven that no valid solution exists;\n3. $A = \\{8,6,9\\}$, $B = \\{8,7,5\\}$, it can be proven that no valid solution exists;\n4. $A = \\{8,8,9\\}$, $B = \\{7,7,4\\}$, taking $F = \\{8,8,9,\\cdots\\}, G = \\{7,7,4,\\cdots\\}$.\n\n**Example Explanation #2**\n\nThis example satisfies the constraints of test case $4$.\n\n**Example Explanation #3**\n\nThis example satisfies the constraints of test case $7$.\n\n**Example Explanation #4**\n\nThis example satisfies the constraints of test case $9$.\n\n**Example Explanation #5**\n\nThis example satisfies the constraints of test case $18$.\n\n### Constraints\nFor all test data, the following are guaranteed:\n\n- $1 \\le n, m \\le 5 \\times 10 ^ 5$;\n- $0 \\le q \\le 60$;\n- $0 \\le x_i, y_i < 10 ^ 9$;\n- $0 \\le k_x, k_y \\le 5 \\times 10 ^ 5$, and the sum of $(k_x + k_y)$ across all queries does not exceed $5 \\times 10 ^ 5$;\n- $1 \\le p_x \\le n$, $1 \\le p_y \\le m$, $0 \\le v_x, v_y < 10 ^ 9$;\n- In each query, $p_x$ values are pairwise distinct, and $p_y$ values are pairwise distinct.\n\n|Sample ID|$n, m \\le$|Special Properties|\n|:-:|:-:|:-:|\n|$1$|$1$|No|\n|$2$|$2$|No|\n|$3, 4$|$6$|No|\n|$5$|$200$|No|\n|$6, 7$|$2000$|No|\n|$8, 9$|$4 \\times 10 ^ 4$|Yes|\n|$10, 11$|$1.5 \\times 10 ^ 5$|Yes|\n|$12 \\sim 14$|$5 \\times 10 ^ 5$|Yes|\n|$15, 16$|$4 \\times 10 ^ 4$|No|\n|$17, 18$|$1.5 \\times 10 ^ 5$|No|\n|$19, 20$|$5 \\times 10 ^ 5$|No|\n\nSpecial Property: For each inquiry (including the initial inquiry and additional queries), it is guaranteed that $x_1 < y_1$, and $x_n$ is the only smallest value in sequence $X$, while $y_m$ is the only largest value in sequence $Y$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 4004, "prompt": "### Problem Description\nStudent T is very enthusiastic about running. To make running more enjoyable, he decides to create a software called **\"Daily Check-in Challenge\"**, allowing users to log their running activities every day.\n\nAfter completing development, Student T plans to conduct trial runs and invites Student Y to help. There are a total of $n$ trial days, numbered from $1$ to $n$.\n\nFor Student Y, if he chooses to log his running activity on a certain day, his energy level will decrease by $d$. Initially, his energy level is $0$, and during the trial period, his **energy level can be negative**.\n\nMoreover, Student Y will not **continuously log running activities** for **more than** $k$ consecutive days. In other words, there cannot exist $1\\leq x\\leq n-k$ such that he logs his running activity from day $x$ to day $x+k$ inclusively.\n\nStudent T has designed $m$ challenges in the software. The $i$-th ($1\\leq i \\leq m$) challenge is described by three positive integers $(x_i, y_i, v_i)$, which indicate that if the user has continuously logged running activities for at least $y_i$ days up to day $x_i$ (i.e., from day $x_i-y_i+1$ to day $x_i$, all days logged), then Student T will treat the user to a meal, thereby increasing the user's energy level by $v_i$.\n\nNow, Student Y wants to know the **maximum** energy level he can achieve after $n$ trial days in the software.\n\n### Input Format\n**This problem contains multiple test cases.**\n\nThe first line of the input contains two integers $c$ and $t$, which represent the test case identifier and the number of test cases, respectively. For the examples, $c$ indicates that this example shares the same constraints as test case $c$.\n\nFollowing this, for each test case:\n\n- The first line contains four positive integers $n, m, k, d$, which represent the number of trial days, the number of challenges, the maximum consecutive days Student Y can log running activities, and the energy decrease due to logging running activity, respectively.\n- The next $m$ lines each contain three positive integers $x_i, y_i, v_i$, which describe a challenge.\n\n### Output Format\nOutput one integer, representing the answer for each test case.\n\n**\u3010Sample Explanation #1\u3011**\n\nRunning activity is logged on days $1, 2$, and not logged on day $3$. Ultimately, an energy level of $(-1)+(-1)+4=2$ is achieved.\n\n**\u3010Sample Explanation #2\u3011**\n\nThis test case satisfies the constraints of test case $3$.\n\n**\u3010Sample Explanation #3\u3011**\n\nThis test case satisfies the constraints of test case $5$.\n\n**\u3010Sample Explanation #4\u3011**\n\nThis test case satisfies the constraints of test case $15$.\n\n**\u3010Sample Explanation #5\u3011**\n\nThis test case satisfies the constraints of test case $17$.\n\n**\u3010Sample Explanation #6\u3011**\n\nThis test case satisfies the constraints of test case $19$.\n\n### Constraints\n\nLet $l_i = x_i - y_i + 1$, $r_i = x_i$;\n\nFor all test cases, it is guaranteed that: \n$1\\leq t\\leq 10$, $1\\leq k\\leq n\\leq 10^9$, $1\\leq m\\leq 10^5$, $1\\leq l_i\\leq r_i\\leq n$, $1\\leq d, v_i\\leq 10^9$.\n\n|Test Case ID|$n \\leq$|$m \\leq$|Special Properties|\n|:-:|:-:|:-:|:-:|\n|$1, 2$|$18$|$10 ^ 2$|None|\n|$3, 4$|$10 ^ 2$|$10 ^ 2$|None|\n|$5 \\sim 7$|$10 ^ 3$|$10 ^ 3$|None|\n|$8, 9$|$10 ^ 3$|$10 ^ 5$|None|\n|$10, 11$|$10 ^ 5$|$10 ^ 3$|None|\n|$12 \\sim 14$|$10 ^ 5$|$10 ^ 5$|None|\n|$15, 16$|$10 ^ 9$|$10 ^ 5$|A|\n|$17, 18$|$10 ^ 9$|$10 ^ 5$|B|\n|$19 \\sim 21$|$10 ^ 9$|$10 ^ 5$|C|\n|$22 \\sim 25$|$10 ^ 9$|$10 ^ 5$|None|\n\nSpecial Property A: $k \\leq 10^2$; \n\nSpecial Property B: $\\forall 1\\leq i\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 3389, "prompt": "### Problem Description\n\nC loves running and enjoys competing on the WeChat step leaderboard. To this end, he has devised a plan for racking up steps on WeChat.\n\nHe arrives at an open area where the position of a person in the field can be represented by $k$-dimensional integer coordinates $(a_1, a_2, \\ldots, a_k)$. The field has size constraints\u2014specifically, in the $i$-th dimension, its size is $w_i$. Thus, for a person to be within the field, their coordinates must satisfy $1 \\leq a_i \\leq w_i$ ($1 \\leq i \\leq k$). \n\nC plans to pick a new starting position from the field every day for the next $P = w_1 \\times w_2 \\times \\cdots \\times w_k$ days and execute his walking routine from each of these positions (in other words, he will start his routine once from every position in the field). \n\nThe plan is very simple. Each day, he follows a pre-defined walking route consisting of $n$ steps. Each step is defined using $c_i$ and $d_i$. If he is currently at position $(a_1, a_2, \\ldots, a_{c_i}, \\ldots, a_k)$, this step will move him to $(a_1, a_2, \\ldots, a_{c_i} + d_i, \\ldots, a_k)$. Here, $1 \\leq c_i \\leq k$, and $d_i \\in \\{-1, 1\\}$. C will repeat this route continuously until stepping out of the field bounds, upon which he stops his routine for the day (i.e., if C is still within bounds after completing the $n$ steps, he will restart the route from the first step again). \n\nC is very confident about his speed and does not care about the time spent. He only wants to know how many total steps he will accumulate on WeChat after $P$ days. Please help him calculate this. \n\n### Input Format\nThe first line contains two space-separated integers $n$ and $k$, representing the number of steps in the route and the number of dimensions of the field, respectively. \nThe second line contains $k$ space-separated integers $w_i$, indicating the size of the field in each dimension. \nThe next $n$ lines each contain two space-separated integers $c_i$ and $d_i$, representing the direction of each step, as described in the problem description. \n\n### Output Format\nOutput a single integer representing the answer. Since the answer may be very large, output it modulo ${10}^9 + 7$. \nIf C's plan causes him to get stuck in the field forever on any day (i.e., he cannot step out of the field), print a single integer $-1$. \n\n### Sample Input\n\n```\n2 2\n3 3\n2 1\n1 -1\n```### Sample Output\n\n```\n21\n```\n\n### **Sample #1 Explanation**\n\nStarting from $(1, 1)$, C will take $2$ steps. Starting from $(1, 2)$, C will take $4$ steps. Starting from $(1, 3)$, C will take $4$ steps. \nStarting from $(2, 1)$, C will take $2$ steps. Starting from $(2, 2)$, C will take $3$ steps. Starting from $(2, 3)$, C will take $3$ steps. \nStarting from $(3, 1)$, C will take $1$ step. Starting from $(3, 2)$, C will take $1$ step. Starting from $(3, 3)$, C will take $1$ step. \nA total of $21$ steps. \n\n### **Constraints**\n\n| Test Case Range | $n \\leq$ | $k \\leq$ | $w_i \\leq$ |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 3$ | $5$ | $5$ | $3$ |\n| $4 \\sim 6$ | $100$ | $3$ | $10$ |\n| $7 \\sim 8$ | ${10}^5$ | $1$ | ${10}^5$ |\n| $9 \\sim 12$ | ${10}^5$ | $2$ | ${10}^6$ |\n| $13 \\sim 16$ | $5 \\times {10}^5$ | $10$ | ${10}^6$ |\n| $17 \\sim 20$ | $5 \\times {10}^5$ | $3$ | ${10}^9$ |\n\nFor all test cases, it is guaranteed that $1 \\leq n \\leq 5 \\times {10}^5$, $1 \\leq k \\leq 10$, $1 \\leq w_i \\leq {10}^9$, and $d_i \\in \\{-1, 1\\}$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 4001, "prompt": "### Problem Description\n\nLittle S has a dictionary containing $n$ distinct words, each of length $m$: $w_1, w_2, \\cdots, w_n$. Each word is a string composed of lowercase English letters.\n\nLittle S can perform the following operation any number of times (including zero times): Select any word from the dictionary and swap any two characters in it.\n\nFor each $1 \\le i \\le n$, Little S wants to determine if it is possible to perform the above operations to obtain a new set of $n$ words $w'_1, w'_2, \\cdots , w'_n$ such that for every $j \\neq i$, the lexicographical order of $w'_i$ is smaller than all $w'_j$. **For the case where $n=1$, we assume that this property is naturally satisfied.**\n\nFor two strings of the same length $s = s_1s_2\\cdots s_L$ and $t = t_1t_2 \\cdots t_L$, we say that $s$ has a smaller lexicographical order than $t$ if and only if the following condition is met: There exists a position $i$ such that $s$ and $t$ are identical up to position $i-1$, and $s_i < t_i$, where the lowercase letter $s_i$ comes before $t_i$ in the alphabetical order.\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $m$, representing the number of words and the length of each word, respectively.\n\nThe next $n$ lines each contain a lowercase string of length $m$, denoted as $w_i$, representing a word in the dictionary.\n\n### Output Format\n\nOutput one line containing a binary string of length $n$, denoted as $a$. For each $1 \\le i \\le n$, if the property mentioned in the problem description holds, set $a_i = 1$; otherwise, set $a_i = 0$.\n\n### Example Explanation #1\n\n- Without performing any operations, the first word is already lexicographically smallest, so the first character of the output is `1`.\n- By swapping the first two characters of `bananaa` and the third and sixth characters of `abandon`, you can obtain the following: `abondan`, `abnanaa`, `baannaa`, `notnotn`. In this case, the second word becomes lexicographically smallest, so the second character of the output is `1`.\n- By swapping the first and last characters of `baannaa`, you can obtain `aaannab`, while the other words remain unchanged. In this case, the third word becomes lexicographically smallest, so the third character of the output is `1`.\n- However, no matter what operations you perform, the fourth word will not become smaller than the second word, so the fourth character of the output is `0`.\n\n### Example Explanation #2\n\nThis example satisfies the constraints of Test Case $4$.\n\n### Example Explanation #3\n\nThis example satisfies the constraints of Test Case $7$.\n\n### Example Explanation #4\n\nThis example satisfies the constraints of Test Case $10$.\n\n### Constraints\n\nFor all test cases, it is guaranteed that $1 \\le n \\le 3000$, $1 \\le m \\le 3000$, and each $w_i$ is a unique lowercase string of length $m$.\n\n| Test Case ID | $n\\leq$ | $m\\leq$ |\n| :----------: | :----------: | :----------: |\n| $1$ | $1$ | $1$ |\n| $2\\sim 4$ | $26$ | $1$ |\n| $5\\sim 7$ | $15$ | $2$ |\n| $8$ | $300$ | $300$ |\n| $9$ | $10^3$ | $10^3$ |\n| $10$ | $3000$ | $3000$ | \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "easy"} +{"id": 3899, "prompt": "### Problem Description\nXiao N and Xiao O will participate in the grand programming competition NOIP in November 2022! Xiao P will host the competition as the judge. Both Xiao N and Xiao O lead a team of $n$ members, where the players in each team are numbered from $1$ to $n$. Each player has a specific programming skill level. Specifically, in Xiao N's team, the programming skill level of the player numbered $i$ ($1 \\leq i \\leq n$) is $a _ i$; in Xiao O's team, the programming skill level of the player numbered $i$ ($1 \\leq i \\leq n$) is $b _ i$. Moreover, $\\{a _ i\\}$ and $\\{b _ i\\}$ are permutations of the integers from $1$ to $n$.\n\nBefore each match, considering factors such as travel distance and consecutive participation in matches, Xiao P will select two parameters $l$ and $r$ ($1 \\leq l \\leq r \\leq n$), indicating that players from both teams whose numbers are within the range $[l, r]$ will be invited to the venue to prepare for the match. At the venue, Xiao N and Xiao O use dice rolls to choose the parameters $p$ and $q$ ($l \\leq p \\leq q \\leq r$), and only players within the range $[p, q]$ will participate in the match. To provide the audience with the most exciting competition, both teams will send the players in $[p, q]$ who have the highest programming skill levels to compete. Assuming the skill level of Xiao N's player is $m _ a$, and the skill level of Xiao O's player is $m _ b$, the excitement of the match is calculated as $m _ a \\times m _ b$.\n\nThere are $Q$ matches in total in NOIP. For each match, the parameters $l$ and $r$ are already determined, but $p$ and $q$ have not been selected yet. Xiao P wants to know, for each match, the sum of the excitement values for all possible $p$ and $q$ ($l \\leq p \\leq q \\leq r$). Since the result could be extremely large, you only need to output the result modulo $2 ^ {64}$ for each match.\n\n### Input Format\nThe first line contains two positive integers $T$ and $n$, representing the test point number and the number of participants. If the data is a sample, it is guaranteed that $T = 0$.\n\nThe second line contains $n$ positive integers, where the $i$-th integer is $a _ i$, representing the programming skill level of the player numbered $i$ in Xiao N's team.\n\nThe third line contains $n$ positive integers, where the $i$-th integer is $b _ i$, representing the programming skill level of the player numbered $i$ in Xiao O's team.\n\nThe fourth line contains a positive integer $Q$, representing the number of matches.\n\nThe next $Q$ lines, the $i$-th line contains two positive integers $l _ i$ and $r _ i$, indicating the parameters $l$ and $r$ of the $i$-th match.\n\n### Output Format\nOutput $Q$ lines. The $i$-th line contains a non-negative integer, representing the result of the sum of all possible match excitement values modulo $2 ^ {64}$ for the $i$-th match.\n\n**\u3010Example 1 Explanation\u3011**\n\nWhen $p = 1, q = 2$, Xiao N will send player $1$, Xiao O will send player $2$, and the excitement of the match is $2 \\times 2 = 4$.\n\nWhen $p = 1, q = 1$, Xiao N will send player $1$, Xiao O will send player $1$, and the excitement of the match is $2 \\times 1 = 2$.\n\nWhen $p = 2, q = 2$, Xiao N will send player $2$, Xiao O will send player $2$, and the excitement of the match is $1 \\times 2 = 2$.\n\n**\u3010Example 2\u3011**\n\nThis example satisfies the constraints of test points $1 \\sim 2$.\n\n**\u3010Example 3\u3011**\n\nThis example satisfies the constraints of test points $3 \\sim 5$.\n\n### Data Constraints\n\nFor all data, guaranteed:\n- $1 \\leq n, Q \\leq 2.5 \\times 10 ^ 5$\n- $1 \\leq l _ i \\leq r _ i \\leq n$\n- $1 \\leq a _ i, b _ i \\leq n$, and $\\{a _ i\\}$ and $\\{b _ i\\}$ are permutations of the integers from $1$ to $n$.\n\n| Test Point | $n$ | $Q$ | Special Property A | Special Property B |\n| :----------: | :----------: | :----------: | :----------: | :----------: |\n| $1, 2$ | $\\leq 30$ | $\\leq 30$ | Yes | Yes |\n| $3, 4, 5$ | $\\leq 3,000$ | $\\leq 3,000$ | Yes | Yes |\n| $6, 7$ | $\\leq 10 ^ 5$ | $\\leq 5$ | Yes | Yes |\n| $8, 9$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 5$ | Yes | Yes |\n| $10, 11$ | $\\leq 10 ^ 5$ | $\\leq 5$ | No | No |\n| $12, 13$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 5$ | No | No |\n| $14, 15$ | $\\leq 10 ^ 5$ | $\\leq 10 ^ 5$ | Yes | Yes |\n| $16, 17$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 2.5 \\times 10 ^ 5$ | Yes | Yes |\n| $18, 19$ | $\\leq 10 ^ 5$ | $\\leq 10 ^ 5$ | Yes | No |\n| $20, 21$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 2.5 \\times 10 ^ 5$ | Yes | No |\n| $22, 23$ | $\\leq 10 ^ 5$ | $\\leq 10 ^ 5$ | No | No |\n| $24, 25$ | $\\leq 2.5 \\times 10 ^ 5$ | $\\leq 2.5 \\times 10 ^ 5$ | No | No |\n\nSpecial Property A: Guarantees $a$ is a uniformly random permutation of integers from $1 \\sim n$.\n\nSpecial Property B: Guarantees $b$ is a uniformly random permutation of integers from $1 \\sim n$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3981, "prompt": "### Problem Description\n\nDepth-First Search (DFS) is a common traversal algorithm. Using this algorithm, starting from a connected undirected graph without multi-edges and self-loops $G = (V, E)$, and a specified starting point $s$, we can obtain a DFS tree $T$.\n\nThe algorithm proceeds as follows:\n\n1. Initialize an empty stack $S$, and set $T = (V, \\emptyset)$, meaning that the edge set of $T$ is initially empty.\n2. Push the starting point $s$ into the stack $S$.\n3. Visit the top node $u$ of the stack, marking $u$ as \"visited.\"\n4. If there exists an unvisited node adjacent to $u$, randomly pick one of these nodes and denote it as $v$. Add the edge $(u, v)$ to the edge set of $T$, push $v$ into $S$, and **return to step 3**. If no such node exists, pop the node $u$ from the stack.\n\nIt can be proven that when the graph $G$ is connected, this algorithm will result in a spanning tree $T$ for the graph. However, **the tree $T$ obtained by this algorithm may not be unique, as it depends on the search sequence, particularly the choice of nodes in step 4**. For a specified starting point $s$, if a specific search sequence can be chosen such that the algorithm produces exactly the tree $T$, we call **$T$ an $s$-dfs tree of $G$**.\n\nNow, given a tree $T$ with $n$ vertices numbered $1 \\sim n$, and an additional $m$ edges, we guarantee that the $m$ edges are distinct, connect different vertices, and do not overlap with the $n - 1$ edges in the tree $T$. These $m$ edges are referred to as **non-tree edges**. Among these $n$ vertices, $k$ vertices are designated as **key vertices**.\n\nYou want to know how many ways there are to select the $m$ non-tree edges (possibly choosing none), such that: after constructing the graph $G$ by combining the edges of the tree $T$ and the selected non-tree edges, there exists a **key vertex** $s$ such that $T$ is an $s$-dfs tree of $G$.\n\nSince the answer can be very large, report the number of ways modulo $(10 ^ 9 + 7)$. \n\n### Input Format\n\nThe first line of input contains an integer $c$, indicating the test point number. $c = 0$ signifies that this test point is a sample test case.\n\nThe second line contains three positive integers $n, m, k$, representing the number of vertices, the number of non-tree edges, and the number of key vertices, respectively.\n\nThe next $n - 1$ lines each contain two positive integers $u, v$, representing an edge from the tree $T$. These $n - 1$ edges form a connected tree structure.\n\nThe next $m$ lines each contain two positive integers $a, b$, representing a non-tree edge. It is guaranteed that $(a, b)$ does not overlap with the edges in the tree and that there are no duplicate edges.\n\nThe last line contains $k$ positive integers $s_1, s_2, \\dots, s_k$, representing the indices of the $k$ key vertices. It is guaranteed that $s_1, s_2, \\dots, s_k$ are distinct.\n\n### Output Format\n\nOutput a single line containing a non-negative integer representing the number of valid ways to select the non-tree edges, modulo $(10 ^ 9 + 7)$. \n\n### **Sample Explanation #1**\n\nIn this sample, there are three ways to select the non-tree edges: choosing only the edge $(1, 3)$, choosing only the edge $(2, 4)$, or choosing none of the non-tree edges.\n\n1. If only the edge $(1, 3)$ is selected, or if no non-tree edges are chosen, it can be observed that $T$ is an $s$-dfs tree of $G$, where the key vertex $s = 3$. The specific DFS sequence is as follows:\n 1. Push $3$ into the stack $S$. Now $S = [3]$.\n 2. Mark $3$ as \"visited.\"\n 3. Since $3$ is connected to $2$, and $2$ is \"unvisited,\" add $(3, 2)$ to $T$, push $2$ into the stack $S$. Now $S = [3, 2]$.\n 4. Mark $2$ as \"visited.\"\n 5. Since $2$ is connected to $1$, and $1$ is \"unvisited,\" add $(2, 1)$ to $T$, push $1$ into the stack $S$. Now $S = [3, 2, 1]$.\n 6. As all vertices connected to $1$ are \"visited,\" pop $1$ from the stack. Now $S = [3, 2]$.\n 7. As all vertices connected to $2$ are \"visited,\" pop $2$ from the stack. Now $S = [3]$.\n 8. Since $3$ is connected to $4$, and $4$ is \"unvisited,\" add $(3, 4)$ to $T$, push $4$ into the stack $S$. Now $S = [3, 4]$.\n 9. As all vertices connected to $4$ are \"visited,\" pop $4$ from the stack. Now $S = [3]$.\n 10. As all vertices connected to $3$ are \"visited,\" pop $3$ from the stack. The stack becomes empty.\n\n2. If only the edge $(2, 4)$ is selected, it can be shown that $T$ is an $s$-dfs tree of $G$, where the key vertex $s = 2$. The specific DFS sequence is as follows:\n 1. Push $2$ into the stack $S$. Now $S = [2]$.\n 2. Mark $2$ as \"visited.\"\n 3. Since $2$ is connected to $3$, and $3$ is \"unvisited,\" add $(2, 3)$ to $T$, push $3$ into the stack $S$. Now $S = [2, 3]$.\n 4. Mark $3$ as \"visited.\"\n 5. Since $3$ is connected to $4$, and $4$ is \"unvisited,\" add $(3, 4)$ to $T$, push $4$ into the stack $S$. Now $S = [2, 3, 4]$.\n 6. As all vertices connected to $4$ are \"visited,\" pop $4$ from the stack. Now $S = [2, 3]$.\n 7. As all vertices connected to $3$ are \"visited,\" pop $3$ from the stack. Now $S = [2]$.\n 8. Since $2$ is connected to $1$, and $1$ is \"unvisited,\" add $(2, 1)$ to $T$, push $1$ into the stack $S$. Now $S = [2, 1]$.\n 9. As all vertices connected to $1$ are \"visited,\" pop $1$ from the stack. Now $S = [2]$.\n 10. As all vertices connected to $2$ are \"visited,\" pop $2$ from the stack. The stack becomes empty.\n\n### **Sample Explanation #2**\n\nThis sample satisfies constraints from test points $4 \\sim 6$.\n\n### **Sample Explanation #3**\n\nThis sample satisfies constraints from test points $10 \\sim 11$.\n\n### **Sample Explanation #4**\n\nThis sample satisfies constraints from test points $12 \\sim 13$.\n\n### **Sample Explanation #5**\n\nThis sample satisfies constraints from test points $14 \\sim 16$.\n\n### **Sample Explanation #6**\n\nThis sample satisfies constraints from test points $23 \\sim 24$.\n\n---\n\n### **Constraints**\n\nFor all test cases, it is guaranteed that $1 \\le k \\le n \\le 5 \\times 10 ^ 5$, $1 \\le m \\le 5 \\times 10 ^ 5$.\n\n| Test Point | $n \\le$ | $m \\le$ | $k \\le$ | Special Properties |\n|:-:|:-:|:-:|:-:|:-:|\n| $1 \\sim 3$ | $6$ | $6$ | $n$ | None |\n| $4 \\sim 6$ | $15$ | $15$ | $6$ | None |\n| $7 \\sim 9$ | $300$ | $300$ | $6$ | None |\n| $10 \\sim 11$ | $300$ | $300$ | $n$ | A |\n| $12 \\sim 13$ | $300$ | $300$ | $n$ | B |\n| $14 \\sim 16$ | $300$ | $300$ | $n$ | None |\n| $17 \\sim 18$ | $2 \\times 10 ^ 5$ | $2 \\times 10 ^ 5$ | $n$ | A |\n| $19 \\sim 21$ | $2 \\times 10 ^ 5$ | $2 \\times 10 ^ 5$ | $n$ | B |\n| $22$ | $2 \\times 10 ^ 5$ | $2 \\times 10 ^ 5$ | $n$ | None |\n| $23 \\sim 25$ | $5 \\times 10 ^ 5$ | $5 \\times 10 ^ 5$ | $n$ | None |\n\nSpecial Property A: In the tree $T$, vertex $i$ is connected to vertex $i + 1$ ($1 \\le i < n$).\n\nSpecial Property B: If all $m$ non-tree edges are added to graph $G$ along with the edges of $T$, $T$ is guaranteed to be a $1$-dfs tree of $G$.\n\n**Note:** Vertex $1$ is not necessarily one of the $k$ key vertices.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3983, "prompt": "### Problem Description\nXiao Y is a college student who has recently been researching problems related to strings.\n\nXiao Y has learned the following definitions about strings:\n\n- Given a string $s[1: n]$ of length $n$, we define its substring $s[l: r]$ ($1 \\leq l \\leq r \\leq n$) as the string obtained by concatenating $s[l], s[l+1], \\dots, s[r]$ in order.\n- Given a string $s[1: n]$ of length $n$, we define its reversed version $R(s)$ as the string obtained by concatenating $s[n], s[n-1], \\dots, s[1]$ in reverse order.\n- Given two strings $a[1: n]$ and $b[1: n]$ both of length $n$, we define $a$ as lexicographically smaller than $b$ if and only if there exists $1 \\leq i \\leq n$, such that for all $1 \\leq j < i$, $a[j] = b[j]$, and $a[i] < b[i]$.\n\nAfter understanding the above definitions, Xiao Y thought of this problem:\n\nGiven a string $s[1: n]$ of length $n$, there are $q$ queries, and for each query you are given two parameters $i$ and $r$. You need to find how many values of $l$ satisfy the following conditions:\n- $1 \\leq l \\leq r$.\n- $s[i: i+l-1]$ is lexicographically smaller than $R(s[i+l: i+2l-1])$.\n\nXiao Y asks for your help in solving this problem.\n\n### Input Format\n**This problem contains multiple test cases.**\n\nThe first line of the input contains two integers $c$ and $t$, which represent the test case identifier and the number of test cases respectively. $c=0$ indicates that this is a sample test case.\n\nFor each test case:\n\nThe first line contains two positive integers $n$ and $q$, representing the length of the string and the number of queries.\n\nThe second line contains a string $s$ of length $n$ consisting of lowercase English letters only.\n\nThe next $q$ lines contain two positive integers $i$ and $r$, representing a query. It is guaranteed that $i + 2r - 1 \\leq n$.\n\n### Output Format\nFor each query in each test case, output a single integer in one line representing the number of values of $l$ that satisfy the conditions.\n\n### **Sample Explanation #1**\n\nFor the first query of the first test case:\n- When $l = 1$, $s[i: i + l - 1] = \\texttt{a}$, $R(s[i + l: i + 2l - 1]) = \\texttt{b}$.\n- When $l = 2$, $s[i: i + l - 1] = \\texttt{ab}$, $R(s[i + l: i + 2l - 1]) = \\texttt{ca}$.\n- When $l = 3$, $s[i: i + l - 1] = \\texttt{aba}$, $R(s[i + l: i + 2l - 1]) = \\texttt{bac}$.\n- When $l = 4$, $s[i: i + l - 1] = \\texttt{abac}$, $R(s[i + l: i + 2l - 1]) = \\texttt{baba}$.\n\nIn all four cases, $s[i: i + l - 1]$ is lexicographically smaller than $R(s[i + l: i + 2l - 1])$. Thus, the answer is $4$.\n\n### **Sample Explanation #2**\n\nThis sample satisfies the conditions for test case $5$.\n\n### **Sample Explanation #4**\n\nThis sample satisfies the conditions for test cases $24 \\sim 25$.\n\n### **Constraints**\n\nFor all test cases:\n$1 \\leq t \\leq 5$, $1 \\leq n \\leq 10 ^ 5$, $1 \\leq q \\leq 10 ^ 5$, $1 \\leq i + 2r - 1 \\leq n$, and the string $s$ contains only lowercase letters.\n\n|Test Case Identifier|$n \\leq$|$q \\leq$|Special Properties|\n|:-:|:-:|:-:|:-:|\n|$1$|$5$|$5$|A|\n|$2$|$10$|$10$|A|\n|$3$|$20$|$20$|A|\n|$4$|$50$|$50$|A|\n|$5$|$10^2$|$10^2$|A|\n|$6$|$10^3$|$10^3$|None|\n|$7$|$2,000$|$2,000$|None|\n|$8$|$3,000$|$3,000$|None|\n|$9$|$4,000$|$4,000$|None|\n|$10$|$23,333$|$23,333$|A|\n|$11$|$5 \\times 10 ^ 4$|$5 \\times 10 ^ 4$|A|\n|$12$|$75,000$|$75,000$|A|\n|$13$|$9 \\times 10 ^ 4$|$9 \\times 10 ^ 4$|A|\n|$14$|$10 ^ 5$|$10 ^ 5$|A|\n|$15$|$23,333$|$23,333$|B|\n|$16$|$75,000$|$75,000$|B|\n|$17$|$9 \\times 10 ^ 4$|$9 \\times 10 ^ 4$|B|\n|$18$|$10 ^ 5$|$10 ^ 5$|B|\n|$19$|$23,333$|$23,333$|None|\n|$20$|$5 \\times 10 ^ 4$|$5 \\times 10 ^ 4$|None|\n|$21$|$75,000$|$75,000$|None|\n|$22$|$9 \\times 10 ^ 4$|$9 \\times 10 ^ 4$|None|\n|$23$|$95,000$|$95,000$|None|\n|$24 \\sim 25$|$10 ^ 5$|$10 ^ 5$|None|\n\nSpecial Property A: The string contains only characters $\\texttt{a}$ and $\\texttt{b}$, and each character is independently chosen with equal probability between $\\texttt{a}$ and $\\texttt{b}$.\n\nSpecial Property B: Adjacent characters in the string are guaranteed to be different.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2356, "prompt": "### Problem Description\nRecently, Xiao Dong has made remarkable progress in calculating the number of spanning trees in undirected connected graphs. He discovered that:\n\n- The number of spanning trees of a ring graph with $n$ nodes is $n$.\n- The number of spanning trees of a complete graph with $n$ nodes is $n^{n-2}$.\n\nThese two findings made Xiao Dong ecstatic, and he became even more motivated to continue his research on counting spanning trees for various graphs. \nOne day, during a gathering with his classmates, everyone sat around a large round table. Xiao Dong looked around and was reminded of the spanning tree problem. He thought that if each classmate was treated as a node and an edge was added between neighboring classmates (nodes with a distance of $1$), the resulting graph would form a ring. However, since Xiao Dong had already mastered counting the number of spanning trees for ring graphs and found it uninteresting, he decided to modify the graph: not only did he connect adjacent classmates, but also those sitting at a distance of $2$, treating both cases as having an edge between the nodes, as shown in Figure 1.\n\n![count.png](https://img.loj.ac.cn/2021/12/29/94344181076fa.png)\n\nXiao Dong had never calculated the number of spanning trees for this type of graph before. However, he recalled a method his teacher taught for calculating spanning trees for any graph: \nConstruct an $n \\times n$ matrix $A = \\{a_{ij}\\}$, where:\n\n$$ \n\\begin{equation}\na_{ij}= \n\\begin{cases} \nd_i & i=j \\\\\n-1 & (i,j)\\in V \\\\\n0 & (i,j)\\notin V, \\, i \\neq j \n\\end{cases} \n\\end{equation} \n$$ \n\nHere, $d_i$ represents the degree of node $i$. The matrix $A$ corresponding to Figure 1 is shown below. To calculate the number of spanning trees corresponding to Figure 1, remove the last row and column of the matrix $A$, resulting in a $(n-1) \\times (n-1)$ matrix $B$. The determinant of matrix $B$ gives the number of spanning trees for Figure 1.\n\n$$\n\\mathbf{A} =\n\\begin{matrix}\n4 & -1 & -1 & 0 & 0 & 0 & -1 & -1 \\\\\n-1 & 4 & -1 & -1 & 0 & 0 & 0 & -1 \\\\\n-1 & -1 & 4 & -1 & -1 & 0 & 0 & 0 \\\\\n0 & -1 & -1 & 4 & -1 & -1 & 0 & 0 \\\\\n0 & 0 & -1 & -1 & 4 & -1 & -1 & 0 \\\\\n0 & 0 & 0 & -1 & -1 & 4 & -1 & -1 \\\\\n-1 & 0 & 0 & 0 & -1 & -1 & 4 & -1 \\\\\n-1 & -1 & 0 & 0 & 0 & -1 & -1 & 4\n\\end{matrix}\n\\quad\n\\mathbf{B} =\n\\begin{matrix}\n4 & -1 & -1 & 0 & 0 & 0 & -1 \\\\\n-1 & 4 & -1 & -1 & 0 & 0 & 0 \\\\\n-1 & -1 & 4 & -1 & -1 & 0 & 0 \\\\\n0 & -1 & -1 & 4 & -1 & -1 & 0 \\\\\n0 & 0 & -1 & -1 & 4 & -1 & -1 \\\\\n0 & 0 & 0 & -1 & -1 & 4 & -1 \\\\\n-1 & 0 & 0 & 0 & -1 & -1 & 4\n\\end{matrix}\n$$\n\nThus, the number of spanning trees is $|B| = 3528$. Xiao Dong found that the general method was too computationally complex, and other methods failed to provide a simpler formula for calculation. Therefore, he simplified the graph by breaking the round table at one point, forming a linear chain. In this case, every classmate is represented as a node, with edges between nodes at a distance of $1$ and $2$. For example, for eight nodes, the graph looks like this:\n\n![3(2).png](https://i.loli.net/2018/02/12/5a814c7f75f3e.png)\n\nThis significantly reduces the number of spanning trees. Xiao Dong continued thinking about it until the end of the gathering and finally found a quick way to calculate the number of spanning trees for this graph. However, if nodes at a distance of $3$ are also connected, Xiao Dong found himself unable to determine the total number of spanning trees efficiently. Now, he needs your help to calculate the number of spanning trees for such graphs.\n\n### Input Format\nThe input consists of two integers $k$ and $n$, separated by a space. Here:\n- $k$ indicates connecting all pairs of nodes whose distance does not exceed $k$ (inclusive).\n- $n$ indicates the total number of nodes.\n\n### Output Format\nOutput an integer representing the number of spanning trees. Since the result can be very large, output the remainder when the result is divided by $65521$.\n\n### Example\nThe graph corresponding to the example input is shown below:\n\n![\u6355\u83b7.JPG](https://i.loli.net/2018/02/12/5a814d9247c63.jpg)\n\n$$\n\\mathbf{A} =\n\\begin{matrix}\n3 & -1 & -1 & -1 & 0 \\\\\n-1 & 4 & -1 & -1 & -1 \\\\\n-1 & -1 & 4 & -1 & -1 \\\\\n-1 & -1 & -1 & 4 & -1 \\\\\n0 & -1 & -1 & -1 & 3\n\\end{matrix}\n\\quad\n\\mathbf{B} =\n\\begin{matrix}\n3 & -1 & -1 & -1 \\\\\n-1 & 4 & -1 & -1 \\\\\n-1 & -1 & 4 & -1 \\\\\n-1 & -1 & -1 & 4\n\\end{matrix}\n\\quad\n|B| = 75\n$$\n\n### Data Constraints\n#### Scale and Assumptions\nFor all test cases, $2 \\le k \\le n$.\n\n\n\n| Case ID | $k$ Range | $n$ Range | Case ID | $k$ Range | $n$ Range |\n|-|-|-|-|-|-|\n| 1 | $k = 2$ | $n \\le 10$ | 6 | $k \\le 5$ | $n \\le 100$ |\n| 2 | $k = 3$ | $n = 5$ | 7 | $k \\le 3$ | $n \\le 2000$ |\n| 3 | $k = 4$ | $n \\le 10$ | 8 | $k \\le 5$ | $n \\le 10000$ |\n| 4 | $k = 5$ | $n = 10$ | 9 | $k \\le 3$ | $n \\le 10^{15}$ |\n| 5 | $k \\le 3$ | $n \\le 100$ | 10 | $k \\le 5$ | $n \\le 10^{15}$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3344, "prompt": "### Problem Description\n\nCountry C consists of $n$ cities connected by $m$ bidirectional roads. The cities are numbered from $1$ to $n$, and the roads are numbered from $1$ to $m$. The $i^{th}$ road connects city $u_i$ and city $v_i$ with a length of $w_i$ meters. Through these roads, it is possible to travel from any city to any other city in Country C.\n\nThe citizens of Country C enjoy circular tours but dislike passing through too many roads. To accommodate this preference, the roads in Country C are constructed with special properties. Specifically, for a simple cycle that consists of $l$ roads (i.e., a cycle that does not pass through any city more than once except for the start and end city), such a cycle can be expressed as:\n\n$c_{1} \\rightarrow c_{2} \\rightarrow \\cdots \\rightarrow c_{l} \\rightarrow c_{1}$ \n\n(where for all $1 \\leq i < l$, city $c_i$ and city $c_{i+1}$ are connected by a road; $c_l$ and $c_1$ are also connected by a road; and for all $1 \\leq i < j \\leq l$, $c_{i} \\neq c_{j}$). If $l > 3$, the roads of Country C satisfy the following condition:\n - There exist two **non-adjacent** cities $u$ and $v$ in the cycle that are directly connected by a road. In other words, there exist $1 \\leq u < v \\leq l$ such that $v - u \\geq 2$, $u$ and $v$ are not simultaneously $1$ and $l$, and city $c_u$ is directly connected to city $c_v$ by a road.\n\nThe government of Country C now has a renovation plan, which requires finding a path between city $s$ and city $t$ to be renovated. During the renovation, all roads on the selected path will become inaccessible. To ensure the daily life of citizens is unaffected during this process, the remaining roads (i.e., those not included in the renovated path) must still satisfy the property that: **it is possible to travel from any city to any other city in Country C**.\n\nAs a master engineer, you are tasked with helping Country C find a renovation path that satisfies the above requirements and has the **minimum total length**.\n\n### Input Format\n\nThe first line contains two integers $n$ and $m$, representing the number of cities and the number of roads, respectively.\n\nThe next $m$ lines each contain three integers $u_i$, $v_i$, and $w_i$, representing the two endpoints of the $i^{th}$ road and its length.\n\nIt is guaranteed that every road connects two distinct cities, i.e., $u_i \\neq v_i$.\n\nThe last line contains two integers $s$ and $t$, representing the endpoints of the path to be renovated.\n\n### Output Format\n\nOutput a single integer, representing the minimum possible total length of the renovation path that satisfies the requirements. \n\n**If no such path exists, output a single integer $-1$.**\n\n### Example 1 Explanation\n\nThe path $(1, 2, 1), (2, 3, 1), (3, 4, 1)$ is the shortest path between city $1$ and city $4$, but it does not meet the requirements.\n\nThe path $(1, 3, 5), (3, 4, 1)$ meets the requirements, with a total length of $6$.\n\nThe path $(1, 2, 1), (2, 4, 6)$ also meets the requirements, with a total length of $7$.\n\nNo other paths satisfy the requirements.\n\n### Example 3\n\nSee the file `road/road3.in` and `road/road3.ans` in the contestant's directory. This example corresponds to constraints in test cases $1\\sim6$.\n\n### Example 4\n\nSee the file `road/road4.in` and `road/road4.ans` in the contestant's directory. This example corresponds to constraints in test cases $7\\sim10$.\n\n### Example 5\n\nSee the file `road/road5.in` and `road/road5.ans` in the contestant's directory. This example corresponds to constraints in test cases $11\\sim15$.\n\n### Example 6\n\nSee the file `road/road6.in` and `road/road6.ans` in the contestant's directory. This example corresponds to constraints in test cases $16\\sim20$.\n\n*However, the last three examples are too large to upload\u2026*\n\n---\n\n### Constraints\n\nFor all test cases: $2 \\leq n \\leq 5 \\times 10^{5}$, $2 \\leq m \\leq 10^{6}$, and $s \\neq t$.\n\n$1 \\leq u_{i}, v_{i} \\leq n$, $u_{i} \\neq v_{i}$, $1 \\leq w_{i} \\leq 10^{9}$. It is guaranteed that any two roads do not have the exact same endpoints. \n\nIt is also guaranteed that the given roads satisfy the property described in the second paragraph of the problem description.\n\nThe specific constraints for each test case are shown in the table below:\n\n| Test Case | $n\\le $ | $m\\le $ | Special Constraints |\n| :-: | :-: | :-:| :-: |\n| $1\\sim6$ | $2 \\times 10^3$ | $4 \\times 10^3$ | None |\n| $7\\sim10$ | $5 \\times 10^5$ | $10^6$ | $\\text{A}$ |\n| $11\\sim15$ | $5 \\times 10^5$ | $10^6$ | $\\text{B}$ |\n| $16\\sim20$ | $5 \\times 10^5$ | $10^6$ | None |\n\nSpecial Constraints A: The lengths of all roads are equal.\n\nSpecial Constraints B: All roads with $w_i = 1$ form exactly one path from $s$ to $t$, and all other roads with $w_i \\neq 1$ have endpoints that are at a distance of $2$ from each other on this path.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3851, "prompt": "### Problem Description\nThe sequences studied by Xiao Z are composed of non-negative integers. Each sequence has a length of $n$ and must satisfy $m$ additional conditions. The $i$-th condition specifies that the numbers at indices within $[L_i, R_i]$, i.e., $a_{L_i}, a_{L_{i+1}}, \\dots, a_{R_i}$, must have a minimum value **equal to $\\boldsymbol{V_i}$**.\n\nXiao Z knows that bubble sort often results in excessive time consumption. Therefore, he wants to determine the minimum number of swap operations required during bubble sort among all sequences that satisfy the additional conditions.\n\n### Input Format\nThis problem contains multiple test cases.\n\nThe first line of input contains a positive integer $T$.\n\nFor each test case, the first line contains two positive integers $n$ and $m$. It is guaranteed that $1 \\leq n, m \\leq 10^6$.\n\nThe following $m$ lines each contain three non-negative integers $L_i, R_i, V_i$, representing an additional condition. It is guaranteed that $1 \\leq L_i \\leq R_i \\leq n$ and $0 \\leq V_i \\leq 10^9$.\n\n### Output Format\nOutput $T$ lines in total, one for each test case.\n\nFor each test case, if there exists a sequence that satisfies all $m$ additional conditions, output the minimum number of swaps required during bubble sort among all such sequences. If no sequence satisfies all the conditions, output $-1$.\n\n### **Sample Explanation #1**\n\nThe conditions for this test case are $a_1 = 2022, \\min\\{a_2, a_3\\} = 39$.\n\n- If $a_2 = 39$, and $39 \\leq a_3 < 2022$, bubble sort requires only one round of swapping. In this round, $a_1$ and $a_2$ are swapped, followed by $a_2$ and $a_3$, totaling $2$ swaps.\n- If $a_2 = 39$, and $a_3 \\geq 2022$, bubble sort requires only one round of swapping. In this round, only $a_1$ and $a_2$ are swapped, totaling $1$ swap.\n- If $a_3 = 39$, and $39 < a_2 < 2022$, bubble sort requires swapping $a_1$ and $a_2$, followed by $a_2$ and $a_3$ in the first round, then swapping $a_1$ and $a_2$ again in the second round, totaling $3$ swaps.\n- If $a_3 = 39$, and $a_2 \\geq 2022$, bubble sort swaps $a_2$ and $a_3$ in the first round, followed by $a_1$ and $a_2$ in the second round, totaling $2$ swaps.\n\nThe minimum number of swaps is therefore $1$.\n\n----\n\n### **Sample #2**\n\nRefer to the files `bubble/bubble2.in` and `bubble/bubble2.ans`.\n\n----\n\n### **Sample #3**\n\nRefer to the files `bubble/bubble3.in` and `bubble/bubble3.ans`.\n\nThis sample satisfies the conditions of test points $8$ to $10$.\n\n----\n\n### **Sample #4**\n\nRefer to the files `bubble/bubble4.in` and `bubble/bubble4.ans`.\n\nThis sample satisfies the conditions of test points $13$ to $14$.\n\n----\n\n### **Sample #5**\n\nRefer to the files `bubble/bubble5.in` and `bubble/bubble5.ans`.\n\nThis sample satisfies the conditions of test points $15$ to $16$.\n\n----\n\n### **Sample #6**\n\nRefer to the files `bubble/bubble6.in` and `bubble/bubble6.ans`.\n\nThis sample satisfies the conditions of test points $23$ to $25$.\n\n----\n\n### **Constraints**\n\nThis problem contains $25$ test points. All test points satisfy the constraints: $1 \\leq T \\leq 1000$, $1 \\leq \\sum n, \\sum m \\leq 10^6$, $1 \\leq L_i \\leq R_i \\leq n$, $0 \\leq V_i \\leq 10^9$.\n\nHere, $\\sum n$ and $\\sum m$ represent the total sum of $n$ and $m$ across all test points, respectively. $\\sum n^2$, $\\sum m^2$, $\\sum n^3$, and $\\sum m^3$ have similar meanings.\n\n| Test Points | Data Range | Special Properties |\n|:-------------:|:-----------------------------------------------------:|:------------------:|\n| $1 \\sim 4$ | $n,m \\leq 7$, and at most $2$ test cases exceed $n, m \\leq 5$ | |\n| $5 \\sim 7$ | $n,m \\leq 17$, and at most $3$ test cases exceed $n, m \\leq 9$ | A |\n| $8 \\sim 10$ | $n,m \\leq 100$, $\\sum n^3, \\sum m^3 \\leq 4 \\times 10^7$ | A |\n| $11 \\sim 12$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| A |\n| $13 \\sim 14$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| B |\n| $15 \\sim 16$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| C |\n| $17 \\sim 18$ | $n,m \\leq 2000$, $\\sum n^2, \\sum m^2 \\leq 4 \\times 10^7$| |\n| $19$ | $\\sum n,\\sum m \\leq 10^6$ | A |\n| $20$ | $\\sum n,\\sum m \\leq 10^6$ | B |\n| $21 \\sim 22$ | $\\sum n,\\sum m \\leq 10^6$ | C |\n| $23 \\sim 25$ | $\\sum n,\\sum m \\leq 10^6$ | |\n\nSpecial Property A: For $1 \\leq i \\leq m$, $0 \\leq V_i \\leq 1$. \nSpecial Property B: For $1 \\leq i \\leq m$, $L_i = R_i$. \nSpecial Property C: The $m$ intervals $[L_i, R_i]$ given in input are pairwise non-overlapping.\n\n----\n\n### **Hint**\n\nSome test cases have large input sizes. It is recommended to use a fast input method.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2954, "prompt": "### Problem Description\n\nLittle D loves playing games. One day, he is playing a number-filling game.\n\nThe board of this number-filling game is an $n\\times m$ rectangular grid. Players need to fill each cell of the grid with either the number $0$ or $1$, while meeting certain constraints. Let's describe these constraints in detail.\n\nTo facilitate the description, we first define some terms:\n- Each cell is represented by its row and column coordinates $(x, y)$, where $x$ is the row index and $y$ is the column index (note: both indices start from $0$).\n- Valid Path $P$: A path is valid if and only if:\n 1. The path starts from the top-left cell of the grid $(0,0)$ and ends at the bottom-right cell of the grid $(n-1,m-1)$;\n 2. For each step along the path, you can either move to the cell immediately to the right of the current cell or to the cell immediately below the current cell.\n\nFor example, in the grid shown below, there are only two valid paths: $P_1:(0,0)\\to (0,1)\\to (1,1)$, and $P_2:(0,0)\\to (1,0)\\to (1,1)$.\n\n![game.png](https://i.loli.net/2018/11/25/5bfa4a3e042ef.png)\n\nFor a valid path $P$, we can represent it using a string $w(P)$. The length of $w(P)$ is $n+m-2$, and it consists only of characters `R` and `D`. The $i$-th character records the $i$-th move in the path $P$: `R` indicates moving to the cell immediately to the right, and `D` indicates moving to the cell immediately below. For example, in the figure above, for the path $P_1$, $w(P_1)=\\texttt{RD}$; and for the other path $P_2$, $w(P_2)=\\texttt{DR}$.\n\nAt the same time, for any valid path $P$, if you concatenate the numbers filled in each cell along the path, it forms a binary string of length $n+m-1$, denoted as $s(P)$. For example, if you fill the number $0$ in cells $(0,0)$ and $(1,0)$, and the number $1$ in cells $(0,1)$ and $(1,1)$ (as shown by the red numbers in the figure above), then for the path $P_1$, $s(P_1)=\\texttt{011}$, and for the path $P_2$, $s(P_2)=\\texttt{001}$.\n\nThe goal of the game is to find a way to fill the numbers $0$ and $1$ into the grid such that for any two paths $P_1$ and $P_2$, if $w(P_1) > w(P_2)$, then it must satisfy $s(P_1) \\leq s(P_2)$. A string $a$ is considered smaller than a string $b$ if and only if $a$ is lexicographically smaller than $b$. The definition of lexicographical order can be found in [Problem 1](https://loj.ac/problem/2953).\n\nHowever, simply finding one valid solution does not satisfy Little D's curiosity. Little D wants to know how many different ways there are to fill the grid such that the game requirements are met. \n\nSince the answer can be very large, you need to output the result modulo $10^9+7$.\n\n### Input Format\n\nThe input file is named `game.in`. \nThe input consists of a single line containing two positive integers $n$ and $m$, separated by a space, representing the size of the rectangular grid. Here, $n$ is the number of rows, and $m$ is the number of columns.\n\n### Output Format\n\nThe output file is named `game.out`. \nThe output consists of a single line containing one positive integer, the number of ways to fill the grid with $0$s and $1$s that meet the game's requirements. \nThe answer should be output modulo $10^9+7$.\n\n### Example 1\n\nGrid for a $2 \\times 2$ board: \n![game2.png](https://i.loli.net/2018/11/25/5bfa4bb92d884.png)\n\nFor a $2\\times 2$ grid, there are 12 valid ways to fill the grid that satisfy the requirements.\n\n### Example 2\n\n### Example 3\n\n### Constraints and Hints\n\n| Test Case ID | $n \\leq$ | $m \\leq$ |\n| :----------: | :------: | :------: |\n| $1\\sim 4$ | $3$ | $3$ |\n| $5\\sim 10$ | $2$ | $10^6$ |\n| $11\\sim 13$ | $3$ | $10^6$ |\n| $14\\sim 16$ | $8$ | $8$ |\n| $17\\sim 20$ | $8$ | $10^6$ |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3984, "prompt": "### Problem Description\n\nLittle C has $n$ books, each with a specific weight. He decides to combine them into a single stack.\n\nIn each merging operation, Little C can stack one pile of books onto another, thereby merging them into one pile. If Little C places the $i$-th pile of books on top of the $j$-th pile, the energy consumption for this operation is calculated as **the weight of the $i$-th pile** plus **the sum of the wear values of the two piles**.\n\nInitially, each book forms its own pile, and the wear value of each pile is $0$. After Little C merges two piles, the newly formed pile's wear value is **twice the larger of the two original wear values, plus one**, and its weight is **the sum of the weights of the two original piles**.\n\nYour task is to design a merging sequence that minimizes Little C's total energy consumption and output this minimum energy consumption.\n\n### Input Format\n\n**This problem has multiple test cases.**\n\nThe first line of input contains a positive integer $t$, the number of test cases.\n\nThe following lines contain the data for each test case. For each test case:\n\n- The first line contains a positive integer $n$, the number of books.\n- The second line contains $n$ positive integers, where the $i$-th number $w_i$ represents the weight of the $i$-th book.\n\n### Output Format\n\nFor each test case, output one line containing a single integer \u2014 the minimum energy consumption required to combine $n$ books into one pile.\n\n**Example Explanation #1**\n\nIf Little C combines the $4$ books in pairs, then combines the resulting two piles into one pile:\n\n- The energy cost of the first two merges is $1$ each. \n- The third merge involves stacking a pile weighing $2$ onto another pile, with each pile having a wear value of $1$, resulting in an energy cost of $2 + 1 + 1 = 4$.\n\nThus, for this sequence, the total energy consumption is $1 + 1 + 4 = 6$.\n\nIt can be proven that $6$ is the minimum energy consumption for the given example.\n\n### Constraints\n\nFor all test cases:\n\n$1 \\leq t \\leq 10$, $1 \\leq n \\leq 100$, $1 \\leq w_i \\leq 10^9$.\n\n| Test Case ID | $n \\leq$ | Special Properties |\n|:-------------:|:--------:|:------------------:|\n| $1 \\sim 2$ | $7$ | No |\n| $3$ | $11$ | No |\n| $4$ | $13$ | No |\n| $5 \\sim 6$ | $22$ | No |\n| $7 \\sim 8$ | $28$ | No |\n| $9 \\sim 13$ | $50$ | No |\n| $14$ | $60$ | No |\n| $15$ | $70$ | No |\n| $16$ | $80$ | No |\n| $17 \\sim 18$ | $100$ | Yes |\n| $19 \\sim 20$ | $100$ | No |\n\nSpecial Property: Guaranteed $w_i = 1$ for these cases. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3979, "prompt": "### Problem Description\n\nYou are given a chessboard with $n$ columns and $m$ rows, consisting of $n \\times m$ cells. Both rows and columns are indexed starting from $1$, and the cell in the $i$th column and $j$th row is denoted by $(i, j)$. Initially, all cells are white. Now, you are required to perform $q$ coloring operations on the chessboard.\n\nThere are three types of coloring operations:\n\n1. **Coloring a horizontal line:** Specifically, given two cells $(x_1, y_1)$ and $(x_2, y_2)$, where $x_1 \\leq x_2$ and $y_1 = y_2$, all cells between these two (inclusive) are colored black.\n2. **Coloring a vertical line:** Specifically, given two cells $(x_1, y_1)$ and $(x_2, y_2)$, where $x_1 = x_2$ and $y_1 \\leq y_2$, all cells between these two (inclusive) are colored black.\n3. **Coloring a diagonal line:** Specifically, given two cells $(x_1, y_1)$ and $(x_2, y_2)$, where $x_1 \\leq x_2$ and $x_2 - x_1 = y_2 - y_1$, all diagonal cells of the form $(x_1 + i, y_1 + i)$ for $0 \\leq i \\leq x_2 - x_1$ are colored black. **This type of coloring operation will occur at most $5$ times.**\n\nYour task is to determine how many cells on the chessboard are black after $q$ coloring operations.\n\n---\n\n### Input Format\n\nInput data is read from the file `color.in`.\n\nThe first line contains an integer $c$, which represents the test case number. $c = 0$ indicates that this test case is a sample case.\n\nThe second line contains three positive integers $n$, $m$, and $q$, representing the number of columns, rows, and coloring operations, respectively.\n\nThe next $q$ lines describe the coloring operations. Each line contains five positive integers $t$, $x_1$, $y_1$, $x_2$, $y_2$:\n\n- $t = 1$ represents the first type of coloring operation.\n- $t = 2$ represents the second type of coloring operation.\n- $t = 3$ represents the third type of coloring operation.\n- The integers $x_1$, $y_1$, $x_2$, and $y_2$ specify the parameters for the operation.\n\n---\n\n### Output Format\n\nOutput the result to the file `color.out`.\n\nOutput a single line containing a single integer, which represents the number of black cells on the chessboard after all the operations.\n\n---\n\n### Example 1\n\nIn this example, three coloring operations are performed, as shown in the figure below:\n\n![color.png](https://img.loj.ac.cn/2023/07/31/8da82c4679eac.png)\n\n1. In the first operation, the cells $(1, 3), (2, 3), (3, 3), (4, 3), (5, 3)$ are colored black.\n\n2. In the second operation, the cells $(3, 1), (3, 2), (3, 3), (3, 4), (3, 5)$ are colored black.\n\n3. In the third operation, the cells $(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)$ are colored black.\n\n---\n\n### Example 2\n\nSee the attached files `color2.in` and `color2.ans` for further details.\n\nThis example satisfies the conditions for test points $1 \\sim 5$.\n\n---\n\n### Example 3\n\nSee the attached files `color3.in` and `color3.ans` for further details.\n\nThis example satisfies the conditions for test points $6 \\sim 9$.\n\n---\n\n### Example 4\n\nSee the attached files `color4.in` and `color4.ans` for further details.\n\nThis example satisfies the conditions for test points $10 \\sim 13$.\n\n---\n\n### Example 5\n\nSee the attached files `color5.in` and `color5.ans` for further details.\n\nThis example satisfies the conditions for test points $14 \\sim 17$.\n\n---\n\n### Example 6\n\nSee the attached files `color6.in` and `color6.ans` for further details.\n\nThis example satisfies the conditions for test points $18 \\sim 19$.\n\n---\n\n### Example 7\n\nSee the attached files `color7.in` and `color7.ans` for further details.\n\nThis example satisfies the conditions for test point $20$.\n\n---\n\n### Constraints and Hints\n\nFor all test cases:\n\n- $1 \\leq n, m \\leq 10^9$ \n- $1 \\leq q \\leq 10^5$ \n- $1 \\leq x_1, x_2 \\leq n$ \n- $1 \\leq y_1, y_2 \\leq m$ \n- **There will be at most $5$ operations of the third type.**\n\n| Test Case Number | $n, m \\leq$ | $q \\leq$ | Special Properties |\n|:-----------------:|:-----------:|:--------:|:------------------:|\n| $1 \\sim 5$ | $300$ | $300$ | None |\n| $6 \\sim 9$ | $10^5$ | $2000$ | None |\n| $10 \\sim 13$ | $10^5$ | $10^5$ | A |\n| $14 \\sim 17$ | $10^5$ | $10^5$ | B |\n| $18 \\sim 19$ | $10^5$ | $10^5$ | None |\n| $20$ | $10^9$ | $10^5$ | None |\n\nSpecial Property A: Only the first type of coloring operation will occur. \nSpecial Property B: Only the first and second types of coloring operations will occur.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3341, "prompt": "### Problem Description\n\nLittle L enjoys discussing and exchanging ideas with a wise individual, who often presents Little L with challenging problems to think about.\n\nOne day, the wise individual conceived a new problem for Little L. The wise individual first abstracted spacetime into a two-dimensional plane, where an **event** is represented by a point on the plane and an **epoch** is represented by a rectangle on the plane.\n\nTo facilitate the problem, let $(a, b) \\leq (c, d)$ denote two points $(a, b)$ and $(c, d)$ on the plane satisfying $a \\leq c$ and $b \\leq d$.\n\nSpecifically, the wise individual provided $n$ **events**, represented by $n$ **distinct points** $\\{(x_i, y_i)\\}^n_{i=1}$ on the plane;\n\nThe wise individual also provided $m$ **epochs**, where each epoch is represented by a **rectangle** $(r_{i,1}, r_{i,2}, c_{i,1}, c_{i,2})$, where $(r_{i,1}, c_{i,1})$ is the bottom-left corner of the rectangle and $(r_{i,2}, c_{i,2})$ is the top-right corner, ensuring $(r_{i,1}, c_{i,1}) \\leq (r_{i,2}, c_{i,2})$. Epoch $i$ is said to **contain** event $j$ if and only if $(r_{i,1}, c_{i,1}) \\leq (x_j, y_j) \\leq (r_{i,2}, c_{i,2})$.\n\nThe wise individual considers two events $i$ and $j$ to form a **regret** if $(x_i, y_i) \\leq (x_j, y_j)$. For all events included in a single epoch, the regrets they form are referred to as the **tears** of that epoch, and the total number of regrets is referred to as the **size of the tears** of the epoch. Now, the wise individual wants Little L to calculate the **size of the tears** for each epoch.\n\nLittle L understands that if he cannot solve the problem, he will also become a tear of the epoch. Can you help him?\n\n---\n\n### Input Format\nInput is read from the file `tears.in`.\n\nThe first line contains two integers $n$ and $m$, representing the number of events and the number of epochs, respectively.\n\nThe second line contains $n$ integers $p_i$, where the $i$-th integer represents the coordinate of event $i$ as $(i, p_i)$ on the plane. It is guaranteed that $p_i$ is a permutation of $1$ to $n$.\n\nThe next $m$ lines each contain four integers $r_{i,1}, r_{i,2}, c_{i,1}, c_{i,2}$, representing the rectangle corresponding to each epoch.\n\n---\n\n### Output Format\nOutput to the file `tears.out`.\n\nThe output should contain $m$ lines, where the $i$-th line contains a single integer, representing the size of the tears for the $i$-th epoch.\n\n---\n\n### Example\n\nFor epoch $1$, the regrets included are $(6, 7)$ (i.e., event $6$ and event $7$ form a regret, and so on).\n\nFor epoch $2$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epoch $3$, the regrets included are $(5, 6), (5, 8)$.\n\nFor epoch $4$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epoch $5$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epoch $6$, the regrets included are $(5, 6), (6, 7), (5, 7), (5, 8)$.\n\nFor epochs $7, 8, 9$, none of these include any regrets.\n\nRefer to the `tears2.in` and `tears2.ans` files for the input and expected output of this example.\n\n---\n\n### Constraints and Example Explanation\nRefer to the `tears3.in` and `tears3.ans` files for another example.\n\n#### Constraints\nFor all test cases, $1 \\leq n \\leq 10^5$, $1 \\leq m \\leq 2 \\times 10^5$, and $1 \\leq r_{i,1}, r_{i,2}, c_{i,1}, c_{i,2} \\leq n$.\n\nThe specific constraints for each test case are given in the following table:\n\n| Test Case ID | $n \\leq$ | $m \\leq$ | Special Properties |\n|:------------:|:---------:|:---------:|:------------------:|\n| $1\\sim3$ | $10$ | $10$ | |\n| $4$ | $3,000$ | $3,000$ | |\n| $5$ | $4,000$ | $4,000$ | |\n| $6$ | $5,000$ | $5,000$ | |\n| $7$ | $25,000$ | $50,000$ | A |\n| $8$ | $50,000$ | $100,000$ | A |\n| $9$ | $75,000$ | $150,000$ | A |\n| $10$ | $100,000$ | $200,000$ | A |\n| $11$ | $60,000$ | $120,000$ | B |\n| $12$ | $80,000$ | $160,000$ | B |\n| $13$ | $100,000$ | $200,000$ | B |\n| $14$ | $20,000$ | $40,000$ | |\n| $15$ | $30,000$ | $60,000$ | |\n| $16$ | $40,000$ | $80,000$ | |\n| $17$ | $50,000$ | $100,000$ | |\n| $18$ | $60,000$ | $120,000$ | |\n| $19$ | $70,000$ | $140,000$ | |\n| $20\\sim22$ | $100,000$ | $200,000$ | C |\n| $23\\sim25$ | $100,000$ | $200,000$ | |\n\n#### Special Constraints\n- **Constraint A**: For all epochs $i$, $c_{i,1} = 1$ and $c_{i,2} = n$.\n- **Constraint B**: For any two different epochs, their rectangles are either inclusive (one rectangle is inside the other, allowing their boundaries to overlap) or disjoint (rectangles share no common points, and their boundaries do not overlap).\n- **Constraint C**: At most $50$ pairs of events $(i, j)$ ($1 \\leq i < j \\leq n$) **do not satisfy** $(i, p_i) \\leq (j, p_j)$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2303, "prompt": "### Problem Description\nThere are $n$ worms in the Worm Kindergarten. To make management easier, the kindergarten director, \"Shen Daoshou,\" often asks the worms to line up and perform.\n\nAll the worms are numbered consecutively as integers from $1$ to $n$. Each worm's length can be represented by a positive integer, and due to admission criteria, the length of each worm does not exceed $6$. Shen Daoshou hopes to arrange the worms into several teams. Initially, each worm forms a team by itself, where it is both the head and tail of the team.\n\nShen Daoshou will perform $m$ operations one by one, where each operation is one of the following three types:\n\n1. Given $i$ and $j$, merge the teams that $i$-th worm and $j$-th worm belong to into a single team. Specifically, place the $j$-th worm immediately after the $i$-th worm, keeping the relative order of all other worms in both teams unchanged.\n\n2. Given $i$, split the $i$-th worm and the worm immediately following it into two separate teams. Specifically, after the split, the $i$-th worm becomes the tail of one team, and the worm originally immediately following it becomes the head of another team, keeping the relative order of all other worms unchanged.\n\n3. Given a positive integer $k$ and a numeric string $s$ of length at least $k$, for every length-$k$ substring $t$ of $s$ (there are $|s| - k + 1$ such substrings, where $|s|$ is the length of $s$), define a function $f(t)$, and query the **product** of all these $f(t)$ values modulo $998244353$. The function $f(t)$ is defined as follows:\n\nFor the current arrangement of worm teams, define the **backward $k$ digital string** of a worm as follows: Starting from that worm, move backward along the team to find the nearest $k$ worms (including itself), and join their lengths as digits to form a numeric string. If fewer than $k$ worms can be found, that worm does not have a **backward $k$ digital string**. For example, if the worm team is composed of worm $10$ (team head) followed by worm $22$ and worm $3$ (team tail), whose lengths are $4$, $5$, and $6$, respectively, the **backward $3$ digital string** of worm $10$ is `456`; worm $22$ does not have a **backward $3$ digital string**, but its **backward $2$ digital string** is `56`, and its **backward $1$ digital string** is `5`.\n\nMeanwhile, $f(t)$ indicates the count of worms whose **backward $k$ digital string** is exactly equal to $t$.\n\n### Input Format\nThe first line contains two positive integers, $n$ and $m$, which represent the number of worms and the number of operations, respectively.\n\nThe second line contains $n$ positive integers not exceeding $6$, representing the lengths of worms numbered $1, 2, \\dots, n$, in order.\n\nThe next $m$ lines describe the operations, each of which can be in one of the following formats:\n\n* `1` $i$ $j$ ($1 \\leq i, j \\leq n$): This denotes merging the teams of worms $i$ and $j$. In the new team, the $j$-th worm is placed immediately after the $i$-th worm. Prior to this operation, the $i$-th worm is guaranteed to be the tail of its team, while the $j$-th worm is guaranteed to be the head of its team, and the two worms reside in different teams.\n\n* `2` $i$ ($1 \\leq i \\leq n$): This denotes splitting the $i$-th worm and the worm immediately following it into two teams. Before this operation, it is guaranteed that the $i$-th worm is not the tail of its team.\n\n* `3` $s$ $k$ ($k$ is a positive integer, $s$ is a numeric string of length at least $k$): This queries the result of the product of $f(t)$ for each length-$k$ substring $t$ of $s$ modulo $998244353$. The definition of $f(t)$ is provided in the problem description.\n\nAdjacent elements in the same input line are separated by exactly one space.\n\nThe input file might be large; avoid using excessively slow input methods.\n\n### Output Format\nFor each operation of type `3 s k`, output a single integer representing the queried result.\n\n### Constraints\nIt is guaranteed that $n \\leq 2 \\times 10^{5}$, $m \\leq 5 \\times 10^{5}$, and $k \\leq 50$. \n\nLet $\\sum |s|$ represent the sum of the lengths of all queried $s$ strings in a particular input file. It is guaranteed that $\\sum |s| \\leq 10^{7}$. \n\nLet $c$ represent the count of type `2 i` operations in a particular input file. It is guaranteed that $c \\leq 10^{3}$.\n\nDetailed testing point information is provided in the table below:\n\n| Test Point ID | $n$ | $m$ | $k$ | $\\sum |s|$ | $c$ | All $\\texttt{1}$ |\n|:-:|:-:|:-:|:-:|:-:|:-:|:-:|\n| 1 | $=1$ | $\\leq 10^{3}$ | $=1$ | $\\leq 10^{3}$ | $=0$ | No |\n| 2 | $\\leq 20$ | $\\leq 40$ | $\\leq 10$ | $\\leq 10^{3}$ | $=0$ | No |\n| 3 | $\\leq 150$ | $\\leq 2,000$ | $\\leq 50$ | $\\leq 10^{3}$ | $\\leq 10^{3}$ | No |\n| 4 | $\\leq 500$ | $\\leq 600$ | $\\leq 50$ | $\\leq 10^{3}$ | $=0$ | No |\n| 5 | $\\leq 10^{3}$ | $\\leq 2,000$ | $\\leq 50$ | $\\leq 10^{3}$ | $\\leq 10^{3}$ | No |\n| 6 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 5$ | $\\leq 5 \\times 10^{4}$ | $\\leq 10^{3}$ | No |\n| 7 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 50$ | $\\leq 5 \\times 10^{4}$ | $=0$ | Yes |\n| 8 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 50$ | $\\leq 5 \\times 10^{4}$ | $=0$ | No |\n| 9 | $\\leq 5 \\times 10^{4}$ | $\\leq 6 \\times 10^{4}$ | $\\leq 50$ | $\\leq 5 \\times 10^{4}$ | $\\leq 10^{3}$ | No |\n| 10 | $\\leq 5 \\times 10^{4}$ | $\\leq 8 \\times 10^{4}$ | $\\leq 50$ | $\\leq 2.5 \\times 10^{6}$ | $=0$ | No |\n| 11 | $\\leq 5 \\times 10^{4}$ | $\\leq 8 \\times 10^{4}$ | $\\leq 50$ | $\\leq 2.5 \\times 10^{6}$ | $\\leq 10^{3}$ | No |\n| 12 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 6$ | $\\leq 10^{5}$ | $\\leq 10^{3}$ | No |\n| 13 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{5}$ | $=0$ | Yes |\n| 14 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{5}$ | $=0$ | No |\n| 15 | $\\leq 10^{5}$ | $\\leq 1.1 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{5}$ | $\\leq 10^{3}$ | No |\n| 16 | $\\leq 10^{5}$ | $\\leq 1.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 5 \\times 10^{6}$ | $=0$ | No |\n| 17 | $\\leq 10^{5}$ | $\\leq 1.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 5 \\times 10^{6}$ | $\\leq 10^{3}$ | No |\n| 18 | $\\leq 2 \\times 10^{5}$ | $\\leq 5 \\times 10^{5}$ | $=1$ | $\\leq 10^{7}$ | $=0$ | No |\n| 19 | $\\leq 2 \\times 10^{5}$ | $\\leq 5 \\times 10^{5}$ | $=1$ | $\\leq 10^{7}$ | $\\leq 10^{3}$ | No |\n| 20 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 7$ | $\\leq 2 \\times 10^{5}$ | $\\leq 10^{3}$ | No |\n| 21 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 2 \\times 10^{5}$ | $=0$ | Yes |\n| 22 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 2 \\times 10^{5}$ | $=0$ | No |\n| 23 | $\\leq 2 \\times 10^{5}$ | $\\leq 2.5 \\times 10^{5}$ | $\\leq 50$ | $\\leq 2 \\times 10^{5}$ | $\\leq 10^{3}$ | No |\n| 24 | $\\leq 2 \\times 10^{5}$ | $\\leq 3 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{7}$ | $=0$ | No |\n| 25 | $\\leq 2 \\times 10^{5}$ | $\\leq 3 \\times 10^{5}$ | $\\leq 50$ | $\\leq 10^{7}$ | $\\leq 10^{3}$ | No |\n\nIf the \"All $\\texttt{1}$\" column of a test point is `Yes`, it means all worms' lengths are `1`, and every character in each query string $s$ is also `1`.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2133, "prompt": "### Problem Description\n\nThe annual \"Phantom Pavilion Summer Wine Tasting Festival\" has grandly opened. The festival features two sections: tasting and fun challenges, with the titles of \"Top Taster\" and \"Top Hunter\" awarded to the winners, attracting numerous wine tasters.\n\nDuring the festival dinner, Rainbow, the bartender, prepared $n$ glasses of cocktails. These $n$ glasses of cocktails are arranged in a row, with the $i$th glass ($1 \\leq i \\leq n$) labeled as $s_i$, where each label is one of the $26$ lowercase English letters. Let $\\mathrm{Str}(l, r)$ represent the string formed by concatenating the labels of the cocktails from glass $l$ to glass $r$ in sequence for $r - l + 1$ labels. If $\\mathrm{Str}(p, p_0) = \\mathrm{Str}(q, q_0)$, where $1 \\leq p \\leq p_0 \\leq n$, $1 \\leq q \\leq q_0 \\leq n$, $p \\neq q$, and $p_0 - p + 1 = q_0 - q + 1 = r$, then the $p$th glass and $q$th glass of cocktails are considered \"$r$-similar\". Clearly, two \"$r$-similar\" ($r > 1$) cocktails are also \"$1$-similar\", \"$2$-similar\", $\\dots$, \"$(r-1)$-similar\". Specifically, for any $1 \\leq p, q \\leq n$, where $p \\neq q$, the $p$th glass and the $q$th glass of cocktails are always \"$0$-similar\".\n\nIn the tasting section of the festival, Freda the wine taster easily assessed the deliciousness of each glass of wine. Due to her professional skills and experience, she successfully earned the title of \"Top Taster\". The deliciousness of the $i$th glass of wine ($1 \\leq i \\leq n$) is $a_i$. Now, Rainbow revealed the challenge: the cocktails for this festival have one unique feature\u2014if two glasses of cocktails, $p$ and $q$, are mixed, the resulting glass of wine will have a deliciousness of $a_p \\cdot a_q$. Please calculate the following for each $r = 0, 1, 2, \\dots, n - 1$:\n\n1. The number of ways to choose two \"$r$-similar\" glasses of cocktails.\n2. The maximum deliciousness that can be obtained by mixing two \"$r$-similar\" glasses of cocktails.\n\n### Input Format\n\nThe first line of the input contains a positive integer $n$, which represents the number of glasses of cocktails.\n\nThe second line contains a string $S$ of length $n$, where the $i$th character represents the label of the $i$th glass of wine.\n\nThe third line contains $n$ integers, separated by single spaces, where the $i$th integer represents the deliciousness $a_i$ of the $i$th glass of wine.\n\n### Output Format\n\nThe output consists of $n$ lines. The $i$th line contains two integers separated by a single space:\n\n1. The number of ways to select two \"$(i-1)$-similar\" glasses of cocktails.\n2. The maximum deliciousness obtained by mixing two \"$(i-1)$-similar\" glasses of cocktails.\n\nIf no two \"$(i-1)$-similar\" glasses of cocktails exist, both integers in the output should be $0$.\n\n### Example 1\n\nUsing a pair $(p, q)$ to represent the $p$th and $q$th glasses of wine:\n\n- **$0$-similar:** All $45$ pairs are $0$-similar, with the maximum deliciousness being $8 \\times 7 = 56$.\n- **$1$-similar:** $(1,8)$, $(2,4)$, $(2,9)$, $(4,9)$, $(5,6)$, $(5,7)$, $(5,10)$, $(6,7)$, $(6,10)$, $(7,10)$, maximum deliciousness is $8 \\times 7 = 56$.\n- **$2$-similar:** $(1,8)$, $(4,9)$, $(5,6)$, maximum deliciousness is $4 \\times 8 = 32$.\n- **No $3$-, $4$-, $5$-, $\\dots$-, $9$-similar pairs of glasses, so output is $0$ for these cases.\n\n### Example 2\n\n... Add specific input/output details for a second example if needed...\n\n---\n\n### Constraints and Hints\n\n| Case # | Scale of $n$ | Scale of $a_i$ | Remarks |\n|:-:|:-:|:-:|:-:|\n| 1 | $n = 100$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 2 | $n = 200$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 3 | $n = 500$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 4 | $n = 750$ | $\\lvert a_i \\rvert \\leq 10000$ | - |\n| 5 | $n = 1000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 6 | $n = 1000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 7 | $n = 2000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 8 | $n = 2000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 9 | $n = 99991$ | $\\lvert a_i \\rvert \\leq 10^9$ | No \"$10$-similar\" glasses |\n| 10 | $n = 99991$ | $\\lvert a_i \\rvert \\leq 10^9$ | No \"$10$-similar\" glasses |\n| 11 | $n = 100000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 12 | $n = 200000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 13 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 14 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^6$ | All $a_i$ values are equal |\n| 15 | $n = 100000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 16 | $n = 100000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 17 | $n = 200000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 18 | $n = 200000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 19 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n| 20 | $n = 300000$ | $\\lvert a_i \\rvert \\leq 10^9$ | - |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3537, "prompt": "### Problem Description\n\nLittle R has $m$ ($1 \\le m \\le 1000$) robots and $m$ paper tapes. The $i$-th robot ($1 \\le i \\le m$) is responsible for operating on the $i$-th paper tape. Each paper tape is divided from left to right into $n$ ($1 \\le n \\le 32$) cells, numbered sequentially as $0, 1, \\ldots, n - 1$. Each cell can have one of three states: \n1. The cell contains the digit `0`. \n2. The cell contains the digit `1`. \n3. The cell is empty.\n\nAt any point in time, the robot **must** stand on one of the cells of the paper tape. After initializing the robot's starting position on the paper tape, the $i$-th robot will execute a predetermined operational sequence $S_i$, consisting of the characters `R`, `0`, `1`, and `*`, where:\n\n1. `R` instructs the robot to move one cell to the right. If there are no cells to the right, the robot will explode on the spot. \n2. `0` instructs the robot, if it is on a non-empty cell, to change the content of that cell to `0`. Otherwise, no change is made. \n3. `1` instructs the robot, if it is on a non-empty cell, to change the content of that cell to `1`. Otherwise, no change is made. \n4. `*` instructs the robot, if it is on a non-empty cell, to flip the content of the cell (`0` becomes `1`, and `1` becomes `0`). Otherwise, no change is made.\n\nThe state of the $i$-th paper tape can be represented by a sequence of length $n$, where each element is `0`, `1`, or `-` (for an empty cell), describing the state of each cell. The initial state of the $i$-th paper tape is called the input $X_i$, and the state after the operation sequence has been fully executed is called the output $Y_i$. Note: If a robot explodes, then this robot will not produce any output.\n\nIt can be observed that if a cell is empty, the robot will never modify its state. Therefore, each robot has the following property: If all the cells in the paper tape of the $i$-th robot are empty, the robot will not perform any operations, and the output will also have all cells empty.\n\nNow, Little R provides the input $X_i$ (initial state of each paper tape) and target output $Y_i$ for each robot. Little R wants Little D to find a position $p$ ($0 \\le p < n$) such that **all robots** can start from the $p$-th cell on their respective paper tapes, complete the operations without exploding, and ultimately produce output $Y_i$ for the $i$-th robot.\n\nLittle D solves the problem in a few milliseconds, but he is now curious to know how many combinations of input and output configurations exist such that the above conditions can be satisfied for at least one position $p$ ($0 \\le p < n$). In other words, how many ways can inputs $X_0, X_1, \\ldots, X_{m-1}$ and target outputs $Y_0, Y_1, \\ldots, Y_{m-1}$ be defined such that there exists at least one position $p$ that allows all robots to satisfy the conditions described. Since the final answer can be very large, output the result modulo ${10}^9 + 7$.\n\nTwo configurations are considered different if and only if there exists at least one robot with a different input or target output in the two configurations.\n\n---\n\n### Input Format\n\nThe first line contains two positive integers $n$ and $m$, representing the number of cells on each paper tape and the number of paper tapes, respectively.\n\nThe next $m$ lines each contain a string $S_i$ consisting only of the characters `R`, `0`, `1`, and `*`. The string $S_i$ represents the operation sequence for the $i$-th robot.\n\n---\n\n### Output Format\n\nOutput a single positive integer representing the result modulo ${10}^9 + 7$.\n\n---\n\n### **Sample Explanation #1**\n\n| Combination No. | Input $X_0$ | Target Output $Y_0$ | Valid Starting Position $p$ |\n|:-:|:-:|:-:|:-:|\n| $1$ | `--` | `--` | $0, 1$ |\n| $2$ | `0-` | `1-` | $0$ |\n| $3$ | `1-` | `1-` | $0$ |\n| $4$ | `-0` | `-1` | $0$ |\n| $5$ | `-1` | `-0` | $0$ |\n| $6$ | `00` | `11` | $0$ |\n| $7$ | `10` | `11` | $0$ |\n| $8$ | `01` | `10` | $0$ |\n| $9$ | `11` | `10` | $0$ |\n\nHere, `-` represents an empty cell. Observe that in combination $1$, both the input and output are entirely empty, so multiple valid starting positions ($p = 0$, $p = 1$) are available. \n\nWhen the input is not entirely empty, only the position $p = 0$ is a valid starting location, as starting from $p = 1$ will cause the robot to explode. For example, in combination $2$, the target output `1-` comes from modifying the first cell to `1` and leaving the second cell unchanged (`-`).\n\n---\n\n### **Sample Explanation #2**\n\nThis sample can be solved using the principle of inclusion-exclusion (details omitted for brevity). The final answer is $1468$.\n\n---\n\n### Constraints\n\nFor all test cases: $1 \\le n \\le 32$, $1 \\le m \\le 1000$, $1 \\le |S_i| \\le 100$.\n\n| Test Case Index | $n$ (Max) | $m$ (Max) | Special Constraints |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 2$ | $1$ | $1$ | None |\n| $3$ | $8$ | $1$ | None |\n| $4$ | $16$ | $1$ | None |\n| $5 \\sim 6$ | $32$ | $1$ | None |\n| $7$ | $16$ | $5$ | None |\n| $8 \\sim 10$ | $32$ | $5$ | None |\n| $11 \\sim 12$ | $16$ | $1000$ | None |\n| $13 \\sim 15$ | $32$ | $1000$ | A |\n| $16 \\sim 21$ | $32$ | $1000$ | B |\n| $22 \\sim 25$ | $32$ | $1000$ | None |\n\nSpecial Constraint A: No `R` exists in any operation sequence. \nSpecial Constraint B: Each operation sequence contains at most $15$ occurrences of `R`. \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3847, "prompt": "### Problem Description\n\n**For a sequence, the mode is defined as the number appearing strictly more than half the times in the sequence. Note that this definition differs from the conventional definition; for this problem, please adhere to the definition provided in the problem statement.**\n\nInitially, there are $n$ sequences of positive integers with varying lengths, numbered $1 \\sim n$. These initial sequences may be empty. The $n$ sequences are considered to exist, while other numbered sequences are considered nonexistent.\n\nThere are $q$ operations, which can be of the following types:\n\n- $1 \\ x \\ y$: Append the number $y$ to the end of sequence $x$. It is guaranteed that sequence $x$ exists, and $1 \\leq x, y \\leq n + q$.\n- $2 \\ x$: Remove the number at the end of sequence $x$. It is guaranteed that sequence $x$ exists, is non-empty, and $1 \\leq x \\leq n + q$.\n- $3 \\ m \\ x_1 \\ x_2 \\ x_m$: Concatenate the $x_1, x_2, \\ldots, x_m$ sequences in order to form a new sequence, and query its mode. If there is no number satisfying the aforementioned conditions, return $-1$. It is guaranteed that for any $1 \\leq i \\leq m$, $x_i$ is a sequence that still exists, $1 \\leq x_i \\leq n + q$, and the concatenated sequence is non-empty. **Note: $x_1, \\ldots, x_m$ are not guaranteed to be distinct, and the concatenation operation during queries will not affect subsequent operations.**\n- $4 \\ x_1 \\ x_2 \\ x_3$: Create a new sequence numbered $x_3$, which is formed by appending the numbers of sequence $x_2$ to the end of sequence $x_1$, then delete the sequences corresponding to $x_1$ and $x_2$. At this point, sequence $x_3$ is considered to exist, while sequences $x_1$ and $x_2$ are considered nonexistent and will no longer be used in subsequent operations. It is guaranteed that $1 \\leq x_1, x_2, x_3 \\leq n + q$, $x_1 \\neq x_2$, sequences $x_1, x_2$ exist before the operation, and no sequence has previously used the number $x_3$.\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $q$, representing the number of sequences and the number of operations, respectively. It is guaranteed that $n \\leq 5 \\times {10}^5$ and $q \\leq 5 \\times {10}^5$.\n\nThe following $n$ lines describe the initial sequences. The $i$-th line starts with a non-negative integer $l_i$, representing the initial number of elements in sequence $i$. This is followed by $l_i$ non-negative integers $a_{i,j}$, representing the numbers in sequence $i$ in order. Let $C_l = \\sum l_i$ represent the sum of the input sequence lengths. It is guaranteed that $C_l \\leq 5 \\times {10}^5$ and $a_{i,j} \\leq n + q$.\n\nThe following $q$ lines describe the operations, each consisting of several positive integers as specified in the problem description.\n\nLet $C_m = \\sum m$ represent the total number of sequences involved in all operations of type $3$. It is guaranteed that $C_m \\leq 5 \\times {10}^5$.\n\n### Output Format\n\nFor each query, output a single integer representing the result.\n\n**\u3010Sample Explanation \\#1\u3011**\n\nThe first query asks for the mode of sequence $1$. Since sequence $1$ contains two $1$s, which exceeds half of the sequence's length, the mode is $1$.\n\nThe second query asks for the mode of sequence $2$. Since sequence $2$ only contains $3$, the mode is $3$.\n\nThe third query asks for the mode of sequence $3$. At this point, sequence $3$ is $(3, 3, 3, 1, 1, 2)$. There is no number that appears more than $3$ times, so the output is $-1$.\n\n----\n\n**\u3010Sample Explanation \\#2\u3011**\n\nThe first query joins sequences $1, 2, 3, 4$ and asks for the mode. The concatenated sequence is $(1, 2, 3, 4)$, where no number appears more than half the length, so the output is $-1$.\n\nThe fourth query joins sequences $1, 2, 3, 4$ and asks for the mode. The concatenated sequence is $(1, 2, 2, 4, 4, 4, 4)$, where the mode is $4$.\n\n----\n\n**\u3010Sample \\#3\u3011**\n\nSee the `major/major3.in` and `major/major3.ans` files provided as attachments.\n\nThis sample satisfies the constraints for test cases $1 \\sim 3$.\n\n----\n\n**\u3010Sample \\#4\u3011**\n\nSee the `major/major4.in` and `major/major4.ans` files provided as attachments.\n\nThis sample satisfies the constraints for test cases $11 \\sim 12$.\n\n----\n\n### Constraints\n\nFor all test data, it is guaranteed that $1 \\leq n, q, C_m, C_l \\leq 5 \\times {10}^5$.\n\n| $n, q$ | $C_m, C_l$ | Test Case Range | Special Property A | Special Property B | Special Property C |\n|:-:|:-:|:-:|:-:|:-:|:-:|\n| $\\leq 300$ | $\\leq 300$ | $1 \\sim 3$ | No | No | Yes |\n| $\\leq 4000$ | $\\leq 4000$ | $4 \\sim 7$ | No | No | Yes |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $8$ | Yes | Yes | Yes |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $9$ | Yes | No | No |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $10$ | No | Yes | No |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $11 \\sim 12$ | No | No | Yes |\n| $\\leq {10}^5$ | $\\leq {10}^5$ | $13$ | No | No | No |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $14$ | Yes | Yes | Yes |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $15$ | Yes | No | No |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $16$ | No | Yes | No |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $17 \\sim 18$ | No | No | Yes |\n| $\\leq 5 \\times {10}^5$ | $\\leq 5 \\times {10}^5$ | $19 \\sim 20$ | No | No | No |\n\nSpecial Property A: Ensures $n = 1$ and no operations of type $4$. \nSpecial Property B: Ensures that at any time, any sequence only contains the numbers $1$ and $2$. \nSpecial Property C: Ensures no operations of type $2$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2719, "prompt": "### Problem Description\n\nRecently, Little S has developed a keen interest in bubble sort. To simplify the problem, Little S is only studying the bubble sort of **permutations of $1$ to $n$**.\n\nBelow is the algorithm description of bubble sort:\n\n```plain\nInput: A permutation p[1...n] of length n\nOutput: The sorted result of p\nfor i = 1 to n do\n for j = 1 to n - 1 do\n if(p[j] > p[j + 1])\n Swap the values of p[j] and p[j + 1]\n```The number of swaps in bubble sort is defined as the number of times the swapping process is executed. It can be proven that a lower bound of the number of swaps is $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$, where $p_i$ is the number in the $i$-th position of permutation $p$. If you are interested in the proof, refer to the hints.\n\nLittle S began focusing on permutations of length $n$ satisfying the condition that the number of swaps is equal to $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$. (For convenience, we'll call all such permutations \"Good\" permutations in the following text.) He further wondered how plentiful are such permutations and whether they are densely distributed.\n\nLittle S wants to calculate, for a given permutation $q$ of length $n$, the number of \"Good\" permutations that are lexicographically greater than $q$. Since he doesn't know how to do this, he seeks your help. Considering that the answer may be very large, you only need to output the result modulo $998244353$.\n\n### Input Format\n\nThe input consists of multiple test cases. \n\nThe first line contains a positive integer $T$, representing the number of test cases.\n\nFor each test case:\n- The first line contains a positive integer $n$, where $n \\leq 6 \\times 10^5$.\n- The second line consists of $n$ positive integers corresponding to $q_i$, which is a permutation of $1$ to $n$, as described in the problem.\n\n### Output Format\n\nThe output contains $T$ lines, one integer per line.\n\nFor each test case, output an integer representing the number of \"Good\" permutations, lexicographically greater than $q$, modulo $998244353$.\n\n### Additional Samples\n\nAdditional samples can be downloaded from the supplementary files.\n\n#### Sample 3\n\nSee the supplementary files `inverse3.in` and `inverse3.ans`.\n\n### Explanation for Sample 1\n\nAmong the permutations lexicographically greater than $1 \\ 3 \\ 2$, all of them except $3 \\ 2 \\ 1$ are \"Good\" permutations. Therefore, the answer is $3$.\n\n### Constraints\n\nBelow is the explanation of input sizes for each test point:\n\nFor all the data, it is guaranteed that $T = 5$ (the sample may not satisfy this).\n\nLet $n_\\mathrm{max}$ denote the maximum value of $n$ among all test cases, and $\\sum n$ denote the sum of all $n$s across test cases.\n\n| Test Point | $n_\\mathrm{max}$ | $\\sum n \\leq$ | Special Property |\n|:-:|:-:|:-:|:-:|\n| 1 | $8$ | $5 \\ n_\\mathrm{max}$ | None |\n| 2 | $9$ | $5 \\ n_\\mathrm{max}$ | None |\n| 3 | $10$ | $5 \\ n_\\mathrm{max}$ | None |\n| 4 | $12$ | $5 \\ n_\\mathrm{max}$ | None |\n| 5 | $13$ | $5 \\ n_\\mathrm{max}$ | None |\n| 6 | $14$ | $5 \\ n_\\mathrm{max}$ | None |\n| 7 | $16$ | $5 \\ n_\\mathrm{max}$ | None |\n| 8 | $16$ | $5 \\ n_\\mathrm{max}$ | None |\n| 9 | $17$ | $5 \\ n_\\mathrm{max}$ | None |\n| 10 | $18$ | $5 \\ n_\\mathrm{max}$ | None |\n| 11 | $18$ | $5 \\ n_\\mathrm{max}$ | None |\n| 12 | $122$ | $700$ | $\\forall i \\enspace q_i = i$ |\n| 13 | $144$ | $700$ | None |\n| 14 | $166$ | $700$ | None |\n| 15 | $200$ | $700$ | None |\n| 16 | $233$ | $700$ | None |\n| 17 | $777$ | $4000$ | $\\forall i \\enspace q_i = i$ |\n| 18 | $888$ | $4000$ | None |\n| 19 | $933$ | $4000$ | None |\n| 20 | $1000$ | $4000$ | None |\n| 21 | $266666$ | $2000000$ | $\\forall i \\enspace q_i = i$ |\n| 22 | $333333$ | $2000000$ | None |\n| 23 | $444444$ | $2000000$ | None |\n| 24 | $555555$ | $2000000$ | None |\n| 25 | $600000$ | $2000000$ | None |\n\n### Hints\n\nHere is a proof that the lower bound for the number of swaps is $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$.\n\nThe essence of sorting is moving numbers, so the total number of swaps should be describable in terms of the total moving distance of numbers. For the $i$-th position, suppose the number in this position in the initial permutation is $p_i$. Then we need to move this number to the $p_i$-th position, and the moving distance is $\\lvert i - p_i \\rvert$. Thus, the total moving distance is $\\sum_{i=1}^n \\lvert i - p_i \\rvert$. Since bubble sort swaps two adjacent numbers in each operation, each swap can reduce the total moving distance by at most $2$. Therefore, $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$ is a lower bound for the number of swaps in bubble sort.\n\nNote that not all permutations achieve this lower bound. For example, when $n = 3$, consider the permutation $3 \\ 2 \\ 1$. The number of swaps required in bubble sort is $3$, but $\\frac{1}{2} \\sum_{i=1}^n \\lvert i - p_i \\rvert$ is only $2$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3158, "prompt": "### Problem Description\n\nGiven two sequences of positive integers $\\{a_i\\}$ and $\\{b_i\\}$, both of length $n$ with indices ranging from $1$ to $n$, you are required to choose **exactly** $K$ indices from each sequence. The goal is to ensure that **at least** $L$ indices are selected from both sequences (i.e., the same indices for both sequences) while maximizing the total sum of the elements corresponding to the selected indices.\n\nFormally, you need to determine two subsequences $\\{c_i\\}$ and $\\{d_i\\}$ of length $K$, subject to the following constraints:\n\n$$\n1 \\leq c_1 < c_2 < \\ldots < c_K \\leq n, \\quad 1 \\leq d_1 < d_2 < \\ldots < d_K \\leq n,\n$$\n\nand\n\n$$\n\\Big| \\{c_1, c_2, \\ldots, c_K\\} \\cap \\{d_1, d_2, \\ldots, d_K\\} \\Big| \\geq L,\n$$\n\nsuch that the following sum is maximized:\n\n$$\n\\sum_{i=1}^K a_{c_i} + \\sum_{i=1}^K b_{d_i}.\n$$\n\n### Input Format\n\nRead the input from a file named `sequence.in`.\n\n**The input file contains multiple test cases.**\n\n- The first line contains a positive integer $T$, the number of test cases.\n- For each test case, three lines are provided:\n 1. The first line contains three integers $n$, $K$, and $L$, which are described in the problem statement.\n 2. The second line contains $n$ integers, specifying the sequence $\\{a_i\\}$.\n 3. The third line contains $n$ integers, specifying the sequence $\\{b_i\\}$.\n\n### Output Format\n\nWrite the output to a file named `sequence.out`.\n\nFor each test case, output a single line containing an integer: the maximum possible total sum.\n\n### Example\n\n**Input:**\n\n```\n2\n5 2 1\n1 2 3 4 5\n5 4 3 2 1\n6 3 2\n10 20 30 40 50 60\n60 50 40 30 20 10\n```**Output:**\n\n```\n16\n210\n```\n\n### Explanation of Example\n\n- For the first test case, choose $\\{c_i\\} = \\{4, 5\\}$ from $\\{a_i\\}$ and $\\{d_i\\} = \\{3, 4\\}$ from $\\{b_i\\}$, ensuring at least one overlapping index (in this case, index $4$). The total sum is $4 + 5 + 3 + 4 = 16$.\n- For the second test case, choose $\\{c_i\\} = \\{4, 5, 6\\}$ from $\\{a_i\\}$ and $\\{d_i\\} = \\{1, 2, 3\\}$ from $\\{b_i\\}$, ensuring at least two overlapping indices. The total sum is $40 + 50 + 60 + 60 + 50 + 40 = 210$.\n\n### Constraints and Hints\n\nFor all test points:\n\n- $T \\leq 10$,\n- $1 \\leq \\sum n \\leq 10^6$,\n- $1 \\leq L \\leq K \\leq n \\leq 2 \\times 10^5$,\n- $1 \\leq a_i, b_i \\leq 10^9$.\n\nSpecific constraints for individual test points:\n\n| Test Point ID | $n \\leq$ | $\\sum n \\leq$ |\n|---------------|----------------|-------------------|\n| $1 \\sim 3$ | $10$ | $3 \\times 10^5$ |\n| $4, 5$ | $18$ | $3 \\times 10^5$ |\n| $6, 7$ | $30$ | $3 \\times 10^5$ |\n| $8 \\sim 10$ | $150$ | $3 \\times 10^5$ |\n| $11 \\sim 16$ | $2 \\times 10^3$| $3 \\times 10^5$ |\n| $17 \\sim 21$ | $2 \\times 10^5$| $3 \\times 10^5$ |\n| $22 \\sim 25$ | $2 \\times 10^5$| $10^6$ |\n\nExample input and output files can be found in the contestant's directory at `sequence/sequence2.in`, `sequence/sequence2.ans`, `sequence/sequence3.in`, and `sequence/sequence3.ans`.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2721, "prompt": "### Problem Description\n\nD recently discovered an online mini-game. The rules are as follows:\n\n- The objective of the game is to defeat $n$ dragons in sequential order numbered $1 \\rightarrow n$. Each dragon has an initial health value $a_i$. Additionally, each dragon has a regeneration ability: when activated, the dragon\u2019s health increases by $p_i$ each time, continuing until its health is non-negative. A dragon only dies if its \"final\" health value is **exactly zero** after attacks and regeneration.\n- At the start of the game, the player has $m$ swords with known attack values. When facing a dragon, the player can choose only one sword to use. Once the dragon is slain, the sword used is lost; however, the player is awarded a new sword as a reward.\n\nThough D quickly became bored of this game, she learned that the fastest clearing player could qualify to compete in ION2018. As a result, D wants to develop a simple robot to clear the game. The robot operates using the following methodology:\n\n- When facing a dragon, the robot chooses the sword with the **highest attack power** among those with attack power less than or equal to the dragon's initial health. If no such sword exists, the robot chooses the **lowest attack power** sword.\n- Against each dragon, the robot will attack it exactly $x$ times using the selected sword, reducing the dragon's health by $x \\times ATK$, where $ATK$ is the attack power of the sword.\n- Subsequently, the dragon starts regenerating health using its regeneration ability, increasing its health by $p_i$ after each regeneration. If the dragon\u2019s health becomes zero either before the first regeneration step or after some subsequent regeneration step, the dragon is defeated, and the player advances to the next level.\n\nClearly, the number of attacks performed by the robot is the crucial factor in determining how quickly the game is cleared. D now has detailed information about the properties of all dragons. She wants to test your intuition: can you determine the minimum number of attacks $x$ required by the robot to clear the game? \n\nIf clearing the game is impossible regardless of the setting for $x$, output $-1$.\n\n---\n\n### Input Format\n\nThe first line contains an integer $T$, representing the number of test cases.\n\nFollowing are $T$ test cases, each consisting of five lines:\n\n- The first line of each test case contains two integers, $n$ and $m$, representing the number of dragons and the initial number of swords.\n- The second line contains $n$ positive integers, where the $i$-th number $a_i$ represents the initial health of the $i$-th dragon.\n- The third line contains $n$ positive integers, where the $i$-th number $p_i$ represents the regeneration ability of the $i$-th dragon.\n- The fourth line contains $n$ positive integers, where the $i$-th number denotes the attack power of the sword rewarded for defeating the $i$-th dragon.\n- The fifth line contains $m$ positive integers, representing the attack power of the initial $m$ swords.\n\n---\n\n### Output Format\n\nOutput consists of $T$ lines.\n\nThe $i$-th line contains a single integer, representing the minimum number of attacks $x$ required for the robot to clear the game for the $i$-th test case. If clearing the game is impossible, output $-1$.\n\n---\n\n### Additional Examples\n\nDownload additional examples from the provided files.\n\n---\n\n### Example 2\n\nRefer to the files `dragon2.in` and `dragon2.ans`.\n\n---\n\n### Explanation of Example 1\n\nFor the first test case:\n\n- The robot starts with swords of attack power $\\{1,9,10\\}$. For the first dragon with health $3$, the robot chooses the sword with attack power $1$, and attacks $59$ times, dealing $59$ damage. The dragon\u2019s health becomes $-56$. It regenerates $14$ times until its health is precisely $0$, then dies.\n \n- The sword with attack power $1$ is lost. The robot receives a sword with attack power $7$. The current swords have attack power $\\{7,9,10\\}$. For the second dragon with health $5$, the robot chooses the sword with attack power $7$, and attacks $59$ times, dealing $413$ damage. The dragon\u2019s health becomes $-408$. It regenerates $68$ times until its health is precisely $0$, then dies.\n\n- Now the robot's swords have attack power $\\{3,9,10\\}$. For the third dragon with health $7$, the robot chooses the sword with attack power $3$, and attacks $59$ times, dealing $177$ damage. The dragon\u2019s health becomes $-170$. It regenerates $17$ times until its health is precisely $0$, then dies.\n\n- There is no faster way to clear the level with fewer than $59$ attacks per dragon. Thus, the answer is $59$.\n\nFor the second test case:\n\nIt is impossible to kill the first dragon and the second dragon simultaneously. Thus, the output is $-1$.\n\n---\n\n### Subtasks\n\n| Test Case ID | $n$ | $m$ | $p_i$ | $a_i$ | Attack Power | Other Constraints |\n|-|-|-|-|-|-|-|\n| 1 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $=1$ | None |\n| 2 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $=1$ | None |\n| 3 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $\\leq 10^5$ | None |\n| 4 | $\\leq 10^5$ | $=1$ | $=1$ | $\\leq 10^5$ | $\\leq 10^5$ | None |\n| 5 | $\\leq 10^3$ | $\\leq 10^3$ | $\\leq 10^5$ | $\\leq 10^5$ | $\\leq 10^5$ | Property 1, Property 2 |\n| 6 | $\\leq 10^3$ | $\\leq 10^3$ | $\\leq 10^5$ | $\\leq 10^5$ | $\\leq 10^5$ | Property 1, Property 2 |\n| 7 | $\\leq 10^3$ | $\\leq 10^3$ | $\\leq 10^5$ | $\\leq 10^5$ | $\\leq 10^5$ | Property 1, Property 2 |\n| 8 | $=1$ | $=1$ | $\\leq 10^8$ | $\\leq 10^8$ | $\\leq 10^6$ | Property 1 |\n| ... | ... | ... | ... | ... | ... | ... |\n\n**Property 1**: For any $i$, $a_i \\leq p_i$. \n**Property 2**: $\\operatorname{lcm}(p_i) \\leq 10^6$, i.e., the **least common multiple** of all $p_i$ is no greater than $10^6$.\n\nFor all test cases, $T \\leq 5$, all sword attack powers $\\leq 10^6$, and the least common multiple of all $p_i \\leq 10^{12}$. \n\nIt is guaranteed that $T$, $n$, and $m$ are positive integers.\n\n---\n\n### Notes\n\nIntermediate results may become very large. Ensure that your variable types can adequately store intermediate values.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2306, "prompt": "### Problem Description\n\nLittle N is the manager of a vegetable warehouse and is responsible for designing vegetable sales plans. \nIn the vegetable warehouse, there are a total of $n$ types of vegetables. Little N needs to consider various factors based on the characteristics of each vegetable to design an optimal sales plan to maximize revenue. \n\nWhen calculating the revenue from selling vegetables, selling one unit of the $i$-th type of vegetable will bring in a revenue of $a_i$. \nParticularly, since policies encourage diversified sales, the first unit of the $i$-th type of vegetable sold will also yield an additional revenue of $s_i$. \n\nAt the beginning of the operation, the initial inventory of the $i$-th type of vegetable is $c_i$ units. \nHowever, vegetables have a very limited freshness period. Once spoiled, they can no longer be sold. Fortunately, Little N has already calculated the spoilage time for every unit of vegetable: for the $i$-th type of vegetable, there is a freshness value $x_i$, meaning $x_i$ units of the vegetable will spoil at the end of every day until all units are spoiled. (Note: The spoilage time for each unit of vegetable is fixed and does not change with sales.) \n\nFormally: for all positive integers $d$ satisfying $d \\times x_i \\leq c_i$, $x_i$ units of the $i$-th type of vegetable will spoil at the end of the $d$-th day. \nParticularly, if $(d-1) \\times x_i \\leq c_i < d \\times x_i$, then $c_i - (d-1) \\times x_i$ units of the vegetable will spoil at the end of the $d$-th day. \nNote that if $x_i = 0$, it means this type of vegetable will not spoil. \n\nIn addition, the total quantity of vegetables sold each day is also limited and cannot exceed $m$ units. \n\nNow, Little N has $k$ queries and wants your help to calculate the results. Each query is in the form of a given $p_j$, asking: if the sales last for $p_j$ days, what is the maximum revenue that can be obtained?\n\n---\n\n### Input Format\n\nThe first line contains three positive integers $n, m, k$, representing the number of vegetable types, the daily maximum sales limit, and the number of queries, respectively. \nThe next $n$ lines each contain four non-negative integers describing the characteristics of one type of vegetable: $a_i, s_i, c_i, x_i$, as described above. \nThe next $k$ lines each contain a non-negative integer $p_j$, as described above.\n\n---\n\n### Output Format\n\nOutput $k$ lines, each containing a single integer. The $i$-th line represents the answer to the $i$-th query.\n\n---\n\n### Sample\n\n```\nInput\n2 10 1\n5 10 100 5\n4 0 50 0\n1\n\nOutput\n65\n```---\n\n### Data Range and Constraints\n\n| Test Case ID | $n$ | $m$ | $p_j$ | Characteristic $1$ | Characteristic $2$ |\n| :----------: | :--------: | :------: | :--------: | :-----------------: | :----------------------: |\n| $1$ | $\\leq 2$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $2$ | $\\leq 3$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $3$ | $\\leq 4$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $4$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 2$ | None | None |\n| $5$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 3$ | None | None |\n| $6$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 4$ | None | None |\n| $7$ | $\\leq 4$ | $\\leq 1$ | $\\leq 4$ | None | None |\n| $8$ | $\\leq 6$ | $\\leq 2$ | $\\leq 6$ | None | None |\n| $9$ | $\\leq 8$ | $\\leq 1$ | $\\leq 8$ | None | None |\n| $10$ | $\\leq 10$ | $\\leq 2$ | $\\leq 10$ | None | None |\n| $11$ | $\\leq 20$ | $\\leq 3$ | $\\leq 20$ | None | None |\n| $12$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | Present | None |\n| $13$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | None | Present |\n| $14$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | None | None |\n| $15$ | $\\leq 10^2$ | $\\leq 10$ | $\\leq 10^2$ | None | None |\n| $16$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | Present | Present |\n| $17$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | Present | None |\n| $18$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | None | Present |\n| $19$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $20$ | $\\leq 10^3$ | $\\leq 10$ | $\\leq 10^3$ | None | None |\n| $21$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | Present | Present |\n| $22$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | Present | None |\n| $23$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | None | Present |\n| $24$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | None | None |\n| $25$ | $\\leq 10^5$ | $\\leq 10$ | $\\leq 10^5$ | None | None |\n\n- Characteristic $1$: All $s_i$ are $0$. \n- Characteristic $2$: All $x_i$ are $0$. \n\nFor all test cases, it is guaranteed that the $k$ queries $p_j$ are distinct, and $0 < a_i, c_i \\leq 10^9$, $0 \\leq s_i, x_i \\leq 10^9$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3982, "prompt": "### Problem Description\n\nIn recent years, Country A has experienced rapid commercial development. However, its road infrastructure has not kept pace, significantly constraining trade and travel. The government has been working tirelessly to address this issue.\n\nSpecifically, Country A consists of $2^n - 1$ cities, where City $1$ is the capital. For every non-capital city $i$, there is a **one-way** road from City $i$ to City $\\lfloor \\frac{i}{2} \\rfloor$. For convenience, these roads are referred to as \"Type-1 Roads,\" and City $\\lfloor \\frac{i}{2} \\rfloor$ is called the \"superior city\" of City $i$.\n\nIn addition, there are $m$ other **one-way** roads. The $i$-th of these roads connects City $u_i$ to City $v_i$ and possesses a unique property: starting from City $v_i$ and continuously following Type-1 Roads toward superior cities will eventually lead to City $u_i$. Such roads are referred to as \"Type-2 Roads.\"\n\nEach road has an associated length. Consequently, for any two cities $x$ and $y$ in Country A, we can compute the minimum total length of roads required to travel from City $x$ to City $y$, denoted as $dist(x, y)$. However, due to the poor state of road infrastructure, it may not be possible to travel from City $x$ to City $y$ at all. In such cases, $dist(x, y)$ is defined to be $0$. Additionally, the distance from a city to itself is $0$, i.e., $dist(x, x) = 0$.\n\nThe government wishes to calculate the sum of all $dist(x,y)$ values to better evaluate the convenience of trade and travel. However, since there are too many cities, listing all such values is infeasible. Instead, they want to compute the sum $\\sum_{x=1}^{2^n-1}\\sum_{y=1}^{2^n-1} dist(x, y)$ and have asked for your help in solving this task.\n\n### Input Format\n\nThe first line of input contains two positive integers $n$ and $m$.\n\nThe second line of input contains $2^n - 2$ positive integers. The $i$-th integer $a_i$ represents the length of the \"Type-1 Road\" from City $i+1$ to City $\\lfloor \\frac{i+1}{2} \\rfloor$.\n\nThe next $m$ lines each contain three positive integers $u, v, w$, describing a \"Type-2 Road\" from City $u$ to City $v$ with a length of $w$.\n\n### Output Format\n\nOutput one line containing a single positive integer, representing the answer. Since the result may be very large, output the result modulo $998244353$.\n\n**\u3010Constraints\u3011**\n\nAll test data satisfy the following constraints: \n$2 \\leq n \\leq 18$, $1 \\leq m \\leq 2^n$, $1 \\leq u, v \\leq 2^n - 1$, $1 \\leq a_i, w \\leq 10^9$.\n\n| Test Case ID | $n$ | $m$ | Special Property? |\n| :---: | :---: | :---: | :---: |\n| $1\\sim 2$ | $=8$ | $\\leq 256$ | No |\n| $3\\sim 4$ | $=9$ | $\\leq 512$ | No |\n| $5\\sim 8$ | $=12$ | $\\leq 4,096$ | No |\n| $9$ | $=16$ | $\\leq 10$ | No |\n| $10$ | $=16$ | $\\leq 50$ | No |\n| $11$ | $=16$ | $\\leq 100$ | No |\n| $12$ | $=16$ | $\\leq 65,536$ | Yes |\n| $13\\sim 15$ | $=16$ | $\\leq 65,536$ | No |\n| $16\\sim 17$ | $=18$ | $\\leq 262,144$ | Yes |\n| $18\\sim 20$ | $=18$ | $\\leq 262,144$ | No |\n\nSpecial Property: If present, all \u201cType-2 Roads\u201d start from the capital (City $1$). \n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 2315, "prompt": "### Problem Description\n\nXiao Ming is learning a new programming language called A++. Having just mastered loop statements, he excitedly wrote many programs and calculated their time complexities himself. However, his programming teacher is unwilling to check each of Xiao Ming\u2019s programs one by one. This is where you step in! Please write a program to determine whether the time complexity given by Xiao Ming for each of his programs is correct.\n\nIn the A++ language, the loop structure is as follows:\n\n```plain\nF i x y\n Loop Body\nE\n```Here, `F i x y` represents the creation of a new variable $i$ (note that variable $i$ cannot have the same name as any currently existing variable that has not been destroyed) initialized to $x$. Then, it compares $i$ with $y$. If $i$ is less than or equal to $y$, the loop starts; otherwise, it does not. After the end of each loop iteration, $i$ will increment by 1. The loop terminates when $i$ exceeds $y$.\n\n$x$ and $y$ can be either positive integers ($x$ and $y$ have no predetermined size relationship) or the variable $n$. The variable $n$ represents the data size and must be retained in complexity calculations without being treated as a constant. This variable is significantly larger than $100$.\n\n`E` marks the end of the loop body. When the loop body ends, the variables created by this loop are destroyed.\n\n**Note**: To simplify notation in the problem, we use capital letter $O$ to represent the commonly understood concept of $\\Theta$ in time complexity.\n\n---\n\n### Input Format\n\nThe first line of the input file contains a positive integer $t$, representing the number of programs to analyze $(t \\leq 10)$. For each program, we only extract the `F i x y` and `E` statements to calculate the time complexity. Note that the loop structures may have nested loops.\n\nThe first line of each program contains a positive integer $L$ and a string denoting the program\u2019s time complexity. Complexity is described as `O(1)` for constant complexity, or `O(n^w)` for complexity proportional to $n^w$, where $w$ is a positive integer less than $100$. The input guarantees that only these two forms of complexity (`O(1)` and `O(n^w)`) are present (without quotation marks).\n\nThe next $L$ lines represent the loop structure of the program: either `F i x y` or `E`.\n\n- Lines starting with `F` denote the beginning of a loop, followed by three space-separated tokens `i x y`. Here, $i$ is a lowercase English letter (guaranteed not to be `n`), indicating the newly declared variable name. $x$ and $y$ can be either positive integers (known to be less than $100$) or `n`. \n- **Important Note**: In the 10th test case, there may be instances of variable names being `n`, which contradicts the earlier description.\n- Lines starting with `E` mark the end of the loop body.\n\n---\n\n### Output Format\n\nThe output contains $t$ lines, corresponding to the $t$ programs provided in the input. Each line should output `Yes`, `No`, or `ERR`:\n- If the program\u2019s actual complexity matches the provided complexity, output `Yes`.\n- If the complexity does not match, output `No`.\n- If the program contains a syntax error, output `ERR`. Syntax errors are of two types:\n 1. Mismatched `F` and `E` statements.\n 2. A variable being redefined within a loop while it is already defined but has not yet been destroyed.\n\n**Note**: Even if a syntax error appears inside a loop body that will not execute at runtime, the program is considered to have a compile-time error and should output `ERR`.\n\n---\n\n### Examples\n\n1. The first program has $i$ loop from $1$ to $1$, resulting in constant complexity (`O(1)`).\n2. The second program has $x$ loop from $1$ to $n$, resulting in a complexity of $n$ ($O(n^1)$).\n3. The third program contains an unmatched `F` statement without a corresponding `E`, causing a syntax error.\n4. The fourth program contains a nested loop structure, resulting in $n^2$ complexity (`O(n^2)`).\n5. The fifth program consists of two independent loops, each with complexity $n$. The overall complexity is $n$ ($O(n^1)`).\n6. The sixth program has a first loop that executes normally, but the second loop terminates immediately (as $n$ is significantly larger than $100$, and $100 > 4`).\n7. The seventh program\u2019s first loop does not execute at all, resulting in constant complexity (`O(1)`).\n8. The eighth program contains a variable `x` in the second loop that redefines a variable already defined in the first loop, resulting in a syntax error (`ERR`).\n\n---\n\n### Constraints and Notes\n\n**Constraints**:\n- For $30\\%$ of the test cases:\n - No syntax errors exist.\n - The first $L/2$ lines of each program will always start with `F`, while the last $L/2$ lines will start with `E`.\n - $L \\leq 10$.\n - If both $x$ and $y$ are integers, it is guaranteed that $x < y$, and only $y$ may be equal to `n`.\n\n- For $50\\%$ of the test cases:\n - No syntax errors exist.\n - $L \\leq 100$.\n - If both $x$ and $y$ are integers, it is guaranteed that $x < y$, and only $y$ may be equal to `n`.\n\n- For $70\\%$ of the test cases:\n - No syntax errors exist.\n - $L \\leq 100$.\n\n- For $100\\%$ of the test cases:\n - $t \\leq 10$, $L \\leq 100`.\n\n---\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2722, "prompt": "### Problem Description\n\nIn recent years, Country C and Country D have been caught in the chaos of war.\n\nRecently, Country C successfully infiltrated a city in Country D. This city can be abstracted as an undirected graph with $n$ nodes and $n-1$ bidirectional edges connecting the nodes, ensuring that any two nodes can reach each other. In other words, this undirected graph is actually a tree.\n\nThrough reconnaissance, the intelligence minister of Country C, GGB, was surprised to find that this seemingly inconspicuous city is the military hub of Country D. Therefore, GGB decided to establish intelligence agencies within the city. After investigation, intelligence expert TAC organized $m$ options to set up these agencies. According to option $i$, intelligence officers would be stationed along all the edges on the shortest path between node $x_i$ and node $y_i$, incurring a cost of $v_i$.\n\nHowever, due to manpower constraints, GGB can implement only two of the $m$ options. Furthermore, TAC pointed out that for better cooperation between these two intelligence agencies, their surveillance areas must **share at least one edge**. To evaluate the performance of an option, GGB and TAC surveyed all the edges and assigned each edge an intelligence value $c_i$, which represents the monetary benefit ($c_i$) derived from gathering intelligence on this edge. Note that intelligence is unique, so an edge being monitored by two agencies will still yield only $c_i$ monetary benefit.\n\nNow, your task is to help GGB select two legal options to implement such that the surveillance areas of the two options share at least one edge, and the **difference between the total benefit and the total cost** is maximized.\n\nNote: This value may be negative, but it is still considered valid. If no such pair of options can be found, output `F`.\n\n---\n\n### Input Format\n\nInput is read from the file `center.in`.\n\nThis problem consists of multiple test cases.\n\nThe first line of the input file contains an integer $T$, representing the number of test cases.\n\nEach test case contains $(n + m + 1)$ lines:\n\n1. The first line contains an integer $n$, representing the number of nodes in the city.\n2. The next $n-1$ lines contain three integers $a_i$, $b_i$, and $c_i$, representing a bidirectional edge connecting node $a_i$ to node $b_i$ with an intelligence value of $c_i$. It is guaranteed that $a_i < b_i$, and $b_i$ values are distinct.\n3. The $(n+1)$-th line contains an integer $m$, representing the number of options provided by TAC for establishing intelligence agencies.\n4. The following $m$ lines contain three integers $x_i$, $y_i$, and $v_i$, representing the $i$-th option for establishing an intelligence agency. According to this option, intelligence officers are stationed on all the edges along the shortest path between nodes $x_i$ and $y_i$, incurring a cost of $v_i$.\n\n---\n\n### Output Format\n\nOutput to the file `center.out`.\n\nThe output file contains $T$ lines.\n\nFor each test case, output a single line: If a legal pair of options exists, output the maximum difference between the total benefit and the total cost. Otherwise, output `F`.\n\n---\n\n### Example\n\nThis example contains two test cases. In both cases, the city structure remains the same, but the intelligence values and agency options differ. The city's graph is as follows:\n\n![](https://i.loli.net/2018/07/20/5b519ef60c198.png)\n\n#### Test Case 1\n\n- In Option 1, the shortest path from node $1$ to node $4$ is $1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4$. \n- In Option 2, the shortest path from node $3$ to node $5$ is $3 \\rightarrow 2 \\rightarrow 1 \\rightarrow 5$. \n\nChoosing these two options incurs a cost of $5 + 8 = 13$. All edges are monitored, yielding a total benefit of $1 + 3 + 2 + 8 = 14$. Thus, the difference between total benefit and total cost is $14 \u2212 13 = 1$.\n\n#### Test Case 2\n\n- In Option 1, the shortest path from node $1$ to node $5$ is $1 \\rightarrow 5$. \n- In Option 2, the shortest path from node $2$ to node $3$ is $2 \\rightarrow 3$. \n\nThere is no shared edge between these two options. Thus, this test case has no legal solution, and the output is `F`.\n\n---\n\nSee the attached files `center2.in` and `center2.ans`. \n\nThis example includes only one test case. For this test case, the optimal solution is to choose Option 2 and Option 3.\n\nThe city's graph is as follows. **Bold** edges represent those being monitored. Red edges are monitored only by Option 2, blue edges are monitored only by Option 3, and purple edges are monitored by both options.\n\n![](https://i.loli.net/2018/07/20/5b51a17325aed.png)\n\n---\n\nSee the attached files `center3.in` and `center3.ans`.\n\nThis example shares the same structure as the fourth test case described below. You can utilize this test case for robust debugging and testing.\n\n---\n\n### Data Ranges and Hints\n\nThe scale and properties of each test case are indicated in the table below:\n\n| Test Point | $n \\le$ | $m \\le$ | $T \\le 50$ | Special Properties |\n| :-: | :-: | :-: | :-: | :-: |\n| 1 | $2$ | $3$ | Guaranteed | None |\n| 2 | $10$ | $30$ | Guaranteed | None |\n| 3 | $200$ | $300$ | Guaranteed | None |\n| 4 | $10^3$ | $2,000$ | Guaranteed | $a_i = b_i - 1$ |\n| 5 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $a_i = b_i - 1$ |\n| 6 | $5 \\times 10^4$ | $3 \\times 10^4$ | Guaranteed | $a_i = b_i - 1$ |\n| 7 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $c_i = 0$ |\n| 8 | $5 \\times 10^4$ | $10^5$ | Guaranteed | $c_i = 0$ |\n| 9 | $5 \\times 10^4$ | $10^5$ | Guaranteed | $c_i = 0$ |\n| 10 | $10^4$ | $n$ | Guaranteed | $S_1$ |\n| 11 | $5 \\times 10^4$ | $n$ | Not Guaranteed | $S_1$ |\n| 12 | $5 \\times 10^4$ | $n$ | Not Guaranteed | $S_1$ |\n| 13 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $S_2$ |\n| 14 | $10^4$ | $3 \\times 10^4$ | Guaranteed | $S_2$ |\n| 15 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | $S_2$ |\n| 16 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | $S_2$ |\n| 17 | $10^4$ | $3 \\times 10^4$ | Guaranteed | None |\n| 18 | $5 \\times 10^4$ | $10^5$ | Guaranteed | None |\n| 19 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | None |\n| 20 | $5 \\times 10^4$ | $10^5$ | Not Guaranteed | None |\n\n#### Special Properties:\n1. Property $S_1$: For any $i$ and $j$, it is guaranteed that the smallest indexed node on the shortest path between $x_i$ and $y_i$ differs from the smallest indexed node on the shortest path between $x_j$ and $y_j$.\n2. Property $S_2$: For any $i$, the smallest indexed node on the shortest path between $x_i$ and $y_i$ is guaranteed to be node $1$.\n\n#### Constraints:\nFor all test cases:\n- $1 \\le n \\le 5 \\times 10^4$\n- $0 \\le m \\le 10^5$\n- $0 \\le c_i \\le 10^9$\n- $0 \\le v_i \\le 10^{10} \\times n$\n\nThe sum of all $n$ across all test cases does not exceed $1,000,233$, and the sum of all $m$ does not exceed $2,000,233$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3567, "prompt": "### Problem Description\n\nThe game is played on a rectangular grid-based chessboard of dimensions $n$ rows by $m$ columns. The chess pieces are placed at the grid's intersections. Let the top-left intersection be represented as $(1,1)$ and the bottom-right intersection as $(n,m)$.\n\nThe chess pieces are divided into two colors: black and white. Each player controls one color.\n\nIn addition to color, each chess piece has a level, denoted as $\\mathit{col}_i$ for the color of piece $i$ and $\\mathit{lv}_i$ for its level. Furthermore, the grid lines of the chessboard have $4$ possible states, where the state of the $i$-th grid line is denoted as $\\mathit{opt}_i$.\n\nWhen it is a player's turn, they can select one of their own chess pieces and move it along the grid lines to another intersection, referred to as a \"move\". The formal definition of making a \"move\" involves selecting a sequence of coordinates $(x_0,y_0),(x_1,y_1),\\ldots,(x_k,y_k)$. Here, $k$ is any chosen positive integer, $(x_0,y_0)$ is the initial position of the piece, and $(x_k,y_k)$ is the final destination. The following conditions must be satisfied:\n\n- For all $i = 0,1,\\ldots,k-1$, the coordinates $(x_i,y_i)$ and $(x_{i+1},y_{i+1})$ must be directly connected by a grid line. This means **all moves must follow grid lines**.\n- For all $i \\neq j$, $(x_i,y_i) \\neq (x_j,y_j)$. In other words, the piece cannot pass through the same position more than once, and specifically, $(x_0,y_0) \\neq (x_k,y_k)$. That is, **the piece cannot remain stationary or return to its original position**.\n- For all $i = 1,\\ldots,k-1$, the position $(x_i,y_i)$ must not contain any chess piece. This means **the move cannot skip over any existing chess pieces**.\n- If there is no chess piece at $(x_k,y_k)$, the move is called a normal move. If there is a piece at $(x_k,y_k)$, the move is called a capture. In a capture move, if the moving piece has color $\\mathit{col}_1$ and level $\\mathit{lv}_1$, and the captured piece has color $\\mathit{col}_2$ and level $\\mathit{lv}_2$, the following conditions must hold: $\\mathit{col}_1 \\neq \\mathit{col}_2$ and $\\mathit{lv}_1 \\geq \\mathit{lv}_2$. In other words, **a piece can only capture an opponent's piece, and its level must be greater than or equal to the opponent's level**.\n\nAdditionally, note that a piece cannot continue moving after performing a capture.\n\nThe meanings of the grid line states are as follows:\n\n- If $\\mathit{opt}_i=0$, it means the path is blocked, and the piece cannot move through this grid line.\n- If $\\mathit{opt}_i=1$, it means the grid line is a \"normal road\", and the piece can pass through at most one normal road during a move.\n- If $\\mathit{opt}_i=2$, it means the grid line is a \"straight road\", and the piece can pass through any number of straight roads during a single move. However, the piece must move **strictly either horizontally or vertically without turning**. For example, moving from $(1,1)$ to $(1,2)$ and then to $(1,3)$ along straight roads is allowed, but moving from $(1,1)$ to $(1,2)$ and then to $(2,2)$ is not allowed.\n- If $\\mathit{opt}_i=3$, it means the grid line is an \"open road\", and the piece can pass through any number of open roads during a single move, with turns allowed.\n\nAdditionally, during a single move, **all grid lines along the path must be of the same state**. For instance, moving from $(1,1)$ to $(1,2)$ via a straight road and then to $(1,3)$ via an open road is not allowed.\n\nDetails such as how to determine the winner are not relevant to this problem and are thus omitted.\n\nAfter developing this board game, Little Z and Little C decided to improve their skills through a training strategy. Initially, the board is empty. Little C places a chess piece onto an empty intersection on the board at each step. Little Z needs to quickly calculate how many positions on the board can be reached if the newly placed chess piece is selected to make a move. Note: This is a mental training activity, and they do not actually move the pieces.\n\nHowever, Little Z found this calculation too difficult to perform, so he came to you for help.\n\n### Input Format\n\nEach test point consists of multiple data sets.\n\nThe first line contains a positive integer $T$, representing the number of data sets.\n\nFor each data set:\n\n- The first line contains three positive integers $n, m, q$, the number of rows, columns, and game rounds, respectively.\n- The next $n$ lines each contain a string of length $m - 1$, where each character is one of $\\texttt{0}$, $\\texttt{1}$, $\\texttt{2}$, or $\\texttt{3}$. The $j$-th character in the $i$-th line represents the state of the grid line connecting intersection $(i, j)$ to $(i, j+1)$. \n- The next $n - 1$ lines each contain a string of length $m$, where each character is one of $\\texttt{0}$, $\\texttt{1}$, $\\texttt{2}$, or $\\texttt{3}$. The $j$-th character in the $i$-th line represents the state of the grid line connecting intersection $(i, j)$ to $(i+1, j)$.\n- The next $q$ lines each contain $4$ non-negative integers $\\mathit{col}_i, \\mathit{lv}_i, x_i, y_i$, indicating that in the $i$-th round, a chess piece with color $\\mathit{col}_i$ and level $\\mathit{lv}_i$ is placed at the intersection $(x_i, y_i)$. Here, $\\mathit{col}_i = 0$ represents a black piece and $\\mathit{col}_i = 1$ represents a white piece. It is guaranteed that there was no chess piece at $(x_i, y_i)$ beforehand.\n\n### Output Format\n\nFor each data set, output $q$ lines. Each line contains a non-negative integer, representing the number of intersections that the $i$-th chess piece can reach after being placed.\n\n**Sample Explanation #1**\n\nAfter placing piece $1$, it can move to positions $(2, 1),(2, 2),(3, 2),(3, 3)$.\n\nAfter placing piece $2$, it can move to positions $(2, 2),(2, 3),(3, 1)$.\n\nAfter placing piece $3$, it can move to positions $(1, 1),(1, 3),(2, 2)$.\n\nAfter placing piece $4$, it can move to positions $(2, 2),(3, 1),(3, 3)$.\n\nAfter placing piece $5$, it can move to positions $(2, 3),(3, 2)$.\n\n### Constraints\n\n| Test Case | $n \\times m \\le$ | $q \\le$ | Special Notes |\n|:-:|:-:|:-:|:-:|\n| $1 \\sim 2$ | $100$ | $50$ | None |\n| $3 \\sim 6$ | $5000$ | $2000$ | None |\n| $7 \\sim 8$ | $2 \\times {10}^5$ | ${10}^5$ | No \"straight roads\" or \"open roads\" |\n| $9 \\sim 11$ | $2 \\times {10}^5$ | ${10}^5$ | No \"open roads\" |\n| $12 \\sim 14$ | $2 \\times {10}^5$ | ${10}^5$ | No \"straight roads\" |\n| $15 \\sim 16$ | $2 \\times {10}^5$ | ${10}^5$ | $\\mathit{lv}_i = i$ |\n| $17 \\sim 18$ | $2 \\times {10}^5$ | ${10}^5$ | $\\mathit{lv}_i = q - i + 1$ |\n| $19 \\sim 21$ | $2 \\times {10}^5$ | $2000$ | $n, m \\le 1000$ |\n| $22 \\sim 25$ | $2 \\times {10}^5$ | ${10}^5$ | None |\n\nFor $100\\%$ of the data, $1 \\le T \\le 5$, $2 \\le n, m \\le {10}^5$, $4 \\le n \\times m \\le 2 \\times {10}^5$, $1 \\le q \\le \\min \\{ {10}^5, n \\times m \\}$, $1 \\le \\mathit{lv}_i \\le q$, $1 \\le x_i \\le n$, $1 \\le y_i \\le m$, and $\\mathit{col}_i \\in \\{ 0, 1 \\}$.\n\nNote: Due to the large input and output size of this problem, it is recommended to use fast input and output methods.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3535, "prompt": "### Problem Description\nXiao Z is self-learning knowledge about quantum computers and has recently been studying the quantum communication chapter. During this study, he encountered an interesting problem. In this problem, Alice and Bob are performing quantum communication, and their communication language is a dictionary $S$ of size $n$. Each word $s_i$ ($1 \\leq i \\leq n$) in the dictionary can be represented as a $\\boldsymbol{256}$-bit binary string composed of $\\boldsymbol{0}$ and $\\boldsymbol{1}$. In this problem, $s_i$ can be generated by calling the function `gen`, which is implemented in `gen.cpp` that you can access in the problem's directory. The function takes parameters `n`, `a1`, and `a2`, which will be provided in the input data.\n\nAlice and Bob will conduct $m$ rounds of communication, and in each communication, Alice transmits **exactly one** word from the dictionary to Bob. However, the communication channel they use is not reliable due to noise interference. Specifically, in the $i$-th transmission, let's denote the original word that Alice transmits as $x_i$. This $256$-bit binary string may be affected by noise and could have at **most** $\\boldsymbol{k_i}$ bit flips. In other terms, let $y_i$ represent the $256$-bit binary string received by Bob after transmission. Compared to $x_i$, $y_i$ may differ by at most $k_i$ bits, and $y_i$ may not necessarily belong to the dictionary $S$.\n\nAt the same time, Bob learns that an adversary, Eve, has also infiltrated the communication channel and is attempting to disrupt their transmission. Eve's interference strategy involves altering the $256$-bit binary string received by Bob into **any arbitrary** $256$-bit binary string, which may not necessarily belong to dictionary $S$. Eve is cunning and **does not necessarily** interfere with every communication.\n\nNow, Bob seeks your help. For every communication round, based on the $256$-bit binary string Bob ultimately receives and the noise tolerance threshold $k_i$ ($0 \\leq k_i \\leq 15$), you need to determine whether it is **possible** that this communication was not interfered with by Eve. In other words, you need to check if it is possible that the received $256$-bit string can be transformed into a dictionary word with at most $k_i$ bit flips. If it is possible that Eve did not interfere, output $1$; otherwise, output $0$. Bob has full trust in your ability, so you need to provide answers **online** as described in the input format.\n\nTo reduce input processing time, the binary string received by Bob will be given as a $\\boldsymbol{64}$-character hexadecimal string ($16$-base string). The hexadecimal string consists of digits $\\texttt{0} \\sim \\texttt{9}$ and uppercase letters $\\texttt{A} \\sim \\texttt{F}$, where characters $\\texttt{A} \\sim \\texttt{F}$ correspond to values $10 \\sim 15$, respectively.\n\nA hexadecimal string can be converted character by character into a binary string. For example, `5` corresponds to `0101`, `A` corresponds to `1010`, and `C` corresponds to `1100`.\n\n### Input Format\nThe first line of input contains four non-negative integers: $n$, $m$, $a_1$, and $a_2$, which represent the size of the dictionary, the number of communication rounds, and the initial values of the parameters `a1` and `a2` used in the `gen` function.\n\nParticipants need to call the `gen` function mentioned in the problem description to generate the dictionary. The function implementation can be copied and used directly from the `gen.cpp` file. In the program, the boolean array `s[N+1][256]` will store all the dictionary words.\n\nThe next $m$ lines each contain a hexadecimal string of length $64$ and a non-negative integer $k_i$, representing the $256$-bit binary string Bob finally received in the $i$-th communication and the noise tolerance threshold.\n\nTo ensure **online querying**, participants must first convert the $64$-character hexadecimal string to a $256$-bit binary string, and then XOR ($\\texttt{exclusive-or}$) each bit with ${\\mathit{lastans}}$. Here, ${\\mathit{lastans}} \\in \\{0, 1\\}$ is the answer to the previous query, with an initial value of ${\\mathit{lastans}} = 0$ before the first query.\n\n**Note:** When using `scanf` or `printf` to handle `unsigned long long` types in C/C++, the format specifier is `llu`.\n\n### Output Format\nThe output should contain $m$ lines, where each line is an integer $0$ or $1$ representing the answer to the current query.\n\n**Example for Queries**\n\nTo better illustrate the problem, consider a simplified example using direct dictionary words, shorter word lengths of $4$, and allowing offline answers for clarity.\n\nConsider a dictionary size $n = 2$ with words `1010` and `0111`.\n\n- For the query `B = 1011` and $k_1 = 1$, the answer should be $1$, as flipping the $4$th bit of `1010` will result in `1011`.\n- For the query `1 = 0001` and $k_2 = 2$, the answer should be $1$, as flipping the $2$nd and $3$rd bits of `0111` will result in `0001`.\n- For the query `1 = 0001` and $k_3 = 1$, the answer should be $0`.\n\nExplanation for $k_3 = 1$: \n- Flipping at most $1$ bit of `1010` results in: `1010`, `0010`, `1110`, `1000`, `1011`. \n- Flipping at most $1$ bit of `0111` results in: `0111`, `1111`, `0011`, `0101`, `0110`. \n- However, `0001` cannot be generated, and it must have been caused by Eve's interference.\n\n### Constraints\nFor all test cases: \n$1 \\leq n \\leq 4 \\times 10^5$, $1 \\leq m \\leq 1.2 \\times 10^5$, $0 \\leq k_i \\leq 15$, and $a_1, a_2$ are chosen uniformly at random within the range $[0, 2^{64} - 1]$.\n\n| Case ID | $n =$ | $m =$ | Max $k_i$ | Special Property |\n|:-:|:-:|:-:|:-:|:-:|\n| 1 | $10$ | $10$ | $2$ | None |\n| 2 | $500$ | $500$ | $15$ | None |\n| 3 | $1000$ | $1000$ | $0$ | None |\n| 4 | $2000$ | $2000$ | $2$ | None |\n| 5 | $5000$ | $5000$ | $15$ | None |\n| 6 | $10^4$ | $10^4$ | $15$ | None |\n| 7 | $2 \\times 10^4$ | $2 \\times 10^4$ | $15$ | None |\n| 8 | $10^5$ | $10^5$ | $1$ | None |\n| 9 | $4 \\times 10^5$ | $1.2 \\times 10^5$ | $1$ | None |\n| 10 | $5 \\times 10^4$ | $5 \\times 10^4$ | $2$ | None |\n| 11 | $7 \\times 10^4$ | $7 \\times 10^4$ | $3$ | None |\n| 12 | $10^5$ | $10^5$ | $2$ | None |\n| 13 | $3 \\times 10^4$ | $3 \\times 10^4$ | $5$ | None |\n| 14 | $6 \\times 10^4$ | $6 \\times 10^4$ | $4$ | None |\n| 15 | $1.2 \\times 10^5$ | $1.2 \\times 10^5$ | $5$ | None |\n| 16 | $6 \\times 10^4$ | $6 \\times 10^4$ | $8$ | All queries randomly generated |\n| 17 | $1.2 \\times 10^5$ | $1.2 \\times 10^5$ | $12$ | All queries randomly generated |\n| 18 | $4 \\times 10^5$ | $10^5$ | $15$ | All queries randomly generated |\n| 19 | $3 \\times 10^4$ | $3 \\times 10^4$ | $7$ | None |\n| 20 | $6 \\times 10^4$ | $6 \\times 10^4$ | $9$ | None |\n| 21 | $9 \\times 10^4$ | $9 \\times 10^4$ | $11$ | None |\n| 22 | $2 \\times 10^5$ | $1.2 \\times 10^5$ | $12$ | None |\n| 23 | $4 \\times 10^5$ | $8 \\times 10^4$ | $15$ | None |\n| 24 | $4 \\times 10^5$ | $10^5$ | $15$ | None |\n| 25 | $4 \\times 10^5$ | $1.2 \\times 10^5$ | $15$ | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3896, "prompt": "### Problem Description\n\nLittle C has decided to plant flowers in his garden to form a pattern that spells \"CCF\". He wants to know how many ways he can plant flowers to form the letter `C` and the letter `F` respectively. Unfortunately, some spots in the garden have pits and cannot be used for planting. He hopes you can help him solve this problem.\n\nThe garden can be viewed as a grid with $n \\times m$ positions, numbered from top to bottom as rows $1$ to $n$, and from left to right as columns $1$ to $m$. Each position may either be a pit or not, denoted by $a_{i, j}$. If $a_{i, j} = 1$, it means the position at row $i$ and column $j$ is a pit and cannot be used for planting; otherwise, if $a_{i, j} = 0$, the position is not a pit and can be planted.\n\nA planting configuration is called a $\\texttt{C-}$**shaped** configuration if there exist $x_1, x_2 \\in [1, n]$ and $y_0, y_1, y_2 \\in [1, m]$ such that:\n\n- $x_1 + 1 < x_2$ \n- $y_0 < y_1, y_2 \\leq m$\n\nand the positions:\n\n1. From column $y_0$ to $y_1$ in row $x_1$,\n2. From column $y_0$ to $y_2$ in row $x_2$, and\n3. From row $x_1$ to $x_2$ in column $y_0$,\n\nare **all free of pits**, and flowers are planted only in these positions.\n\nA planting configuration is called an $\\texttt{F-}$**shaped** configuration if there exist $x_1, x_2, x_3 \\in [1, n]$ and $y_0, y_1, y_2 \\in [1, m]$ such that:\n\n- $x_1 + 1 < x_2 < x_3$ \n- $y_0 < y_1, y_2 \\leq m$\n\nand the positions:\n\n1. From column $y_0$ to $y_1$ in row $x_1$,\n2. From column $y_0$ to $y_2$ in row $x_2$, and\n3. From row $x_1$ to $x_3$ in column $y_0$,\n\nare **all free of pits**, and flowers are planted only in these positions.\n\nThe examples provided explain the patterns formed by $\\texttt{C-}$shaped and $\\texttt{F-}$shaped planting configurations.\n\nGiven $n, m$, and the values of $a_{i, j}$ that indicate which positions are pits, Little C wants to know how many possible configurations of $\\texttt{C-}$shaped and $\\texttt{F-}$shaped plantings exist. Since the results could be very large, you only need to output the results modulo $998244353$ as specified in the output format section.\n\n### Input Format\n\nThe first line contains two integers $T$ and $id$, representing the number of test cases and the test point number respectively. If the input is an example case, $id = 0$.\n\nFor each of the $T$ test cases:\n\n- The first line contains four integers $n, m, c, f$, where $n$ and $m$ represent the number of rows and columns of the garden. The meanings of $c$ and $f$ are explained in the output format section.\n- The next $n$ lines each contain a string of length $m$ consisting of only `0` and `1`. The $j$-th character in the $i$-th string denotes $a_{i, j}$, indicating whether row $i$ and column $j$ is a pit or not (`1` for a pit, `0` otherwise).\n\n### Output Format\n\nLet $V_C$ and $V_F$ be the number of $\\texttt{C-}$shaped and $\\texttt{F-}$shaped planting configurations in the garden respectively. For each test case, output one line with two non-negative integers separated by a space:\n\n- $(c \\times V_C) \\bmod 998244353$, $(f \\times V_F) \\bmod 998244353$,\n\nwhere $a \\bmod P$ represents the result of $a$ modulo $P$.\n\n### **Example Explanation**\n\nFor the first example, there are four $\\texttt{C-}$shaped planting configurations:\n\n```plain\n**1 **1 **1 **1\n*10 *10 *10 *10\n**0 *** *00 *00\n000 000 **0 ***\n```In the visualizations, `*` marks the positions where flowers are planted. Note that the two horizontal lines of the letter `C` can have different lengths.\n\nSimilarly, there are two $\\texttt{F-}$shaped planting configurations:\n\n```plain\n**1 **1\n*10 *10\n**0 ***\n*00 *00\n```\n\n### **Example 2**\n\nSee the files `plant/plant2.in` and `plant/plant2.ans`.\n\n### **Example 3**\n\nSee the files `plant/plant3.in` and `plant/plant3.ans`.\n\n### **Constraints**\n\nFor all the test cases, the following conditions are guaranteed:\n\n- $1 \\leq T \\leq 5$\n- $1 \\leq n, m \\leq 10^3$\n- $0 \\leq c, f \\leq 1$\n- $a_{i, j} \\in \\{0, 1\\}$\n\n| Test Point ID | $n$ | $m$ | $c$ | $f$ | Special Properties | Test Point Value |\n| :----------: | :----------: | :----------: | :----------: | :----------: | :----------: | :----------: |\n| $1$ | $\\leq 1000$ | $\\leq 1000$ | $0$ | $0$ | None | $1$ |\n| $2$ | $=3$ | $=2$ | $1$ | $1$ | None | $2$ |\n| $3$ | $=4$ | $=2$ | $1$ | $1$ | None | $3$ |\n| $4$ | $\\leq 1000$ | $=2$ | $1$ | $1$ | None | $4$ |\n| $5$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $1$ | A | $4$ |\n| $6$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $1$ | B | $6$ |\n| $7$ | $\\leq 10$ | $\\leq 10$ | $1$ | $1$ | None | $10$ |\n| $8$ | $\\leq 20$ | $\\leq 20$ | $1$ | $1$ | None | $6$ |\n| $9$ | $\\leq 30$ | $\\leq 30$ | $1$ | $1$ | None | $6$ |\n| $10$ | $\\leq 50$ | $\\leq 50$ | $1$ | $1$ | None | $8$ |\n| $11$ | $\\leq 100$ | $\\leq 100$ | $1$ | $1$ | None | $10$ |\n| $12$ | $\\leq 200$ | $\\leq 200$ | $1$ | $1$ | None | $6$ |\n| $13$ | $\\leq 300$ | $\\leq 300$ | $1$ | $1$ | None | $6$ |\n| $14$ | $\\leq 500$ | $\\leq 500$ | $1$ | $1$ | None | $8$ |\n| $15$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $0$ | None | $6$ |\n| $16$ | $\\leq 1000$ | $\\leq 1000$ | $1$ | $1$ | None | $14$ |\n\nSpecial Property A: $\\forall 1 \\leq i \\leq n, 1 \\leq j \\leq \\left\\lfloor \\frac{m}{3} \\right\\rfloor$, $a_{i, 3j} = 1$.\n\nSpecial Property B: $\\forall 1 \\leq i \\leq \\left\\lfloor \\frac{n}{4} \\right\\rfloor, 1 \\leq j \\leq m$, $a_{4i, j} = 1$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "medium"} +{"id": 2718, "prompt": "### Problem Description\n\n> This story takes place in the City of Magic, where we will introduce some necessary settings.\n>\n> The City of Magic can be abstracted as an **undirected connected graph** with $n$ nodes and $m$ edges (nodes are numbered from $1$ to $n$). Each edge is described by its **length** $l$ and **altitude** $a$.\n>\n> As a representative city of monsoon climates, the City of Magic is often accompanied by rain, which makes water accumulation on roads inevitable. Due to the interconnected nature of the city\u2019s drainage system, **edges with water accumulation are always those with the lowest altitudes.**\n>\n> We use a **waterline** to describe the degree of rain. Its meaning is: all edges with altitude **not exceeding** the waterline are considered to have **water accumulation.**\n\nYazid is an OIer from the City of Magic. After participating in ION2018, he is on his way home to return to his cozy residence.\n\nYazid's home happens to be located at node $1$ in the City of Magic. For the next $Q$ days, Yazid will provide his **starting point** $v$ and the **waterline** $p$ for each day.\n\nEach day, Yazid has a **car** at his starting point. Due to a malfunction, the car cannot traverse edges with water accumulation.\n\nYazid can get off the car at any node, after which he can walk through edges with water accumulation. However, the car will remain parked at the node where it was left and will no longer be used.\n\n+ Special notes about the car reset for subsequent days:\n + A new car will be prepared for Yazid at the next starting point.\n + Yazid cannot use cars left at other locations from previous days.\n\nYazid dislikes walking in the rain, so he wants to minimize the **total length of edges walked** while still achieving the goal of getting home. Please help Yazid calculate this.\n\n**Some test cases for this problem will be forced to run in an online manner. Please refer to the \"Input Format\" and \"Subtasks\" sections for specific details.**\n\n---\n\n### Input Format\n\nThe input is read from the file `return.in`.\n\nEach test case contains multiple datasets. The first line is a non-negative integer $T$, indicating the number of datasets.\n\nThe description of each dataset is as follows:\n\n+ The first line contains two non-negative integers $n$ and $m$, representing the number of nodes and the number of edges.\n+ The following $m$ lines describe the edges. Each line contains four positive integers $u, v, l, a$, representing an edge connecting node $u$ and node $v$ with a **length** of $l$ and an **altitude** of $a$.\n + It is guaranteed that $1 \\leq u, v \\leq n$.\n+ The next line contains three non-negative integers $Q, K, S$, where:\n + $Q$ represents the number of days,\n + $K \\in \\{0, 1\\}$ is a coefficient used in defining daily parameters,\n + $S$ is the maximum possible value of the waterline.\n+ The next $Q$ lines describe the conditions for each day. Each line contains two integers, $v_0$ and $p_0$, which define the day's parameters:\n + The starting point for the day is calculated as $v = (v_0 + K \\times \\text{lastans} - 1) \\bmod n + 1$.\n + The waterline for the day is calculated as $p = (p_0 + K \\times \\text{lastans}) \\bmod (S + 1)$.\n + Here, $\\text{lastans}$ represents the answer (minimum total walking distance) for the previous day. For the first day, it is predefined as $\\text{lastans} = 0$.\n + It is guaranteed that $1 \\leq v_0 \\leq n$ and $0 \\leq p_0 \\leq S$.\n\nIn input lines with multiple numbers, the numbers are separated by single spaces.\n\n---\n\n### Output Format\n\nThe output is written to the file `return.out`.\n\nOutput the result for each dataset sequentially. For each dataset:\n\n+ Print $Q$ lines, with each line containing one integer representing the minimum total walking distance for the corresponding day.\n\n---\n\n### Example Input and Output\n\n#### Example 1\n\n**Input:**\n\n```plaintext\n1\n4 4\n1 2 1 1\n2 3 1 2\n1 3 3 4\n3 4 2 2\n5 0 3\n2 0\n4 2\n4 2\n4 3\n4 3\n```**Output:**\n\n```plaintext\n0\n3\n4\n1\n6\n```\n\n**Explanation:**\n\n- On Day 1, there is no rain, and Yazid can drive directly home.\n- On Days 2, 3, and 4, the same edges accumulate water: the edge connecting nodes $1$ and $2$, and the edge connecting nodes $3$ and $4$.\n * On Day 2, starting at node $2$, Yazid can only drive to node $3$, which is unhelpful. He must walk back home entirely.\n * On Day 3, starting at node $4$, all edges connected to it are submerged, so the car is useless. He must walk home entirely.\n * On Day 4, Yazid can drive to node $2$ first and then walk home.\n- On Day 5, all edges are submerged, forcing Yazid to walk the entire way home.\n\n#### Example 2\n\n**Input:**\n\n```plaintext\n1\n5 6\n1 2 1 1\n1 3 2 0\n2 4 2 2\n3 4 3 0\n3 5 4 1\n4 5 5 3\n4 1 3\n5 2\n2 0\n0 0\n3 0\n```\n\n**Output:**\n\n```plaintext\n0\n2\n3\n5\n```\n\n---\n\n### Constraints and Notes\n\n**All test cases guarantee $T \\leq 3$. Input data across all test cases satisfy the following constraints:**\n\n+ $n \\leq 2 \\times 10^5$, $m \\leq 4 \\times 10^5$, $Q \\leq 4 \\times 10^5$, $K \\in \\{0, 1\\}$, and $1 \\leq S \\leq 10^9$.\n+ For all edges: $l \\leq 10^4$, $a \\leq 10^9$.\n+ Any two nodes are directly or indirectly connected via edges.\n\n---\n\n### Additional Details\n\nFor easier understanding, we use some simplified explanations in tables. These are formalized as follows:\n\n+ Shape of the graph:\n * When labeled as \u201ca tree\u201d or \u201ca chain,\u201d it means $m = n - 1$. Additionally:\n - \u201cTree\u201d: The graph structure contains no cycles.\n - \u201cChain\u201d: Requires all edges to satisfy $u + 1 = v$.\n+ Altitude:\n * If labeled as \u201cuniform,\u201d all edges satisfy $a = 1$.\n+ Forcing online:\n * When labeled as \u201cyes,\u201d $K = 1$; otherwise, $K = 0$.\n+ If labeled as \u201cnot guaranteed,\u201d no assumptions are made.\n\n| $n$ | $m$ | $Q =$ | Test Case | Graph Type | Altitude | Force Online |\n|-------|-----------------|----------|-----------|------------|------------|--------------|\n| $\\leq 1$ | $\\leq 0$ | $0$ | 1 | Not guaranteed | Uniform | No |\n| $\\leq 6$ | $\\leq 10$ | $10$ | 2 | Not guaranteed | Uniform | No |\n| $\\leq 50$ | $\\leq 150$ | $100$ | 3 | Not guaranteed | Uniform | No |\n| $\\leq 100$ | $\\leq 300$ | $200$ | 4 | Not guaranteed | Uniform | No |\n| $\\leq 1500$| $\\leq 4000$ | $2000$ | 5 | Not guaranteed | Uniform | No |\n| $\\leq 200000$ | $\\leq 400000$ | $100000$ | 6 | Not guaranteed | Uniform | No |\n| $\\leq 1500$| $= n - 1$ | $2000$ | 7 | Chain | Not guaranteed | No |\n| $\\leq 1500$| $= n - 1$ | $2000$ | 8 | Chain | Not guaranteed | No |\n| $\\leq 1500$| $= n - 1$ | $2000$ | 9 | Chain | Not guaranteed | No |\n| $\\leq 200000$| $= n - 1$ | $100000$ | 10 | Tree | Not guaranteed | No |\n| $\\leq 200000$| $= n - 1$ | $100000$ | 11 | Tree | Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 12 | Not guaranteed| Not guaranteed | No |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 13 | Not guaranteed| Not guaranteed | No |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 14 | Not guaranteed| Not guaranteed | No |\n| $\\leq 1500$| $\\leq 4000$ | $2000$ | 15 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 1500$| $\\leq 4000$ | $2000$ | 16 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 17 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $100000$ | 18 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $400000$ | 19 | Not guaranteed| Not guaranteed | Yes |\n| $\\leq 200000$| $\\leq 400000$ | $400000$ | 20 | Not guaranteed| Not guaranteed | Yes |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3852, "prompt": "### Problem Description\n\nIn this problem, you need to solve a well-known NP problem \u2014 the Quadratic Integer Programming Problem.\n\nThe Quadratic Integer Programming Problem has variables: You are required to produce an **integer** sequence of length $n$, denoted as $(x_1, x_2, \\ldots, x_n)$, that satisfies all of the following conditions.\n\nThe Quadratic Integer Programming Problem has constraints: The integer sequence you provide must satisfy the following two types of constraints:\n\n1. **Constraints on individual variables:** Given a positive integer $k$ ($3 \\leq k \\leq 5$) and $n$ intervals $[l_i, r_i]$ ($1 \\leq i \\leq n$), where $1 \\leq l_i \\leq r_i \\leq k$, the sequence must satisfy $\\forall 1 \\leq i \\leq n$, $l_i \\leq x_i \\leq r_i$.\n2. **Constraints between variables:** Given $m$ triplets $(p_j, q_j, b_j)$, the sequence must satisfy $\\forall 1 \\leq j \\leq m$, $\\lvert x_{p_j} - x_{q_j} \\rvert \\leq b_j$.\n\nThe Quadratic Integer Programming Problem has an objective function: Given $k-2$ objective parameters $v_2,v_3,\\dots,v_{k-1}$ (**note that the subscript range is $\\boldsymbol{2}$ to $\\boldsymbol{k-1}$**), for an integer sequence $\\{p_1,p_2,\\ldots,p_n\\}$ with values in the domain $[1, k]$, let $c_i$ denote the number of elements in this sequence that are equal to $i$, and let $G$ denote the number of integer pairs $(i, j)$ that satisfy $1 \\leq i, j \\leq n$ and $\\lvert p_i - p_j \\rvert \\leq 1$. **Note that when $\\boldsymbol{i \\neq j}$, $\\boldsymbol{(i, j)}$ and $\\boldsymbol{(j, i)}$ are different pairs.** The **weight** of this sequence is defined as:\n\n$$\nW(p_1, p_2, \\ldots, p_n) = 10^6 G + \\sum_{i=2}^{k-1} c_i v_i \\text{.}\n$$\n\nYour sequence needs to maximize its weight while satisfying the two types of constraints. Under the given constraints, it is guaranteed that there exists at least one sequence that satisfies the constraints.\n\nThe Quadratic Integer Programming Problem may involve multiple queries. For each query, you will be provided with different objective parameters $v_2, v_3, \\ldots, v_{k-1}$. For each query, you need to find a sequence that maximizes its weight under the given constraints. To reduce output size, you only need to output the weight of the sequence.\n\n### Input Format\n**This problem contains multiple test cases.** The first line contains a non-negative integer and a positive integer $C, T$, representing the test case ID and the number of test cases. $C = 0$ indicates that this group of data is a sample.\n\nFor each test case, the first line contains four integers $k, n, m, q$, specifying the domain of the sequence values, the length of the sequence, the number of constraints between variables, and the number of queries.\n\nThe next $n$ lines each contain two integers $l_i, r_i$, describing the value range of each element in the sequence.\n\nThe next $m$ lines each contain three integers $p_j, q_j, b_j$, describing one constraint between variables.\n\nThe next $q$ lines each contain $k - 2$ non-negative integers $v_2, v_3, \\ldots, v_{k - 1}$, describing the weight parameters for a query.\n\n### Output Format\nFor each query of each test case, output a single integer in a line, representing the maximum weight of the sequence.\n\n---\n\n### **Sample \\#1**\n\nSee the files `qip/qip1.in` and `qip/qip1.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $1$ in the data range.\n\n---\n\n**Sample Explanation \\#1**\n\nIn the first test case, the optimal sequence for both queries is $(1, 2, 2, 1, 3)$, where $c_2 = 2$ and $G = 21$.\n\n---\n\n### **Sample \\#2**\n\nSee the files `qip/qip2.in` and `qip/qip2.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $3$ in the data range.\n\n---\n\n**Sample Explanation \\#2**\n\nIn the first test case, the optimal sequences for the two queries are $(4, 4, 3, 3)$ and $(4, 3, 2, 2)$, respectively.\n\n---\n\n### **Sample \\#3**\n\nSee the files `qip/qip3.in` and `qip/qip3.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $5$ in the data range.\n\n---\n\n**Sample Explanation \\#3**\n\nIn the first test case, the optimal sequences for the three queries are $(3, 3, 3, 3, 3)$, $(2, 2, 3, 3, 2)$, and $(3, 2, 4, 4, 2)$, respectively.\n\n---\n\n### **Sample \\#4**\n\nSee the files `qip/qip4.in` and `qip/qip4.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $2$ in the data range.\n\n---\n\n### **Sample \\#5**\n\nSee the files `qip/qip5.in` and `qip/qip5.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $4$ in the data range.\n\n---\n\n### **Sample \\#6**\n\nSee the files `qip/qip6.in` and `qip/qip6.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $8$ in the data range.\n\n---\n\n### **Sample \\#7**\n\nSee the files `qip/qip7.in` and `qip/qip7.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $14$ in the data range.\n\n---\n\n### **Sample \\#8**\n\nSee the files `qip/qip8.in` and `qip/qip8.ans` in the attachments.\n\nThis sample satisfies the characteristics of test point $17$ in the data range.\n\n---\n\n### **Data Constraints**\n\nLet $\\sum q$ denote the total number of queries for all test cases in a single test point. For all test points:\n\n- $1 \\leq T \\leq 600$,\n- For the $i$-th ($1 \\leq i \\leq T$) test case, $1 \\leq n \\leq \\max(\\frac{T}{i}, 2 \\log_2 T)$,\n- $3 \\leq k \\leq 5$, $0 \\leq m \\leq 3n$, $1 \\leq q, \\sum q \\leq 3 \\times 10^5$,\n- $1 \\leq l_i \\leq r_i \\leq k$,\n- $1 \\leq p_j, q_j \\leq n$, $0 \\leq b_j < k$,\n- $0 \\leq v_2, \\dots, v_{k-1} \\leq 10^{12}$.\n\n| Test Point ID | $T \\leq$ | $k=$ | $\\sum q \\leq$ | Special Properties | Points |\n|:-------------:|:--------:|:----:|:-------------------:|:------------------:|:------:|\n| $1$ | $10$ | $3$ | $200$ | None | $4$ |\n| $2$ | $600$ | $3$ | $3 \\times 10^5$ | None | $6$ |\n| $3$ | $10$ | $4$ | $200$ | None | $4$ |\n| $4$ | $600$ | $4$ | $3 \\times 10^5$ | None | $6$ |\n| $5$ | $10$ | $5$ | $300$ | None | $5$ |\n| $6$ | $15$ | $5$ | $500$ | None | $4$ |\n| $7$ | $25$ | $5$ | $750$ | None | $4$ |\n| $8$ | $50$ | $5$ | $1000$ | None | $6$ |\n| $9$ | $80$ | $5$ | $1500$ | None | $6$ |\n| $10$ | $120$ | $5$ | $2000$ | None | $5$ |\n| $11$ | $200$ | $5$ | $8000$ | A | $3$ |\n| $12$ | $400$ | $5$ | $3 \\times 10^4$ | A | $4$ |\n| $13$ | $600$ | $5$ | $2 \\times 10^5$ | A | $5$ |\n| $14$ | $200$ | $5$ | $8000$ | B | $3$ |\n| $15$ | $400$ | $5$ | $3 \\times 10^4$ | B | $4$ |\n| $16$ | $600$ | $5$ | $2 \\times 10^5$ | B | $4$ |\n| $17$ | $120$ | $5$ | $10^5$ | C | $4$ |\n| $18$ | $150$ | $5$ | $2 \\times 10^5$ | C | $5$ |\n| $19$ | $180$ | $5$ | $3 \\times 10^5$ | C | $5$ |\n| $20$ | $300$ | $5$ | $5 \\times 10^4$ | None | $5$ |\n| $21$ | $450$ | $5$ | $10^5$ | None | $4$ |\n| $22$ | $600$ | $5$ | $3 \\times 10^5$ | None | $4$ |\n\n### Special Properties\n\n- **Property A**: $m = 0$.\n- **Property B**: $m \\leq 10$, and the total of $m$ across all test cases in a single test point does not exceed $200$.\n- **Property C**: Data generated randomly as follows:\n - During dataset generation, given parameters $k, n, m, q$ and $k$ non-negative constants $p_0, p_1, p_2, \\dots, p_{k-1}$, where $p_{k-1} \\neq 0$:\n - For $1 \\leq i \\leq n$, independently generate $x, y \\in [1, k]$ uniformly at random. Then $l_i = \\min(x, y)$, and $r_i = \\max(x, y)$.\n - Continue generating triplets as follows until $m$ triplets are produced:\n 1. Randomly generate $u, v \\in [1, n]$ uniformly.\n 2. Randomly generate $w$ with the probabilities defined over $p$ (for $0 \\leq i \\leq k-1$, $w = i$ with probability $\\frac{p_i}{p_0 + p_1 + \\dots + p_{k-1}}$).\n 3. If adding $(u, v, w)$ to the existing set of triplets causes no sequence $(x_1, x_2, \\dots, x_n)$ to satisfy all constraints, discard this triplet; otherwise, include it.\n - Each query\u2019s $v_2, \\ldots, v_{k-1}$ is independently generated uniformly at random in the range $[0, 10^{12}]$.\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"} +{"id": 3343, "prompt": "### Problem Description\n$\\mathbf{X1}$: Let me translate the message content.\n\n> Definition: Trees described in this context are inductively defined: a single node constitutes a tree; a tree with another tree as its left (or right) child constitutes a tree; a tree with two trees as its left and right children also constitutes a tree. Any structure generated using these rules in a finite number of steps is called a tree.\n\n$\\mathbf{X2}$: In other words, the trees discussed here refer to **non-empty, rooted, binary trees with distinct left and right children**.\n\n$\\mathbf{X1}$: Exactly. Next, the book defines isomorphism between two trees.\n\n> Definition: Two trees $T$, $T^{\\prime}$ are said to be isomorphic, denoted as $T \\equiv T^{\\prime}$, which is defined by the following four rules:\n> 1. Trees consisting of a single node are mutually isomorphic;\n> 2. If the roots of two trees both have only left subtrees, and their left subtrees are isomorphic, then the two trees are isomorphic;\n> 3. If the roots of two trees both have only right subtrees, and their right subtrees are isomorphic, then the two trees are isomorphic;\n> 4. If the roots of two trees have both left and right subtrees, and their left and right subtrees correspondingly are isomorphic, then the two trees are isomorphic.\n>\n> Obviously, the isomorphic relation forms an equivalence relation among all trees. For convenience, we treat isomorphic trees as identical.\n\n$\\mathbf{X2}$: Treating isomorphic trees as identical means the nodes of such trees are equivalent. Simply put, two trees are isomorphic if and only if **they are identical in terms of node arrangement without labels, while distinguishing left and right children**; we say two trees are different if and only if they are not isomorphic.\n\n$\\mathbf{X1}$: The book also defines **leaves**: as in the usual definition, leaves refer to **nodes that have no children**.\n\n$\\mathbf{X2}$: This is completely consistent with the definition we are familiar with. Mathematicians really are a bit verbose... I bet only $\\mathbf{X3}$ would like this kind of approach.\n\n$\\mathbf{X1}$: I don\u2019t really mind this \u2014 compared to an intuition based on experience, precise definitions and rigorous proofs are much more reassuring. Look, the next definition is not as intuitive.\n\n> Definition: A tree $T$ is said to be **replaced in one step** by another tree $T^{\\prime}$ if replacing one **leaf node** of $T$ with another tree $T^{\\prime \\prime}$ results in a tree isomorphic to $T^{\\prime}$, denoted as $T \\rightarrow T^{\\prime}$; a tree $T$ is said to be **replaced** by $T^{\\prime}$, denoted as $T \\rightarrow^{\\star} T^{\\prime}$, if there exists a natural number $n \\geq 1$ and trees $T_{1}, T_{2}, \\ldots, T_{n}$ such that $T \\equiv T_{1} \\rightarrow T_{2} \\rightarrow \\cdots \\rightarrow T_{n} \\equiv T^{\\prime}$.\n\n$\\mathbf{X2}$: Let me think... Replacement means deleting a leaf node and placing another tree in its position, as if the leaf node \"grows\" into a larger subtree. To say one tree replaces another means it can be obtained through **zero, one, or multiple single-step replacements**. Oh... I get it now! For example, any tree can be replaced with itself, meaning for a tree $T$, $T \\rightarrow^{\\star} T^{\\prime}$ always holds. The following image helps to understand the concepts of single-step replacement and replacement.\n\n![img](https://cdn.luogu.com.cn/upload/image_hosting/0o4pfqui.png)\n\n$\\mathbf{X1}$: You are correct. Specifically, any tree can replace itself with infinitely many distinct trees, and a tree consisting only of a single node can replace itself with any other tree. This is also defined in the book.\n\n> Definition: For a tree $T$, define $\\operatorname{grow}(T)$ as the set of all trees that $T$ can replace itself to form, i.e., $\\operatorname{grow}(T)=\\left\\{T^{\\prime} \\mid T \\rightarrow^{\\star} T^{\\prime}\\right\\}$. Moreover, if $\\mathscr{T}=\\left\\{T_{1}, T_{2}, \\ldots, T_{n}\\right\\}$ is a finite set of trees, $\\operatorname{grow}(\\mathscr{T})$ is defined as the union of all $\\operatorname{grow}\\left(T_{i}\\right)$, where $i=1,2, \\ldots, n$. That is,\n> $$\\operatorname{grow}(\\mathscr{T})=\\bigcup_{T_{i} \\in \\mathscr{T}} \\operatorname{grow}\\left(T_{i}\\right)$$\n\n$\\mathbf{X2}$: Let\u2019s call $\\operatorname{grow}(\\mathscr{T})$ the **growth set of tree set $\\mathscr{T}$** \u2014 in other words, the growth set $\\operatorname{grow}(\\mathscr{T})$ contains all the trees that can be obtained by replacing any tree $T \\in \\mathscr{T}$. Let\u2019s refer to a set of trees as a **forest**. Informally, a new forest formed by the growth of an existing forest includes all trees obtained by every tree in the original forest growing in all possible ways. Clearly, the new forests grown from a non-empty forest are always infinite. However, this infinite forest, namely $\\operatorname{grow}(\\mathscr{T})$, does not necessarily include all trees \u2014 furthermore, it may not even include \"almost all\" trees.\n\n$\\mathbf{X1}$: Let me supplement: A forest is considered **almost complete** (or **almost includes all trees**) if only finitely many trees are excluded from it. For a finite forest $\\mathscr{T}$, $\\operatorname{grow}(\\mathscr{T})$ either includes all trees, includes almost all trees, or excludes infinitely many trees. If this were an OI problem, the problem setter would likely **provide examples of all three cases in the test cases**. The key theorem in the book uses the same definitions.\n\n> **Theorem** (**Decidability of Almost Completeness**): A set of trees is **almost complete** if it excludes only finitely many trees. For a given finite set of trees $\\mathscr{T}$, there exists an efficient algorithm to determine whether $\\operatorname{grow}(\\mathscr{T})$ is almost complete.\n\n$\\mathbf{X2}$: This problem has become a pure OI problem! Let me restate the problem: **Given a finite forest $\\mathscr{T}$, determine whether $\\operatorname{grow}(\\mathscr{T})$ is almost complete, i.e., whether only finitely many trees cannot be grown from the trees in the forest**.\n\n$\\mathbf{X1}$: In other words, given a finite set of trees $\\mathscr{T}$, determine whether only finitely many trees $T$ satisfy $T \\notin \\operatorname{grow}(\\mathscr{T})$. The condition $T \\notin \\operatorname{grow}(\\mathscr{T})$ means there does not exist $T^{\\prime} \\in \\mathscr{T}$ such that $T^{\\prime} \\rightarrow^{\\star} T$. This problem is indeed very different from typical OI problems: I cannot even think of an algorithm for this problem.\n\n$\\mathbf{X2}$: Same here, but this gives me a thrilling urge to solve an unknown problem.\n\n---\n\n### Input Format\nThis problem has multiple test cases. The first line of the input contains a positive integer $N$, indicating the number of test cases. The following are exactly the $N$ test cases, each with the following format:\n\nThe first line contains a positive integer $m$, denoting the number of trees in the set. Then, $m$ trees are described in the following format:\n- First, a positive integer $n$, indicating the number of nodes in the tree. Nodes are numbered $1, 2, \\ldots, n$;\n- Following this are $n$ lines, each containing two non-negative integers. The $i$-th line contains $l_i$ and $r_i$, respectively representing the node numbers of the left and right children of node $i$. If a left (or right) child does not exist, then $l_i$ (or $r_i$) is $0$. A leaf node satisfies $l_i = r_i = 0$.\n- The input is guaranteed to form a tree with node $1$ as the root. **Note**: Node numbers are for input convenience; any isomorphic trees are considered identical.\n\nAmong the $m$ input trees, there may be pairs of isomorphic trees; after removing duplicates (i.e., keeping only one of each isomorphic tree), they form a tree set $\\mathscr{T}$. You are required to determine whether the growth set $\\operatorname{grow}(\\mathscr{T})$ is almost complete.\n\n---\n\n### Output Format\nThe output contains $N$ lines corresponding to the answers for the $N$ test cases. For the $i$-th test case, output a string: if the growth set of the forest from the $i$-th test case is almost complete (i.e., only finitely many trees cannot be grown from the forest), output `Almost Complete`; otherwise, output `No`. **Pay attention to the spelling and case of the output strings**.\n\n#### Sample Case 2 Explanation\nThis example contains only one test case, in which the forest $\\mathscr{T}$ includes three trees, as shown below. It is easy to find that only a single-node tree is not included in $\\operatorname{grow}(\\mathscr{T})$, and $\\operatorname{grow}(\\mathscr{T})$ almost contains all trees, making it almost complete.\n\n![img2](https://cdn.luogu.com.cn/upload/image_hosting/394s081s.png)\n\n#### Sample Case 3 Explanation\nThis example contains only one test case, in which the forest $\\mathscr{T}$ includes two trees. It is easy to find that for any $n \\geq 2$, chain-like trees containing $n$ nodes where each non-leaf node has only a right child are excluded from $\\operatorname{grow}(\\mathscr{T})$. Hence, infinitely many trees are excluded from $\\operatorname{grow}(\\mathscr{T})$, and $\\mathscr{T}$ is not almost complete.\n\n#### Sample Case 4\nRefer to the player directory under surreal/surreal4.in and surreal/surreal4.ans.\n\n---\n\n### Constraints on Test Cases\n\n**All test cases satisfy**: $\\sum n \\leq 2 \\times 10^{6}$, $\\sum m \\leq 2 \\times 10^{6}$, $\\max h \\leq 2 \\times 10^{6}$, $N \\leq 10^{2}$. Here, $\\sum n$, $\\sum m$, and $\\max h$ have the following meanings:\n- $\\sum n$: The total number of nodes across all trees in all test cases.\n- $\\sum m$: The total number of trees across all test cases.\n- $\\max h$: The maximum height among all trees in the test cases (a single-node tree has a height of $1$).\n\nBelow is a summary of the constraints for each test case group:\n\n| Case Set | $N$ | $\\sum n$ | $\\sum m$ | $\\max h$ | Special Constraints |\n| :-: | :-: | :-: | :-: | :-: |:-: |\n| $1$ | $100$ | $\\le 10^3$ | $\\le 10^3$ | $\\leq 1$ | None |\n| $2 \\sim 3$ | $100$ | $\\le 10^3$ | $\\le 10^3$ | $\\leq 2$ | Property $1$ |\n| $4$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 4$ | None | \n| $5$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 5$ | Property $2$ | \n| $6$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 8$ | None | \n| $7$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 9$ | Property $2$ | \n| $8$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 10$ | None | \n| $9$ | $100$ | $\\le 10^6$ | $\\le 10^6$ | $\\leq 10^6$ | Property $3$ | \n| $10$ | $20$ | $\\le 10^3$ | $\\le 100$ | $\\leq 10^3$ | Property $4$ | \n| $11$ | $20$ | $\\le 2\\times 10^3$ | $\\le 2\\times 10^3$ | $\\leq 2\\times 10^3$ | Property $4$ | \n| $12$ | $20$ | $\\le 10^5$ | $\\le 10^5$ | $\\leq 10^5$ | Property $4$ | \n| $13$ | $20$ | $\\le 2\\times 10^5$ | $\\le 2\\times 10^5$ | $\\leq 2\\times 10^5$ | Property $4$ | \n| $14$ | $20$ | $\\le 800$ | $\\le 200$ | $\\leq 800$ | None |\n| $15$ | $20$ | $\\le 10^3$ | $\\le 100$ | $\\leq 10^3$ | None |\n| $16$ | $20$ | $\\le 2\\times 10^3$ | $\\le 2\\times 10^3$ | $\\leq 2\\times 10^3$ | None |\n| $17$ | $40$ | $\\le 3\\times 10^5$ | $\\le 3\\times 10^5$ | $\\leq 3\\times 10^5$ | None |\n| $18$ | $40$ | $\\le 6\\times 10^5$ | $\\le 6\\times 10^5$ | $\\leq 6\\times 10^5$ | None |\n| $19$ | $40$ | $\\le 9\\times 10^5$ | $\\le 9\\times 10^5$ | $\\leq 9\\times 10^5$ | None |\n| $20$ | $40$ | $\\le 1.2\\times 10^6$ | $\\le 1.2\\times 10^6$ | $\\leq 1.2\\times 10^6$ | None |\n| $21$ | $40$ | $\\le 1.5\\times 10^6$ | $\\le 1.5\\times 10^6$ | $\\leq 1.5\\times 10^6$ | None |\n| $22 \\sim 25$ | $40$ | $\\leq 2\\times 10^6$ | $\\leq 2\\times 10^6$ | $\\leq 2\\times 10^6$ | None |\n\nPlease reason step by step about the solution, then provide a complete implementation in C++17. Use standard input/output. Enclose your code within delimiters as follows.\n```cpp\n\n```\n\n### Answer: (use the provided format with backticks)\n\n", "dataset": "NOI", "language": "cpp", "difficulty": "hard"}